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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Push ONNX artifacts + tokenizer assets to a HF Hub model repo.
|
| 2 |
+
|
| 3 |
+
Usage:
|
| 4 |
+
uv run python upload_to_hf.py --repo onnx-community/needle-onnx
|
| 5 |
+
|
| 6 |
+
Uploads:
|
| 7 |
+
encoder.onnx — Needle encoder
|
| 8 |
+
decoder_step.onnx — Needle one-step decoder with KV cache I/O
|
| 9 |
+
needle.model — SentencePiece BPE model file (vocab=8192, byte_fallback)
|
| 10 |
+
tokenizer-specials.json — pad/eos/bos/<tool_call>/<tools> token IDs
|
| 11 |
+
README.md — model card with provenance and parity numbers
|
| 12 |
+
"""
|
| 13 |
+
import argparse
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
from huggingface_hub import HfApi, create_repo
|
| 16 |
+
|
| 17 |
+
ART = Path(__file__).resolve().parent / "artifacts"
|
| 18 |
+
WEB_DEV = Path(__file__).resolve().parent.parent / "web" / "public" / "models-dev"
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
README = """---
|
| 22 |
+
license: mit
|
| 23 |
+
tags:
|
| 24 |
+
- onnx
|
| 25 |
+
- function-calling
|
| 26 |
+
- needle
|
| 27 |
+
- cactus
|
| 28 |
+
- browser
|
| 29 |
+
- sentencepiece
|
| 30 |
+
base_model: Cactus-Compute/needle
|
| 31 |
+
library_name: onnxruntime
|
| 32 |
+
---
|
| 33 |
+
|
| 34 |
+
# Needle — ONNX export for in-browser inference
|
| 35 |
+
|
| 36 |
+
Browser-ready ONNX export of [Cactus-Compute/needle](https://huggingface.co/Cactus-Compute/needle), a 26M-parameter function-calling model. Designed to run entirely client-side via `onnxruntime-web` (WASM backend) — no server required.
|
| 37 |
+
|
| 38 |
+
## Files
|
| 39 |
+
|
| 40 |
+
| File | Description | Size |
|
| 41 |
+
|---|---|---|
|
| 42 |
+
| `encoder.onnx` | Needle encoder. Input `input_ids:(B,T)`, output `encoder_out:(B,T,512)`. Single-pass. | ~55 MB |
|
| 43 |
+
| `decoder_step.onnx` | One decoder step with explicit past-KV in / present-KV out. Run in a JS loop. | ~85 MB |
|
| 44 |
+
| `needle.model` | SentencePiece BPE protobuf (vocab=8192, `byte_fallback=True`, `identity` normalization). Loadable by `sentencepiece-js` / `@huggingface/transformers`. | 125 KB |
|
| 45 |
+
| `tokenizer-specials.json` | `{"pad":0,"eos":1,"bos":2,"tool_call":4,"tools":5}` | tiny |
|
| 46 |
+
|
| 47 |
+
## Origin
|
| 48 |
+
|
| 49 |
+
The upstream Cactus Needle is implemented in **JAX/Flax**, not PyTorch — `torch.onnx.export` cannot run against the upstream model directly. This ONNX export was produced via a "port-and-copy" pipeline:
|
| 50 |
+
|
| 51 |
+
1. Reimplemented the Simple Attention Network in PyTorch (parametric on `TransformerConfig`)
|
| 52 |
+
2. Copied weights tensor-by-tensor from the upstream Flax checkpoint (handling Flax `(in, out)` → PyTorch `(out, in)` transposition for Linear kernels and the `nn.scan` layer-stacking convention)
|
| 53 |
+
3. Verified Flax↔PyTorch parity at `<1e-3` max-abs-diff
|
| 54 |
+
4. Exported encoder + decoder-step to ONNX via legacy TorchScript-based `torch.onnx.export`
|
| 55 |
+
5. Verified PyTorch↔ONNX parity at `<1e-3`
|
| 56 |
+
6. Verified end-to-end: Cactus's native `generate()` and a hand-rolled `onnxruntime` KV-cache loop produce **byte-identical** output token sequences
|
| 57 |
+
|
| 58 |
+
## Parity numbers (against Cactus's native `generate(constrained=False)`)
|
| 59 |
+
|
| 60 |
+
| Stage | max-abs-diff |
|
| 61 |
+
|---|---|
|
| 62 |
+
| Flax encoder ↔ PyTorch port | 0.000010 |
|
| 63 |
+
| Flax decoder step-0 ↔ PyTorch port | 0.000029 |
|
| 64 |
+
| PyTorch encoder ↔ ONNX | 0.000004 |
|
| 65 |
+
| PyTorch decoder step ↔ ONNX | 0.000014 (logits) |
|
| 66 |
+
| End-to-end token sequence | byte-identical |
|
| 67 |
+
|
| 68 |
+
Example: `query="set a 5 min timer"` produces `' [{"name":"set_timer","arguments":{"time_human":"5 minutes"}}]'` in both Cactus native and the browser via these artifacts.
|
| 69 |
+
|
| 70 |
+
## Usage in the browser
|
| 71 |
+
|
| 72 |
+
Load both `.onnx` files via `onnxruntime-web` (WASM backend), load `needle.model` via `sentencepiece-js`, and run the encoder once + decoder-step in a JS loop with the KV cache passed through.
|
| 73 |
+
|
| 74 |
+
## Architecture
|
| 75 |
+
|
| 76 |
+
Per the upstream model card: encoder-decoder "Simple Attention Network", d_model=512, GQA 8/4 heads, 12 encoder layers, 8 decoder layers, no FFN, ZCRMSNorm (`(1+γ)·x/RMS(x)`, γ init zero), RoPE on Q and K.
|
| 77 |
+
|
| 78 |
+
The decoder is exported as a **single step** with past/present KV as graph I/O — the JS side calls it in a loop, allowing streaming token output and avoiding ONNX symbolic control flow.
|
| 79 |
+
|
| 80 |
+
## Reproduce / port your own Cactus-trained model
|
| 81 |
+
|
| 82 |
+
The full pipeline that produced these artifacts is checked in alongside the `.onnx` files (see `PORTING.md` for the step-by-step). The scripts are parametric on the source HF repo, so if you've finetuned Needle (or trained a Simple-Attention-Network variant with the upstream Cactus codebase), you can produce a browser-ready ONNX export with the same recipe:
|
| 83 |
+
|
| 84 |
+
```bash
|
| 85 |
+
# 1. Convert your Cactus checkpoint → PyTorch state_dict
|
| 86 |
+
uv run python convert_weights.py --ckpt-repo YOUR_USER/your-finetune --ckpt-file weights.pkl
|
| 87 |
+
|
| 88 |
+
# 2. Verify the port matches your upstream model bit-for-bit (< 1e-3)
|
| 89 |
+
uv run python verify_port_parity.py
|
| 90 |
+
|
| 91 |
+
# 3. Export to ONNX (reads config back from step 1's saved JSON; no edits needed)
|
| 92 |
+
uv run python export_onnx.py
|
| 93 |
+
|
| 94 |
+
# 4. Verify ONNX matches PyTorch AND matches native Cactus generate() token-for-token
|
| 95 |
+
uv run python verify_parity.py --ckpt-repo YOUR_USER/your-finetune --ckpt-file weights.pkl
|
| 96 |
+
|
| 97 |
+
# 5. Push your ONNX artifacts to HF
|
| 98 |
+
uv run python upload_to_hf.py --repo YOUR_USER/your-finetune-onnx
|
| 99 |
+
```
|
| 100 |
+
|
| 101 |
+
The PyTorch port (`needle_torch/`) is **parametric on `TransformerConfig`** — it reads the config straight out of your checkpoint's payload, so dim changes (d_model, layer counts, GQA ratios) are picked up automatically. The same pipeline works for the 26M production Needle, the 1.35M iteration config, and anything in between.
|
| 102 |
+
|
| 103 |
+
Files included for reproduction:
|
| 104 |
+
|
| 105 |
+
```
|
| 106 |
+
needle_torch/ — PyTorch port of the Simple Attention Network
|
| 107 |
+
convert_weights.py — Flax checkpoint → PyTorch state_dict (parametric on --ckpt-repo)
|
| 108 |
+
export_onnx.py — torch.onnx.export of encoder + decoder-step
|
| 109 |
+
verify_port_parity.py — Flax ↔ PyTorch parity check (load-bearing)
|
| 110 |
+
verify_parity.py — PyTorch ↔ ONNX + end-to-end vs native generate()
|
| 111 |
+
dump_tokenizer.py — Copy SentencePiece .model + emit parity goldens for the JS port
|
| 112 |
+
upload_to_hf.py — This script (push artifacts to HF Hub)
|
| 113 |
+
inspect_needle.py — Dump Flax arch / tokenizer / prompt notes (useful when porting a variant)
|
| 114 |
+
pyproject.toml — uv-managed env spec
|
| 115 |
+
PORTING.md — Full step-by-step guide
|
| 116 |
+
```
|
| 117 |
+
|
| 118 |
+
## License
|
| 119 |
+
|
| 120 |
+
MIT, matching the upstream Cactus Needle license.
|
| 121 |
+
"""
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def main():
|
| 125 |
+
p = argparse.ArgumentParser()
|
| 126 |
+
p.add_argument("--repo", required=True, help="e.g. onnx-community/needle-onnx")
|
| 127 |
+
p.add_argument("--private", action="store_true", help="Create as a private repo")
|
| 128 |
+
p.add_argument("--skip-lfs", action="store_true",
|
| 129 |
+
help="Skip the .onnx + .model files (useful for re-pushing docs/scripts only)")
|
| 130 |
+
p.add_argument("--pr", action="store_true",
|
| 131 |
+
help="Open a Pull Request instead of pushing to main (required for org-owned repos where your token lacks direct-write)")
|
| 132 |
+
args = p.parse_args()
|
| 133 |
+
|
| 134 |
+
api = HfApi()
|
| 135 |
+
create_repo(args.repo, exist_ok=True, repo_type="model", private=args.private)
|
| 136 |
+
|
| 137 |
+
HERE = Path(__file__).resolve().parent
|
| 138 |
+
lfs_files = [
|
| 139 |
+
(ART / "encoder.onnx", "encoder.onnx"),
|
| 140 |
+
(ART / "decoder_step.onnx", "decoder_step.onnx"),
|
| 141 |
+
(WEB_DEV / "needle.model", "needle.model"),
|
| 142 |
+
]
|
| 143 |
+
text_files = [
|
| 144 |
+
(WEB_DEV / "tokenizer-specials.json", "tokenizer-specials.json"),
|
| 145 |
+
# Reproduction pipeline (so finetuners can use the same recipe)
|
| 146 |
+
(HERE / "PORTING.md", "PORTING.md"),
|
| 147 |
+
(HERE / "convert_weights.py", "convert_weights.py"),
|
| 148 |
+
(HERE / "export_onnx.py", "export_onnx.py"),
|
| 149 |
+
(HERE / "verify_port_parity.py", "verify_port_parity.py"),
|
| 150 |
+
(HERE / "verify_parity.py", "verify_parity.py"),
|
| 151 |
+
(HERE / "dump_tokenizer.py", "dump_tokenizer.py"),
|
| 152 |
+
(HERE / "inspect_needle.py", "inspect_needle.py"),
|
| 153 |
+
(HERE / "upload_to_hf.py", "upload_to_hf.py"),
|
| 154 |
+
(HERE / "pyproject.toml", "pyproject.toml"),
|
| 155 |
+
]
|
| 156 |
+
files = (lfs_files + text_files) if not args.skip_lfs else text_files
|
| 157 |
+
for local, remote in files:
|
| 158 |
+
if not local.exists():
|
| 159 |
+
raise SystemExit(f"missing artifact: {local}")
|
| 160 |
+
size = local.stat().st_size
|
| 161 |
+
print(f"uploading {remote} ({size / 1e6:.2f} MB)...", flush=True)
|
| 162 |
+
api.upload_file(
|
| 163 |
+
path_or_fileobj=str(local),
|
| 164 |
+
path_in_repo=remote,
|
| 165 |
+
repo_id=args.repo,
|
| 166 |
+
repo_type="model",
|
| 167 |
+
create_pr=args.pr,
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
# The PyTorch port package — preserves the dir layout so `needle_torch/__init__.py` etc.
|
| 171 |
+
pkg = HERE / "needle_torch"
|
| 172 |
+
if pkg.exists():
|
| 173 |
+
for f in sorted(pkg.iterdir()):
|
| 174 |
+
if not f.is_file() or f.name.startswith("__pycache__"):
|
| 175 |
+
continue
|
| 176 |
+
remote = f"needle_torch/{f.name}"
|
| 177 |
+
print(f"uploading {remote} ({f.stat().st_size / 1e6:.2f} MB)...", flush=True)
|
| 178 |
+
api.upload_file(
|
| 179 |
+
path_or_fileobj=str(f),
|
| 180 |
+
path_in_repo=remote,
|
| 181 |
+
repo_id=args.repo,
|
| 182 |
+
repo_type="model",
|
| 183 |
+
)
|
| 184 |
+
|
| 185 |
+
print("uploading README.md...", flush=True)
|
| 186 |
+
api.upload_file(
|
| 187 |
+
path_or_fileobj=README.encode(),
|
| 188 |
+
path_in_repo="README.md",
|
| 189 |
+
repo_id=args.repo,
|
| 190 |
+
create_pr=args.pr,
|
| 191 |
+
repo_type="model",
|
| 192 |
+
)
|
| 193 |
+
|
| 194 |
+
print(f"\ndone. https://huggingface.co/{args.repo}")
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
if __name__ == "__main__":
|
| 198 |
+
main()
|