Skip to content

Automation foundation model for tiny devices: 2-bit, 8-29 MB, tool calls, ASR, structured extraction and embeddings on phones, wearables, smart homes, robots, cars and microcontrollers.

updates

HenryNdubuaku1807b1d230ba
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..7de2a6a
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Cactus Compute
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/README.md b/README.md
index 89cca9b..8e227b1 100644
--- a/README.md
+++ b/README.md
@@ -1,17 +1,10 @@
-```
- ┌────────────────────────────────────────────────────────┐
- │ │
- │ ┌─┐┌─┐┌─┐┌┬┐┬ ┬┌─┐ ┌┐┌┌─┐┌─┐┌┬┐┬ ┌─┐ │
- │ │ ├─┤│ │ │ │└─┐ │││├┤ ├┤ │││ ├┤ │
- │ └─┘┴ ┴└─┘ ┴ └─┘└─┘ ┘└┘└─┘└─┘─┴┘┴─┘└─┘ │
- │ ...a 26m function call model for edge... │
- └────────────────────────────────────────────────────────┘
-```
+# Needle
-# Simple Attention Networks
+<img src="assets/banner.png" alt="Logo" style="border-radius: 30px; width: 70%;">
-Experiments at Cactus showed that MLPs can be completely dropped from transformer networks, as long as the model relies on external knowledge source.
-Function calling relies on external tools list, so we designed a simple attention network for function calling and distilled Gemini-2.0-Flash-Lite.
+We distilled Gemini 3.1 into a 26m parameter "[Simple Attention Network](docs/simple_attention_networks.md)" that you can even finetune locally on your Mac/PC.
+In production, Needle runs on [Cactus](https://github.com/cactus-compute/cactus) at 6000 toks/sec prefill and 1200 decode speed.
+Weights are fully open on [Cactus-Compute/needle](https://huggingface.co/Cactus-Compute/needle), as well as the dataset generation.
```
d=512, 8H/4KV, BPE=8192
@@ -59,62 +52,56 @@ d=512, 8H/4KV, BPE=8192
└───────────┘
```
-## Why No FFN
-
-- **Softmax is nonlinear.** `softmax(QK^T/sqrt(d)) * V` is a data-dependent nonlinear mixing operation. For a task that is about routing information (query -> tool alignment), attention is the right primitive.
-- **Tool calling is retrieval-and-assembly.** Match query to tool name, extract argument values, assemble JSON. All three are aligning and copying between input and output -exactly what cross-attention does. No step requires per-position feature transformation (which is what FFN provides).
-- **At small scale, FFN parameters are wasted.** ~2/3 of standard transformer parameters are FFN. For a <50M model on a structured task, those parameters contribute less than more attention layers (deeper cross-attention = better query-tool alignment).
-- **Fewer parameters = faster inference.** FFNs have the biggest GEMM/GEMV dimensions -removing them cuts per-layer parameters by ~2/3, directly reducing the memory bandwidth bottleneck that dominates latency on edge devices.
-
-## Why Encoder-Decoder
-
-- **Bidirectional encoding.** Tools are structured objects -a bidirectional encoder sees the full definition at once. A causal model sees it left-to-right and must infer structure from partial context.
-- **No input tokens in KV cache.** Encoder-decoder uses a fixed-size encoder representation for cross-attention, not re-attending the full input at every generation step.
-- **Natural fit for multi-head design.** The encoder output feeds the decoder (generation) and the contrastive head (tool retrieval). Clean separation.
+- Pretrained on 16 TPU v6e for 200B tokens (27hrs).
+- Post-trained on 2B tokens of single-shot function call dataset (45mins).
-## Gated Residuals
+Needle is an experimental run for Simple Attention Networks, geared at redefining tiny AI for consumer devies (phones, watches, glasses...).
+So while it beats FunctionGemma-270m, Qwen-0.6B, Graninte-350m, LFM2.5-350m on single-shot function call for personal AI,
+Those model are have more scope/capacity and excel in conversational settings. Also, small models can be finicky.
+Please use the UI in the next section to test on your own tools, and finetune accordingly, at the click of a button.
-Without FFN, there is no per-position nonlinear rewriting per layer. This makes residual connection design critical.
+## Quickstart
-- **Standard residual** `x = x + Attn(Norm(x))` -attention can only ADD a delta. Without FFN to do the rewriting, purely additive is limiting.
-- **No residual** `x = Attn(Norm(x))` -each layer fully rewrites, but we lose the gradient highway. Deep networks (12+ layers) will not train.
-- **Gated residual (ours)** `x = x + sigmoid(gate) * Attn(Norm(x))` -per-sublayer learnable scalar, initialized to 0. sigmoid(0) = 0.5, so training starts with half-strength residual. The model can learn to sharpen useful layers (g->1) or suppress unhelpful ones (g->0) without losing gradient flow.
-
-## ZCRMSNorm
-
-- **Standard RMSNorm:** `x * gamma / RMS(x)`, gamma initialized to 1.
-- **ZCRMSNorm:** `x * (1 + gamma) / RMS(x)`, gamma initialized to 0.
-- At init, ZCRMSNorm is identity-up-to-scale. Pairs with gated residuals: the entire block starts as a damped identity + damped normalized attention. No component starts with a strong learned bias.
-- From the nGPT / DeepSeek-V3 line of work. Applied to QK heads as well (QK-norm) for training stability.
+```bash
+git clone https://github.com/cactus-compute/needle.git
+cd needle && source ./setup
+needle playground
+```
-## Contrastive Tool Selection Head
+Opens a web UI at http://127.0.0.1:7860 where you can test and finetune on your own tools. Weights are auto-downloaded.
-CLIP-style head for retrieving relevant tools before generation. Useful when the tool set is large and you want to filter to the top-k most relevant tools for a query.
+## Usage (Python)
-- **Architecture:** encoder output -> mean pool over non-pad positions -> Dense(d_model/4) -> ReLU -> Dense(128) -> L2-normalize. Produces a unit vector per input.
-- **Training:** symmetric contrastive loss (CLIP). Each batch pairs queries with their positive tools; in-batch negatives provide the contrastive signal. Learnable temperature (`log_temp`).
-- **Inference:** encode query and each tool candidate into the shared embedding space, rank by cosine similarity, take top-k.
-- Trained jointly with the main CE loss at 0.1x weight. Same encoder is used for both generation and retrieval.
+```python
+from needle.model.run import load_checkpoint, generate
+from needle.model.architecture import EncoderDecoderTransformer
+from needle.dataset.dataset import get_tokenizer
-## Muon for Attention-Only
+params, config = load_checkpoint("checkpoints/needle.pkl")
+model = EncoderDecoderTransformer(config)
+tokenizer = get_tokenizer()
-- **Dual optimizer:** Muon (Q/K/V/O projections, LR 0.02, WD 0.01) + AdamW (everything else, LR 3e-4).
-- Without FFN, the model is a deep stack of linear projections with softmax routing. Muon enforces orthogonality on weight updates via Newton-Schulz, preventing the representation collapse that can happen when stacking many linear layers without interleaving nonlinearities.
+result = generate(
+ model, params, tokenizer,
+ query="What's the weather in San Francisco?",
+ tools='[{"name":"get_weather","parameters":{"location":"string"}}]',
+ stream=False,
+)
+print(result)
+# [{"name":"get_weather","arguments":{"location":"San Francisco"}}]
+```
-## Training
+## Finetuning
-- Pretrained on 16 TPU v6e for 200B tokens.
-- Postrained on 2B tokens of tool call dataset.
-- Weights on [Cactus-Compute/needle](https://huggingface.co/Cactus-Compute/needle).
+Finetune on your own tools via the web UI or CLI:
-## Test Needle & Finetune Locally On Your Mac
+```bash
+# Web UI (generates data via Gemini, trains, evaluates, bundles result)
+needle playground
+# CLI (auto-downloads weights if not local)
+needle finetune data.jsonl
```
-git clone https://github.com/cactus-compute/needle.git
-cd needle && source ./setup
-needle ui
-```
-Opens at http://127.0.0.1:7860, play with Needle oin your Mac.
## Needle CLI
@@ -122,7 +109,7 @@ Opens at http://127.0.0.1:7860, play with Needle oin your Mac.
```
┌───────────────────────────────────────────────────────────────────┐
│ │
- │ ui Web UI for inference + finetuning │
+ │ playground Web UI for inference + finetuning │
│ --checkpoint PATH Model checkpoint (optional, │
│ auto-downloads from HuggingFace) │
│ --port INT Server port (default: 7860) │
@@ -152,14 +139,8 @@ Opens at http://127.0.0.1:7860, play with Needle oin your Mac.
│ --max-enc-len INT Max encoder seq len (default: 1024)│
│ --max-dec-len INT Max decoder seq len (default: 512) │
│ --max-samples INT Training samples (default: all) │
- │ --no-feedforward No FFN layers (default: on) │
- │ --feedforward Enable FFN layers (off by default) │
- │ --activation STR swiglu|drelu|geglu (if FFN on) │
- │ --mat-factors INT [...] FFN shrink factors (if FFN on) │
- │ --precision STR QAT: int4|int8 (default: int4) │
│ --warmup-ratio FLOAT LR warmup ratio (default: 0.05) │
│ --decay-ratio FLOAT LR cosine decay ratio (default:0.05│
- │ --dropout FLOAT Dropout rate (default: 0.0) │
│ --eval-every INT Val eval interval (default: 1000) │
│ --max-eval-samples INT Val samples limit (default: 5000) │
│ --contrastive-weight FL CLIP loss weight (default: 0.1) │
@@ -173,9 +154,9 @@ Opens at http://127.0.0.1:7860, play with Needle oin your Mac.
│ --seed INT Random seed (default: 42) │
│ │
│ pretrain │
- │ --name STR Experiment name (default: pretrain) │
+ │ --name STR Experiment name (default: pretrain)│
│ --checkpoint PATH Resume from checkpoint │
- │ --resume-step INT Override resume step │
+ │ --resume-step INT Override resume step │
│ --epochs INT Training epochs (default: 1) │
│ --batch-size INT Batch size (default: 128) │
│ --lr FLOAT AdamW learning rate (default: 3e-4)│
@@ -213,100 +194,11 @@ Opens at http://127.0.0.1:7860, play with Needle oin your Mac.
│ --output-jsonl PATH Also save raw generations to JSONL │
│ --upload-every INT Merge+upload interval │
│ │
- │ tpu │
- │ create NAME Create TPU (auto-finds zone) │
- │ --type STR Accelerator (default: v6e-8) │
- │ --version STR TPU OS (auto-detected from --type) │
- │ --preemptible Create spot/preemptible instance │
- │ connect NAME SSH config + connect (auto-zone) │
- │ setup NAME Full setup: sync code + venv + deps│
- │ sync NAME Fast sync: code (no venv rebuild) │
- │ train NAME [-- ARGS] Launch training on all workers │
- │ pretrain NAME [-- ARGS] Launch pretraining on all workers │
- │ claude NAME Install Claude Code on instance │
- │ stop NAME Stop instance (auto-zone) │
- │ start NAME Start stopped instance (auto-zone) │
- │ delete NAME Delete instance (auto-zone) │
- │ list List all TPU instances │
- │ --zone ZONE Override auto-detected zone │
+ │ tpu See docs/tpu.md │
│ │
└───────────────────────────────────────────────────────────────────┘
```
-## Setup For TPU/GCP
-
-- Setup gcloud 1: download the `macOS ARM` from [here](https://docs.cloud.google.com/sdk/docs/install-sdk) and unzip.
-- Setup gcloud 2: open terminal, cd to your downloads and run `./google-cloud-sdk/install.sh`
-- Setup gcloud 3: restart terminal and run `gcloud init`, sign in with cactus email, should prompt for project
-- Setup gcloud 4: else, set the project with `gcloud config set [PROJECT NAME]`
-- Setup gcloud 5: run `gcloud help` and read carefully
-
-### Single-host (v6e-8) -SSH into instance
-
-```
-1. Create an instance (auto: finds zone → installs Claude Code → connects via SSH)
- needle tpu create my-experiment
- (exit with 'exit' or Ctrl+D)
-
-2. Reconnect anytime
- ssh my-experiment
- or VS Code: click the '><' in the bottom left → select my-experiment
+## TPU
---- run from the instance ---
-
-3. Create a GitHub Personal Access Token (PAT)
- GitHub → Settings → Developer settings → Personal access tokens → Tokens (classic)
- Generate a token with 'repo' scope
-
-4. Clone the repo on your instance using your PAT
- git clone https://github.com/cactus-compute/needle.git
- cd needle && source ./setup
-
-5. Login to Hugging Face (required for private datasets)
- hf auth login
- (paste your HF token -get one at https://huggingface.co/settings/tokens)
-
-6. Use tmux for long training runs (survives SSH disconnects)
- tmux new -s train # start a named session
- needle train --wandb # run training inside it
- Ctrl+B, then D # detach (keeps running)
- tmux attach -t train # reattach later
-
---- back on your Mac ---
-
-7. Stop when done (saves disk, stops billing)
- needle tpu stop my-experiment
-
-8. (Optional) Delete instance when no longer needed
- needle tpu delete my-experiment
-```
-
-### Multi-host (v6e-16+) -run from your Mac
-
-For multi-host TPUs (v6e-16+), you drive everything from your Mac.
-The CLI syncs code and launches training across all workers automatically.
-
-```
-1. Set auth tokens (workers need these to download data + log metrics)
- export HF_TOKEN=hf_...
- export WANDB_API_KEY=...
-
-2. Add SSH key to agent (required for gcloud scp/ssh)
- ssh-add ~/.ssh/google_compute_engine
-
-3. Create a multi-host TPU (auto: finds zone → syncs code → installs deps)
- needle tpu create my-experiment --type v6e-16
-
-4. Launch training on all workers from your Mac
- needle tpu train my-experiment -- --wandb --epochs 1
-
-5. After code changes, sync without rebuilding venv (fast, ~seconds)
- needle tpu sync my-experiment
-
-6. Full re-setup if deps changed (slow, rebuilds venv)
- needle tpu setup my-experiment
-
-7. Stop/delete when done
- needle tpu stop my-experiment
- needle tpu delete my-experiment
-```
+This repo was used for training too, see [docs/tpu.md](docs/tpu.md) for GCP setup, TPU factsheet, and single/multi-host workflows.
\ No newline at end of file
diff --git a/assets/banner.png b/assets/banner.png
new file mode 100644
index 0000000..ce1940d
Binary files /dev/null and b/assets/banner.png differ
diff --git a/docs/hf_model_card.md b/docs/hf_model_card.md
new file mode 100644
index 0000000..933b37a
--- /dev/null
+++ b/docs/hf_model_card.md
@@ -0,0 +1,139 @@
+---
+license: mit
+library_name: jax
+tags:
+ - function-calling
+ - tool-use
+ - encoder-decoder
+ - edge
+ - on-device
+ - jax
+ - flax
+---
+
+# Needle
+
+We distilled Gemini 3.1 into a 26m parameter "[Simple Attention Network](docs/simple_attention_networks.md)" that you can even finetune locally on your Mac/PC.
+In production, Needle runs on [Cactus](https://github.com/cactus-compute/cactus) at 6000 toks/sec prefill and 1200 decode speed.
+Weights are fully open on [Cactus-Compute/needle](https://huggingface.co/Cactus-Compute/needle), as well as the dataset generation.
+
+| | |
+|---|---|
+| Parameters | 26M |
+| Architecture | Encoder-decoder, pure attention (no FFN) |
+| Encoder | 12 layers, GQA (8H/4KV), RoPE, gated residuals |
+| Decoder | 8 layers, self-attn + cross-attn, gated residuals |
+| d_model | 512 |
+| Vocab | 8192 (SentencePiece BPE) |
+| Norm | ZCRMSNorm (zero-centered, init=0) |
+| Precision | bfloat16 (INT4 QAT during training) |
+| Pretraining | 200B tokens on 16x TPU v6e (27hrs) |
+| Post-training | 2B tokens of function call data (45mins) |
+
+```
+d=512, 8H/4KV, BPE=8192
+ ┌──────────────┐
+ │ Tool Call │
+ └──────┬───────┘
+ ┌┴──────────┐
+ │ Softmax │
+ └─────┬─────┘
+ ┌─────┴─────┐
+ │ Linear (T)│ <- tied
+ └─────┬─────┘
+ ┌─────┴─────┐
+ │ ZCRMSNorm │
+ └─────┬─────┘
+ ┌────────┴────────┐
+ │ Decoder x 8 │
+ │┌───────────────┐│
+ ││ ZCRMSNorm ││
+ ││ Masked Self ││
+ ││ Attn + RoPE ││
+ ││ Gated Residual││
+ │├───────────────┤│
+ ┌──────────────┐ ││ ZCRMSNorm ││
+ │ Encoder x 12 │─────────────────────>Cross Attn ││
+ │ │ ││ Gated Residual││
+ │ ┌──────────┐ │ │└───────────────┘│
+ │ │ZCRMSNorm │ │ └────────┬────────┘
+ │ │Self Attn │ │ ┌─────┴─────┐
+ │ │ GQA+RoPE │ │ │ Embedding │ <- shared
+ │ │Gated Res │ │ └─────┬─────┘
+ │ │ │ │ ┌───────┴────────┐
+ │ │ (no FFN) │ │ │[EOS]<tool_call>│
+ │ └──────────┘ │ │ + answer │
+ │ │ └────────────────┘
+ └──────┬───────┘
+ │
+ ┌────┴──────┐
+ │ Embedding │
+ └────┬──────┘
+ │
+ ┌────┴──────┐
+ │ Text │
+ │ query │
+ └───────────┘
+```
+
+## Quickstart
+
+```bash
+git clone https://github.com/cactus-compute/needle.git
+cd needle && source ./setup
+needle playground
+```
+
+Opens a web UI at http://127.0.0.1:7860 where you can test and finetune on your own tools. Weights are auto-downloaded.
+
+## Usage (Python)
+
+```python
+from needle import load_checkpoint, generate, EncoderDecoderTransformer, get_tokenizer
+
+params, config = load_checkpoint("checkpoints/needle.pkl")
+model = EncoderDecoderTransformer(config)
+tokenizer = get_tokenizer()
+
+result = generate(
+ model, params, tokenizer,
+ query="What's the weather in San Francisco?",
+ tools='[{"name":"get_weather","parameters":{"location":"string"}}]',
+ stream=False,
+)
+print(result)
+# [{"name":"get_weather","arguments":{"location":"San Francisco"}}]
+```
+
+## Finetuning
+
+Finetune on your own tools via the web UI or CLI:
+
+```bash
+# Web UI (generates data via Gemini, trains, evaluates, bundles result)
+needle playground
+
+# CLI (auto-downloads weights if not local)
+needle finetune data.jsonl
+```
+
+## Links
+
+- [Needle](https://github.com/cactus-compute/needle) - training, finetuning, and inference code
+- [Cactus](https://github.com/cactus-compute/cactus) - on-device runtime (6000 tok/s prefill, 1200 tok/s decode)
+- [Simple Attention Networks](https://github.com/cactus-compute/needle/blob/main/docs/simple_attention_networks.md) - architecture details
+
+## License
+
+MIT
+
+## Citation
+
+```
+@misc{ndubuaku2026needle,
+ title={Needle},
+ author={Henry Ndubuaku and Jakub Mroz and Karen Mosoyan and Roman Shemet and Parkirat Sandhu and Satyajit Kumar and Noah Cylich and Justin H. Lee},
+ year={2026},
+ url={https://github.com/cactus-compute/needle}
+}
+```
diff --git a/docs/simple_attention_networks.md b/docs/simple_attention_networks.md
new file mode 100644
index 0000000..0694917
--- /dev/null
+++ b/docs/simple_attention_networks.md
@@ -0,0 +1,115 @@
+# Simple Attention Networks
+
+Experiments at Cactus showed that MLPs can be completely dropped from transformer networks, as long as the model relies on external knowledge source.
+Function calling relies on external tools list, so we designed a simple attention network for function calling and distilled Gemini-3.1-Flash-Lite.
+
+```
+d=512, 8H/4KV, BPE=8192
+ ┌──────────────┐
+ │ Tool Call │
+ └──────┬───────┘
+ ┌┴──────────┐
+ │ Softmax │
+ └─────┬─────┘
+ ┌─────┴─────┐
+ │ Linear (T)│ ← tied
+ └─────┬─────┘
+ ┌─────┴─────┐
+ │ ZCRMSNorm │
+ └─────┬─────┘
+ ┌────────┴────────┐
+ │ Decoder x 8 │
+ │┌───────────────┐│
+ ││ ZCRMSNorm ││
+ ││ Masked Self ││
+ ││ Attn + RoPE ││
+ ││ Gated Residual││
+ │├───────────────┤│
+ ┌──────────────┐ ││ ZCRMSNorm ││
+ │ Encoder x 12 │──────────────────────▶Cross Attn ││
+ │ │ ││ Gated Residual││
+ │ ┌──────────┐ │ │└───────────────┘│
+ │ │ZCRMSNorm │ │ └────────┬────────┘
+ │ │Self Attn │ │ ┌─────┴─────┐
+ │ │ GQA+RoPE │ │ │ Embedding │ ← shared
+ │ │Gated Res │ │ └─────┬─────┘
+ │ │ │ │ ┌───────┴───────-┐
+ │ │ (no FFN) │ │ │[EOS]<tool_call>│
+ │ └──────────┘ │ │ + answer │
+ │ │ └───────────────-┘
+ └──────┬───────┘
+ │
+ ┌────┴──────┐
+ │ Embedding │
+ └────┬──────┘
+ │
+ ┌────┴──────┐
+ │ Text │
+ │ query │
+ └───────────┘
+```
+
+## Why No FFN
+
+- **Softmax is nonlinear.** `softmax(QK^T/sqrt(d)) * V` is a data-dependent nonlinear mixing operation. For a task that is about routing information (query -> tool alignment), attention is the right primitive.
+- **Tool calling is retrieval-and-assembly.** Match query to tool name, extract argument values, assemble JSON. All three are aligning and copying between input and output -exactly what cross-attention does. No step requires per-position feature transformation (which is what FFN provides).
+- **At small scale, FFN parameters are wasted.** ~2/3 of standard transformer parameters are FFN. For a <50M model on a structured task, those parameters contribute less than more attention layers (deeper cross-attention = better query-tool alignment).
+- **Fewer parameters = faster inference.** FFNs have the biggest GEMM/GEMV dimensions -removing them cuts per-layer parameters by ~2/3, directly reducing the memory bandwidth bottleneck that dominates latency on edge devices.
+
+## Why Encoder-Decoder
+
+- **Bidirectional encoding.** Tools are structured objects -a bidirectional encoder sees the full definition at once. A causal model sees it left-to-right and must infer structure from partial context.
+- **No input tokens in KV cache.** Encoder-decoder uses a fixed-size encoder representation for cross-attention, not re-attending the full input at every generation step.
+- **Natural fit for multi-head design.** The encoder output feeds the decoder (generation) and the contrastive head (tool retrieval). Clean separation.
+
+## Gated Residuals
+
+Without FFN, there is no per-position nonlinear rewriting per layer. This makes residual connection design critical.
+
+- **Standard residual** `x = x + Attn(Norm(x))` -attention can only ADD a delta. Without FFN to do the rewriting, purely additive is limiting.
+- **No residual** `x = Attn(Norm(x))` -each layer fully rewrites, but we lose the gradient highway. Deep networks (12+ layers) will not train.
+- **Gated residual (ours)** `x = x + sigmoid(gate) * Attn(Norm(x))` -per-sublayer learnable scalar, initialized to 0. sigmoid(0) = 0.5, so training starts with half-strength residual. The model can learn to sharpen useful layers (g->1) or suppress unhelpful ones (g->0) without losing gradient flow.
+
+## ZCRMSNorm
+
+- **Standard RMSNorm:** `x * gamma / RMS(x)`, gamma initialized to 1.
+- **ZCRMSNorm:** `x * (1 + gamma) / RMS(x)`, gamma initialized to 0.
+- At init, ZCRMSNorm is identity-up-to-scale. Pairs with gated residuals: the entire block starts as a damped identity + damped normalized attention. No component starts with a strong learned bias.
+- From the nGPT / DeepSeek-V3 line of work. Applied to QK heads as well (QK-norm) for training stability.
+
+## Contrastive Tool Selection Head
+
+CLIP-style head for retrieving relevant tools before generation. Useful when the tool set is large and you want to filter to the top-k most relevant tools for a query.
+
+- **Architecture:** encoder output -> mean pool over non-pad positions -> Dense(d_model/4) -> ReLU -> Dense(128) -> L2-normalize. Produces a unit vector per input.
+- **Training:** symmetric contrastive loss (CLIP). Each batch pairs queries with their positive tools; in-batch negatives provide the contrastive signal. Learnable temperature (`log_temp`).
+- **Inference:** encode query and each tool candidate into the shared embedding space, rank by cosine similarity, take top-k.
+- Trained jointly with the main CE loss at 0.1x weight. Same encoder is used for both generation and retrieval.
+
+## Muon for Attention-Only
+
+- **Dual optimizer:** Muon (Q/K/V/O projections, LR 0.02, WD 0.01) + AdamW (everything else, LR 3e-4).
+- Without FFN, the model is a deep stack of linear projections with softmax routing. Muon enforces orthogonality on weight updates via Newton-Schulz, preventing the representation collapse that can happen when stacking many linear layers without interleaving nonlinearities.
+
+## INT4 QAT as Regularization
+
+- **Fake quantization every 100 steps.** Weights are group-wise quantized to INT4 (symmetric, group_size=32) with straight-through estimator (STE), then used for the forward pass. Gradients flow through the rounding via STE.
+- **Regularization effect.** Quantization noise acts as a form of weight noise regularization, discouraging the model from relying on precise weight values. For a small model with no FFN (fewer parameters, higher overfitting risk), this is beneficial.
+- **Deploy-ready.** The model trains with the same quantization it will see at inference. No post-training quantization gap.
+
+## Token-Level Loss Weighting
+
+- Base (JSON structure): 1.0x, tool names: 2.0x, argument keys: 1.5x, argument values: 4.0x.
+- The model achieves ~99% JSON parse rate early in training. The actual errors are values > names > keys > structure. Weighting matches the error distribution.
+- Auxiliary: z-loss for logit stability, CLIP contrastive loss at 0.1x.
+
+## Citation
+
+```
+@misc{ndubuaku2025needle,
+ title={Simple Attention Networks},
+ author={Henry Ndubuaku},
+ year={2026},
+ url={https://github.com/cactus-compute/needle/blob/main/docs/simple_attention_networks.md}
+}
+```
diff --git a/docs/tpu.md b/docs/tpu.md
new file mode 100644
index 0000000..d8a8bcc
--- /dev/null
+++ b/docs/tpu.md
@@ -0,0 +1,135 @@
+# TPU Setup & Workflow
+
+## TPU Factsheet
+
+```
+ Trillium (v6e)
+ ──────────────────────────────────────────
+ HBM per chip 32 GB
+ BF16 FLOPS 918 TFLOPS
+ HBM bandwidth 1,640 GB/s
+ ICI bandwidth 3,584 Gbps
+ On-demand/chip/hr $2.70 (US regions)
+ ──────────────────────────────────────────
+
+ Dataset
+ ──────────────────────────────────────────
+ Text 2M Tool-call pairs
+ (query, tools, answers)
+ synthesized via Gemini
+ Cactus-Compute/tool-calls
+ (HuggingFace)
+ ──────────────────────────────────────────
+
+ ┌────────────────────┬──────────┬──────────┬──────────┐
+ │ │ v6e-8 │ v6e-16 │ v6e-32 │
+ ├────────────────────┼──────────┼──────────┼──────────┤
+ │ Chips │ 8 │ 16 │ 32 │
+ │ Total HBM │ 256 GB │ 512 GB │ 1024 GB │
+ │ Scaling eff. │ 0.9× │ 0.8× │ 0.7× │
+ │ Eff. TFLOPS │ 994 │ 1,766 │ 3,091 │
+ │ Est. time │ ~88h │ ~49h │ ~29h │
+ │ On-demand $/hr │ $21.60 │ $43.20 │ $86.40 │
+ │ Est. total cost │ ~$1,900 │ ~$2,120 │ ~$2,510 │
+ └────────────────────┴──────────┴──────────┴──────────┘
+```
+
+## CLI Reference
+
+```
+ needle tpu
+
+ create NAME Create TPU (auto-finds zone)
+ --type STR Accelerator (default: v6e-8)
+ --version STR TPU OS (auto-detected from --type)
+ --preemptible Create spot/preemptible instance
+ connect NAME SSH config + connect (auto-zone)
+ setup NAME Full setup: sync code + venv + deps
+ sync NAME Fast sync: code (no venv rebuild)
+ train NAME [-- ARGS] Launch training on all workers
+ pretrain NAME [-- ARGS] Launch pretraining on all workers
+ claude NAME Install Claude Code on instance
+ stop NAME Stop instance (auto-zone)
+ start NAME Start stopped instance (auto-zone)
+ delete NAME Delete instance (auto-zone)
+ list List all TPU instances
+ --zone ZONE Override auto-detected zone
+```
+
+## GCP Setup
+
+- Download the `macOS ARM` gcloud SDK from [here](https://docs.cloud.google.com/sdk/docs/install-sdk) and unzip.
+- Open terminal, cd to your downloads and run `./google-cloud-sdk/install.sh`
+- Restart terminal and run `gcloud init`, sign in with cactus email, should prompt for project
+- Else, set the project with `gcloud config set [PROJECT NAME]`
+- Run `gcloud help` and read carefully
+
+## Single-host (v6e-8) - SSH into instance
+
+```
+1. Create an instance (auto: finds zone -> installs Claude Code -> connects via SSH)
+ needle tpu create my-experiment
+ (exit with 'exit' or Ctrl+D)
+
+2. Reconnect anytime
+ ssh my-experiment
+ or VS Code: click the '><' in the bottom left -> select my-experiment
+
+--- run from the instance ---
+
+3. Create a GitHub Personal Access Token (PAT)
+ GitHub -> Settings -> Developer settings -> Personal access tokens -> Tokens (classic)
+ Generate a token with 'repo' scope
+
+4. Clone the repo on your instance using your PAT
+ git clone https://github.com/cactus-compute/needle.git
+ cd needle && source ./setup
+
+5. Login to Hugging Face (required for private datasets)
+ hf auth login
+ (paste your HF token - get one at https://huggingface.co/settings/tokens)
+
+6. Use tmux for long training runs (survives SSH disconnects)
+ tmux new -s train # start a named session
+ needle train --wandb # run training inside it
+ Ctrl+B, then D # detach (keeps running)
+ tmux attach -t train # reattach later
+
+--- back on your Mac ---
+
+7. Stop when done (saves disk, stops billing)
+ needle tpu stop my-experiment
+
+8. (Optional) Delete instance when no longer needed
+ needle tpu delete my-experiment
+```
+
+## Multi-host (v6e-16+) - run from your Mac
+
+For multi-host TPUs (v6e-16+), you drive everything from your Mac.
+The CLI syncs code and launches training across all workers automatically.
+
+```
+1. Set auth tokens (workers need these to download data + log metrics)
+ export HF_TOKEN=hf_...
+ export WANDB_API_KEY=...
+
+2. Add SSH key to agent (required for gcloud scp/ssh)
+ ssh-add ~/.ssh/google_compute_engine
+
+3. Create a multi-host TPU (auto: finds zone -> syncs code -> installs deps)
+ needle tpu create my-experiment --type v6e-16
+
+4. Launch training on all workers from your Mac
+ needle tpu train my-experiment -- --wandb --epochs 1
+
+5. After code changes, sync without rebuilding venv (fast, ~seconds)
+ needle tpu sync my-experiment
+
+6. Full re-setup if deps changed (slow, rebuilds venv)
+ needle tpu setup my-experiment
+
+7. Stop/delete when done
+ needle tpu stop my-experiment
+ needle tpu delete my-experiment
+```
diff --git a/launch_train.sh b/launch_train.sh
index 7f7d543..2e7ab7c 100644
--- a/launch_train.sh
+++ b/launch_train.sh
@@ -7,9 +7,14 @@
set -euo pipefail
-TPU_NAME="large"
-ZONE="asia-northeast1-b"
-PROJECT="needle-488623"
+TPU_NAME="${TPU_NAME:-large}"
+ZONE="${ZONE:-asia-northeast1-b}"
+PROJECT="${PROJECT:-$(gcloud config get-value project 2>/dev/null)}"
+
+if [ -z "$PROJECT" ] || [ "$PROJECT" = "(unset)" ]; then
+ echo "[launch] ERROR: no GCP project set. Run 'gcloud config set project <PROJECT>' or export PROJECT=..."
+ exit 1
+fi
TRAIN_ARGS="${@}"
diff --git a/needle/__init__.py b/needle/__init__.py
new file mode 100644
index 0000000..f582872
--- /dev/null
+++ b/needle/__init__.py
@@ -0,0 +1,25 @@
+"""Needle - a 26M parameter function calling model."""
+
+from needle.model.architecture import (
+ SimpleAttentionNetwork,
+ TransformerConfig,
+)
+from needle.model.run import (
+ generate,
+ generate_batch,
+ load_checkpoint,
+ encode_for_retrieval,
+ retrieve_tools,
+)
+from needle.dataset.dataset import get_tokenizer
+
+__all__ = [
+ "SimpleAttentionNetwork",
+ "TransformerConfig",
+ "generate",
+ "generate_batch",
+ "load_checkpoint",
+ "encode_for_retrieval",
+ "retrieve_tools",
+ "get_tokenizer",
+]
diff --git a/src/cli.py b/needle/cli.py
similarity index 93%
rename from src/cli.py
rename to needle/cli.py
index 4c325e2..705ba92 100644
--- a/src/cli.py
+++ b/needle/cli.py
@@ -138,13 +138,6 @@ def main():
p.add_argument("--seed", type=int, default=42)
p.add_argument("--eval-every", type=int, default=1000)
p.add_argument("--max-eval-samples", type=int, default=5000)
- p.add_argument("--precision", type=str, default="int4", choices=["int4", "int8"],
- help="QAT precision: int4 (4-bit) or int8 (8-bit) fake quantization (default: int4)")
- p.add_argument("--activation", type=str, default="swiglu", choices=["drelu", "swiglu", "geglu"])
- p.add_argument("--mat-factors", type=int, nargs="*", default=[2, 4],
- help="Matryoshka FFN shrink factors, e.g. 2=half width (default: 2 4)")
- p.add_argument("--dropout", type=float, default=0.0,
- help="Dropout rate for residual connections (default: 0.0)")
p.add_argument("--contrastive-weight", type=float, default=0.1,
help="Weight for CLIP-style contrastive loss (default: 0.1)")
p.add_argument("--contrastive-dim", type=int, default=128,
@@ -155,8 +148,6 @@ def main():
help="Loss weight for argument value tokens (default: 4.0)")
p.add_argument("--w-key", type=float, default=1.5,
help="Loss weight for argument key tokens (default: 1.5)")
- p.add_argument("--no-feedforward", action=argparse.BooleanOptionalAction, default=True,
- help="Remove feedforward layers entirely (default: True)")
p = sub.add_parser("pretrain", add_help=False)
p.add_argument("--name", type=str, default="pretrain",
@@ -186,8 +177,6 @@ def main():
p.add_argument("--save-every", type=int, default=1000,
help="Save and upload checkpoint every N steps (default: 1000)")
p.add_argument("--checkpoint-dir", type=str, default="checkpoints")
- p.add_argument("--activation", type=str, default="swiglu", choices=["drelu", "swiglu", "geglu"])
- p.add_argument("--no-feedforward", action=argparse.BooleanOptionalAction, default=True)
p = sub.add_parser("tokenize", add_help=False)
p.add_argument("--max-samples", type=int, default=None,
@@ -238,7 +227,18 @@ def main():
choices=["wikitext2", "lambada", "hellaswag", "arc_easy"])
p.add_argument("--max-samples", type=int, default=500)
- p = sub.add_parser("ui", add_help=False)
+ p = sub.add_parser("finetune", add_help=False)
+ p.add_argument("jsonl_path", type=str, help="Path to JSONL training data")
+ p.add_argument("--checkpoint", type=str, default=None,
+ help="Base model checkpoint (auto-downloads from HuggingFace if omitted)")
+ p.add_argument("--epochs", type=int, default=1)
+ p.add_argument("--batch-size", type=int, default=64)
+ p.add_argument("--checkpoint-dir", type=str, default="checkpoints")
+ p.add_argument("--cache-dir", type=str, default=None)
+ p.add_argument("--max-enc-len", type=int, default=None)
+ p.add_argument("--max-dec-len", type=int, default=None)
+
+ p = sub.add_parser("playground", add_help=False)
p.add_argument("--checkpoint", type=str, default=None)
p.add_argument("--port", type=int, default=7860)
p.add_argument("--host", type=str, default="127.0.0.1")
@@ -330,7 +330,10 @@ def main():
if args.upload_every is None:
args.upload_every = _UE
gendata_main(args)
- elif args.command == "ui":
+ elif args.command == "finetune":
+ from .training.finetune import finetune_local
+ finetune_local(args)
+ elif args.command == "playground":
from .ui.server import main as ui_main
ui_main(args)
elif args.command == "tpu":
diff --git a/src/dataset/__init__.py b/needle/dataset/__init__.py
similarity index 100%
rename from src/dataset/__init__.py
rename to needle/dataset/__init__.py
diff --git a/src/dataset/dataset.py b/needle/dataset/dataset.py
similarity index 100%
rename from src/dataset/dataset.py
rename to needle/dataset/dataset.py
diff --git a/src/dataset/generate.py b/needle/dataset/generate.py
similarity index 100%
rename from src/dataset/generate.py
rename to needle/dataset/generate.py
diff --git a/src/dataset/tokenize.py b/needle/dataset/tokenize.py
similarity index 100%
rename from src/dataset/tokenize.py
rename to needle/dataset/tokenize.py
diff --git a/src/dataset/tokenizer.py b/needle/dataset/tokenizer.py
similarity index 100%
rename from src/dataset/tokenizer.py
rename to needle/dataset/tokenizer.py
diff --git a/src/model/__init__.py b/needle/model/__init__.py
similarity index 100%
rename from src/model/__init__.py
rename to needle/model/__init__.py
diff --git a/src/model/architecture.py b/needle/model/architecture.py
similarity index 99%
rename from src/model/architecture.py
rename to needle/model/architecture.py
index 6a2a701..c62cc4d 100644
--- a/src/model/architecture.py
+++ b/needle/model/architecture.py
@@ -323,7 +323,7 @@ class Decoder(nn.Module):
return x
-class EncoderDecoderTransformer(nn.Module):
+class SimpleAttentionNetwork(nn.Module):
"""Encoder-decoder transformer with shared embeddings, tied output, RoPE, and bfloat16."""
config: TransformerConfig
diff --git a/src/model/constrained.py b/needle/model/constrained.py
similarity index 100%
rename from src/model/constrained.py
rename to needle/model/constrained.py
diff --git a/src/model/export.py b/needle/model/export.py
similarity index 100%
rename from src/model/export.py
rename to needle/model/export.py
diff --git a/src/model/quantize.py b/needle/model/quantize.py
similarity index 100%
rename from src/model/quantize.py
rename to needle/model/quantize.py
diff --git a/src/model/run.py b/needle/model/run.py
similarity index 99%
rename from src/model/run.py
rename to needle/model/run.py
index e07d459..9216045 100644
--- a/src/model/run.py
+++ b/needle/model/run.py
@@ -10,7 +10,7 @@ import numpy as np
from ..dataset.dataset import get_tokenizer, to_snake_case, DEFAULT_MAX_ENC_LEN, DEFAULT_MAX_GEN_LEN
from .architecture import (
- EncoderDecoderTransformer,
+ SimpleAttentionNetwork,
TransformerConfig,
make_causal_mask,
make_padding_mask,
@@ -269,7 +269,7 @@ def main(args):
print(f"Loading checkpoint: {args.checkpoint}")
params, config = load_checkpoint(args.checkpoint)
- model = EncoderDecoderTransformer(config)
+ model = SimpleAttentionNetwork(config)
tokenizer = get_tokenizer()
param_count = sum(x.size for x in jax.tree.leaves(params))
diff --git a/src/training/__init__.py b/needle/training/__init__.py
similarity index 100%
rename from src/training/__init__.py
rename to needle/training/__init__.py
diff --git a/src/training/eval.py b/needle/training/eval.py
similarity index 100%
rename from src/training/eval.py
rename to needle/training/eval.py
diff --git a/src/training/finetune.py b/needle/training/finetune.py
similarity index 94%
rename from src/training/finetune.py
rename to needle/training/finetune.py
index b962a1a..4774451 100644
--- a/src/training/finetune.py
+++ b/needle/training/finetune.py
@@ -211,9 +211,28 @@ def _emit(tag, data):
print(f"{tag}:{json.dumps(data)}", flush=True)
+def _resolve_checkpoint(path):
+ """Resolve checkpoint path, downloading from HuggingFace if needed."""
+ if path and os.path.exists(path):
+ return path
+ from huggingface_hub import hf_hub_download
+ local_dir = "checkpoints"
+ os.makedirs(local_dir, exist_ok=True)
+ filename = os.path.basename(path) if path else "needle.pkl"
+ local_path = os.path.join(local_dir, filename)
+ if os.path.exists(local_path):
+ return local_path
+ print(f"Downloading {filename} from Cactus-Compute/needle...")
+ return hf_hub_download(
+ repo_id="Cactus-Compute/needle",
+ filename=filename,
+ repo_type="model",
+ local_dir=local_dir,
+ )
+
+
def finetune_local(args):
- if not args.checkpoint:
- raise ValueError("--checkpoint is required: finetune needs a base model to start from")
+ args.checkpoint = _resolve_checkpoint(args.checkpoint)
with open(args.jsonl_path) as f:
examples = [json.loads(line) for line in f if line.strip()]
@@ -310,14 +329,10 @@ def finetune_local(args):
dtype=cfg.get("dtype", "bfloat16"),
checkpoint_dir=args.checkpoint_dir, seed=42,
eval_every=max(1, approx_steps), max_eval_samples=min(val_kept, 50),
- precision="int4",
- activation=cfg.get("activation", "drelu"),
- mat_factors=[2, 4], dropout=0.0,
contrastive_weight=0.1,
contrastive_dim=cfg.get("contrastive_dim", 128),
num_memory_slots=cfg.get("num_memory_slots", 64),
w_name=2.0, w_value=4.0, w_key=1.5,
- no_feedforward=cfg.get("no_feedforward", True),
val_ds=val_ds,
)
@@ -350,7 +365,7 @@ if __name__ == "__main__":
p.add_argument("--epochs", type=int, default=1)
p.add_argument("--batch-size", type=int, default=64)
p.add_argument("--checkpoint-dir", type=str, default="checkpoints")
- p.add_argument("--checkpoint", type=str, required=True)
+ p.add_argument("--checkpoint", type=str, default=None)
p.add_argument("--cache-dir", type=str, default=None)
p.add_argument("--max-enc-len", type=int, default=None)
p.add_argument("--max-dec-len", type=int, default=None)
diff --git a/src/training/optim.py b/needle/training/optim.py
similarity index 100%
rename from src/training/optim.py
rename to needle/training/optim.py
diff --git a/src/training/pretrain.py b/needle/training/pretrain.py
similarity index 100%
rename from src/training/pretrain.py
rename to needle/training/pretrain.py
diff --git a/src/training/train.py b/needle/training/train.py
similarity index 85%
rename from src/training/train.py
rename to needle/training/train.py
index e147944..9f680fa 100644
--- a/src/training/train.py
+++ b/needle/training/train.py
@@ -31,9 +31,6 @@ from ..model.quantize import _quantize_params
_PRECISION = "int4"
-_MAT_FACTORS = ()
-_MAT_FF_WIDTHS = ()
-_D_FF = 2048
_CONTRASTIVE_WEIGHT = 0.1
# Weight map: class 0=base, 1=name, 2=value, 3=key (set from CLI args at train time)
# Use numpy at module level to avoid initializing JAX backend before jax.distributed.initialize()
@@ -51,7 +48,7 @@ def _clip_contrastive_loss(q_emb, t_emb, log_temp):
return (jnp.mean(loss_q) + jnp.mean(loss_t)) / 2.0
-def _text_loss_fn(state, params, src, tgt_in, tgt_out, ffn_mask, rng, loss_mask, do_quantize,
+def _text_loss_fn(state, params, src, tgt_in, tgt_out, rng, loss_mask, do_quantize,
enc_seg_ids, dec_seg_ids):
q_params = jax.lax.cond(
do_quantize,
@@ -59,9 +56,6 @@ def _text_loss_fn(state, params, src, tgt_in, tgt_out, ffn_mask, rng, loss_mask,
lambda p: p,
params,
)
- # Segment-aware masks work for both packed and non-packed batches.
- # Non-packed: seg_id=1 for all non-padding tokens → equivalent to padding mask + causal.
- # Packed: seg_id=1,2,3... per sub-sequence → block-diagonal attention.
src_mask = make_packing_mask(enc_seg_ids)
tgt_mask = make_causal_packing_mask(dec_seg_ids)
cross_mask = make_cross_packing_mask(enc_seg_ids, dec_seg_ids)
@@ -69,7 +63,6 @@ def _text_loss_fn(state, params, src, tgt_in, tgt_out, ffn_mask, rng, loss_mask,
{"params": q_params},
src, tgt_in, src_mask=src_mask, tgt_mask=tgt_mask,
cross_mask=cross_mask,
- ffn_mask=ffn_mask,
deterministic=False,
method="forward_masked",
rngs={"dropout": rng},
@@ -108,29 +101,11 @@ def _contrastive_loss_fn(state, params, query_tokens, tool_tokens, rng, do_quant
-def _make_ffn_mask(batch_size, d_ff, mat_ff_widths):
- """Build (batch, d_ff) prefix mask: batch split equally across widths.
-
- First 1/N = full width (all ones), remaining 1/N sections = mat widths.
- """
- n_widths = 1 + len(mat_ff_widths) # full + mat widths
- per_width = batch_size // n_widths
- arange = jnp.arange(d_ff)
- rows = [jnp.ones((per_width, d_ff), dtype=jnp.bfloat16)] # full width
- for k in mat_ff_widths:
- rows.append((arange[None, :] < k).astype(jnp.bfloat16).repeat(per_width, axis=0))
- # Handle remainder (assign to full width)
- remainder = batch_size - per_width * n_widths
- if remainder > 0:
- rows.append(jnp.ones((remainder, d_ff), dtype=jnp.bfloat16))
- return jnp.concatenate(rows, axis=0)
-
-
-def _train_step(state, src, tgt_in, tgt_out, enc_seg_ids, dec_seg_ids, ffn_mask, rng, loss_mask, query_tokens, tool_tokens, cl_rng, do_quantize, do_contrastive):
+def _train_step(state, src, tgt_in, tgt_out, enc_seg_ids, dec_seg_ids, rng, loss_mask, query_tokens, tool_tokens, cl_rng, do_quantize, do_contrastive):
"""Unified train step with boolean flag for contrastive loss."""
def combined_loss(p):
- text_loss = _text_loss_fn(state, p, src, tgt_in, tgt_out, ffn_mask, rng, loss_mask, do_quantize,
+ text_loss = _text_loss_fn(state, p, src, tgt_in, tgt_out, rng, loss_mask, do_quantize,
enc_seg_ids, dec_seg_ids)
cl_loss = jax.lax.cond(
do_contrastive,
@@ -168,50 +143,6 @@ def _make_val_loss_fn(apply_fn):
return val_loss_batch
-def _make_mat_val_loss_fn(apply_fn, ff_width):
- """Val loss for matryoshka sub-model at given FFN width."""
- @jax.jit
- def val_loss_batch(params, src, tgt_in, tgt_out, loss_mask, enc_seg_ids, dec_seg_ids):
- src_mask = make_packing_mask(enc_seg_ids)
- tgt_mask = make_causal_packing_mask(dec_seg_ids)
- cross_mask = make_cross_packing_mask(enc_seg_ids, dec_seg_ids)
- logits, _, mat_logits = apply_fn(
- {"params": params}, src, tgt_in,
- src_mask=src_mask, tgt_mask=tgt_mask, cross_mask=cross_mask,
- mat_ff_widths=(ff_width,),
- method="forward_with_aux",
- )
- trunc_logits = mat_logits[0].astype(jnp.float32)
- loss = optax.softmax_cross_entropy_with_integer_labels(trunc_logits, tgt_out)
- padding_mask = (dec_seg_ids > 0).astype(jnp.float32)
- return jnp.sum(loss * padding_mask), jnp.sum(padding_mask)
- return val_loss_batch
-
-
-def _estimate_mat_params(config, matryoshka_factor):
- """Estimate parameter count of a sub-model at a given matryoshka factor.
-
- matryoshka_factor: how many times smaller the FFN widths are (e.g. 2 = half width).
- Embedding and attention weights are unchanged.
- """
- d = config.d_model
- v = config.vocab_size
- n_enc = config.num_encoder_layers
- n_dec = config.num_decoder_layers
- kv_dim = config.num_kv_heads * (d // config.num_heads)
- d_ff = config.d_ff // matryoshka_factor
-
- emb = v * d
- attn = d * d + d * kv_dim * 2 + d * d
- ffn = d * d_ff * 3
- enc_block = attn + ffn
- dec_block = attn * 2 + ffn
- total = emb + n_enc * enc_block + n_dec * dec_block
- return int(total)
-
-
-
-
def train(args):
num_devices = jax.local_device_count()
@@ -298,13 +229,11 @@ def train(args):
d_ff=getattr(args, "d_ff", None) or args.d_model * 4,
max_seq_len=max(args.max_enc_len, args.max_dec_len),
dtype=args.dtype,
- activation=getattr(args, "activation", "drelu"),
num_memory_slots=getattr(args, "num_memory_slots", 64),
contrastive_dim=getattr(args, "contrastive_dim", 128),
- no_feedforward=getattr(args, "no_feedforward", True),
)
- global _PRECISION, _MAT_FACTORS, _MAT_FF_WIDTHS, _D_FF, _CONTRASTIVE_WEIGHT, _LOSS_WEIGHT_MAP
+ global _PRECISION, _CONTRASTIVE_WEIGHT, _LOSS_WEIGHT_MAP
_PRECISION = getattr(args, "precision", "int4")
_CONTRASTIVE_WEIGHT = getattr(args, "contrastive_weight", 0.1)
_LOSS_WEIGHT_MAP = jnp.array([
@@ -313,15 +242,6 @@ def train(args):
getattr(args, "w_value", 4.0), # 2: argument value
getattr(args, "w_key", 1.5), # 3: argument key
], dtype=jnp.float32)
- _D_FF = config.d_ff
- mat_factors_raw = getattr(args, "mat_factors", None)
- if mat_factors_raw and not config.no_feedforward:
- _MAT_FACTORS = tuple(f for f in mat_factors_raw if f > 1)
- _MAT_FF_WIDTHS = tuple(config.d_ff // f for f in _MAT_FACTORS)
- else:
- _MAT_FACTORS = ()
- _MAT_FF_WIDTHS = ()
- n_widths = 1 + len(_MAT_FF_WIDTHS) if _MAT_FF_WIDTHS else 1
p_train_step = _make_p_train_step()
np.random.seed(args.seed)
@@ -386,7 +306,6 @@ def train(args):
print(f" d_model {config.d_model:>12}")
print(f" Heads {config.num_heads:>7} ({config.num_kv_heads} KV)")
print(f" Layers {config.num_encoder_layers:>7} enc / {config.num_decoder_layers} dec")
- print(f" Activation {config.activation:>12}")
print(f" Dtype {config.dtype:>12}")
print(f" ─────────────────────────────────────")
print(f" Hosts {num_hosts:>12}")
@@ -402,15 +321,6 @@ def train(args):
os.makedirs(args.checkpoint_dir, exist_ok=True)
global_step = 0
- text_ffn_mask = _make_ffn_mask(args.batch_size, config.d_ff, _MAT_FF_WIDTHS)
- text_ffn_mask = jnp.broadcast_to(
- text_ffn_mask[None, :, :],
- (num_devices, args.batch_size, config.d_ff),
- )
- if n_widths > 1 and is_main:
- print(f" Mat factors {n_widths} (full + {', '.join(str(f)+'x' for f in _MAT_FACTORS)})")
- print(f" Mat mode unique input ({args.batch_size}/dev, split by width)")
-
adam_schedule = _wsd_schedule(scaled_lr, total_steps, warmup_steps)
muon_schedule = _wsd_schedule(muon_lr, total_steps, warmup_steps)
tokens_per_batch = global_batch_size * (args.max_enc_len + args.max_dec_len)
@@ -492,7 +402,7 @@ def train(args):
state, loss, grad_norm = p_train_step(
state, src_b, tgt_in_b, tgt_out_b, enc_seg_b, dec_seg_b,
- text_ffn_mask, text_rngs, lm_b,
+ text_rngs, lm_b,
cl_q_b, cl_t_b, cl_rngs, do_qat, do_cl,
)
@@ -556,22 +466,14 @@ def train(args):
# ── Host 0 only: val PPL + checkpoint save (fast) ──
quant_val_ppl = 0.0
- mat_results = {}
total_params = 0
ckpt_path = ""
if is_main:
q_params = _quantize_params(eval_params, precision=_PRECISION)
- mat_vl_fns = {}
- if _MAT_FACTORS:
- _apply_fn = _unreplicate(state).apply_fn
- mat_vl_fns = {f: _make_mat_val_loss_fn(_apply_fn, fw)
- for f, fw in zip(_MAT_FACTORS, _MAT_FF_WIDTHS)}
- del _apply_fn
full_loss, full_toks = 0.0, 0.0
q_loss, q_toks = 0.0, 0.0
- mat_accum = {f: [0.0, 0.0] for f in _MAT_FACTORS}
_val_n = count_batches(len(val_enc), args.batch_size)
_val_bar = tqdm(get_batches(val_enc, val_dec_in, val_dec_tgt, args.batch_size,
@@ -590,20 +492,10 @@ def train(args):
full_loss += float(vl); full_toks += float(vt)
vl, vt = val_loss_fn(q_params, src, dec_in, dec_tgt, lm, es, ds)
q_loss += float(vl); q_toks += float(vt)
- for f, fn in mat_vl_fns.items():
- vl, vt = fn(eval_params, src, dec_in, dec_tgt, lm, es, ds)
- mat_accum[f][0] += float(vl)
- mat_accum[f][1] += float(vt)
-
last_val_ppl = float(math.exp(min(full_loss / max(full_toks, 1), 20)))
quant_val_ppl = float(math.exp(min(q_loss / max(q_toks, 1), 20)))
del q_params
- for f in _MAT_FACTORS:
- avg = mat_accum[f][0] / max(mat_accum[f][1], 1)
- mat_results[f] = (float(math.exp(min(avg, 20))),
- _estimate_mat_params(config, f), config.d_ff // f)
-
params_np = jax.tree.map(lambda x: np.array(x).astype(np.float16), eval_params)
total_params = sum(x.size for x in jax.tree.leaves(params_np))
@@ -685,20 +577,9 @@ def train(args):
_EVAL_BATCH = 32
# Prepare generation model (all hosts)
- if _MAT_FACTORS:
- from ..model.export import slice_params
- _max_factor = max(_MAT_FACTORS)
- _mat_params, _mat_config = slice_params(eval_params, config, _max_factor)
- _mat_params = jax.tree.map(jnp.array, _mat_params)
- _gen_model = EncoderDecoderTransformer(_mat_config)
- _gen_label = f"{_max_factor}x (d_ff={_mat_config.d_ff})"
- else:
- _mat_params = eval_params
- _gen_model = eval_model
- _gen_label = "full"
-
- _mat_params = _quantize_params(_mat_params, precision=_PRECISION)
- _gen_label += f" {_PRECISION.upper()}"
+ _gen_params = _quantize_params(eval_params, precision=_PRECISION)
+ _gen_model = eval_model
+ _gen_label = f"full {_PRECISION.upper()}"
# Split eval examples across hosts — each host generates its slice
total_eval = len(all_eval_examples)
@@ -716,7 +597,7 @@ def train(args):
leave=False, disable=not is_main):
_chunk = my_eval_examples[_ei:_ei + _EVAL_BATCH]
my_preds.extend(generate_batch(
- _gen_model, _mat_params, tokenizer,
+ _gen_model, _gen_params, tokenizer,
[ex["query"] for ex in _chunk],
[ex["tools"] for ex in _chunk],
max_gen_len=eval_gen_len,
@@ -724,7 +605,7 @@ def train(args):
constrained=False,
))
_gen_elapsed = time.perf_counter() - _gen_t0
- del _mat_params
+ del _gen_params
# All-gather predictions across hosts via padded token ID arrays
_MAX_PRED_TOKENS = eval_gen_len
@@ -942,24 +823,11 @@ def train(args):
_best_metric = pool_metrics.get("single", {}).get("call_f1", 0)
if _best_metric > best_call_f1:
best_call_f1 = _best_metric
- if config.no_feedforward:
- best_ckpt_path = os.path.join(args.checkpoint_dir, f"{experiment_name}_{args.num_layers}_{args.d_model}_best.pkl")
- else:
- best_ckpt_path = os.path.join(args.checkpoint_dir, f"{experiment_name}_{args.num_layers}_{args.d_model}_{config.d_ff}_best.pkl")
+ best_ckpt_path = os.path.join(args.checkpoint_dir, f"{experiment_name}_{args.num_layers}_{args.d_model}_best.pkl")
import shutil as _shutil
_shutil.copy2(ckpt_path, best_ckpt_path)
print(f" ** New best single call_f1={best_call_f1:.1%} → {best_ckpt_path}")
_upload_checkpoint(best_ckpt_path)
- if _MAT_FACTORS:
- from ..model.export import export_submodel
- for factor in _MAT_FACTORS:
- d_ff_sub = config.d_ff // factor
- mat_ckpt_path = os.path.join(
- args.checkpoint_dir,
- f"{experiment_name}_{args.num_layers}_{args.d_model}_{d_ff_sub}_best.pkl",
- )
- export_submodel(best_ckpt_path, factor, mat_ckpt_path)
- _upload_checkpoint(mat_ckpt_path)
retrieval_metrics = None
if has_contrastive and _CONTRASTIVE_WEIGHT > 0 and val_ds is not None:
@@ -978,14 +846,6 @@ def train(args):
print(f" Text loss {final_loss:>12.4f}")
print(f" Text val ppl {last_val_ppl:>12.2f}")
print(f" Quant val ppl {quant_val_ppl:>12.2f} ({_PRECISION.upper()})")
- if mat_results:
- print(f" ─────────────────────────────────────")
- print(f" Matryoshka sub-models:")
- print(f" {'factor':>6} {'d_ff':>6} {'val ppl':>10} {'params':>12}")
- print(f" {'1x':>6} {config.d_ff:>6} {last_val_ppl:>10.2f} {total_params:>12,} (full)")
- for factor in sorted(mat_results.keys()):
- mat_ppl, mat_params, ff_w = mat_results[factor]
- print(f" {str(factor)+'x':>6} {ff_w:>6} {mat_ppl:>10.2f} {mat_params:>12,}")
def _print_tc_metrics(label, metrics, pc):
if not metrics:
return
@@ -1061,9 +921,6 @@ def train(args):
"epoch/quant_val_ppl": quant_val_ppl,
"epoch": epoch + 1,
}
- for factor, (mat_ppl, mat_params, _) in mat_results.items():
- log_dict[f"epoch/mat_ppl_{factor}x"] = mat_ppl
- log_dict[f"epoch/mat_params_{factor}x"] = mat_params
for name in _pool_names:
m = pool_metrics.get(name)
if not m:
diff --git a/src/__init__.py b/needle/ui/__init__.py
similarity index 100%
rename from src/__init__.py
rename to needle/ui/__init__.py
diff --git a/src/ui/server.py b/needle/ui/server.py
similarity index 99%
rename from src/ui/server.py
rename to needle/ui/server.py
index 726e3f1..c980367 100644
--- a/src/ui/server.py
+++ b/needle/ui/server.py
@@ -586,7 +586,7 @@ def _start_finetune(tools_json, api_key):
proc = subprocess.Popen(
[
python, "-u",
- "-m", "src.training.finetune",
+ "-m", "needle.training.finetune",
str(data_file),
"--epochs", str(_EPOCHS),
"--batch-size", str(batch_size),
diff --git a/src/ui/static/app.js b/needle/ui/static/app.js
similarity index 100%
rename from src/ui/static/app.js
rename to needle/ui/static/app.js
diff --git a/src/ui/static/index.html b/needle/ui/static/index.html
similarity index 100%
rename from src/ui/static/index.html
rename to needle/ui/static/index.html
diff --git a/src/ui/static/style.css b/needle/ui/static/style.css
similarity index 100%
rename from src/ui/static/style.css
rename to needle/ui/static/style.css
diff --git a/src/utils/__init__.py b/needle/utils/__init__.py
similarity index 100%
rename from src/utils/__init__.py
rename to needle/utils/__init__.py
diff --git a/src/utils/distributed.py b/needle/utils/distributed.py
similarity index 100%
rename from src/utils/distributed.py
rename to needle/utils/distributed.py
diff --git a/src/utils/gcs.py b/needle/utils/gcs.py
similarity index 100%
rename from src/utils/gcs.py
rename to needle/utils/gcs.py
diff --git a/src/utils/tpu.py b/needle/utils/tpu.py
similarity index 97%
rename from src/utils/tpu.py
rename to needle/utils/tpu.py
index 3907747..5b7ecf7 100644
--- a/src/utils/tpu.py
+++ b/needle/utils/tpu.py
@@ -4,7 +4,27 @@ import re
import subprocess
import sys
-PROJECT = "needle-488623"
+def _get_project():
+ """Get GCP project from gcloud config or NEEDLE_GCP_PROJECT env var."""
+ proj = os.environ.get("NEEDLE_GCP_PROJECT")
+ if proj:
+ return proj
+ result = subprocess.run(
+ ["gcloud", "config", "get-value", "project"],
+ capture_output=True, text=True,
+ )
+ proj = result.stdout.strip()
+ if proj and proj != "(unset)":
+ return proj
+ print(
+ "[tpu] ERROR: no GCP project set. Either run 'gcloud config set project <PROJECT>' "
+ "or set NEEDLE_GCP_PROJECT environment variable.",
+ file=sys.stderr,
+ )
+ sys.exit(1)
+
+
+PROJECT = None # resolved lazily
VERSION_FOR_TYPE = {
"v6e": "v2-alpha-tpuv6e",
@@ -624,6 +644,8 @@ def tpu_pretrain(args):
def tpu_dispatch(args):
+ global PROJECT
+ PROJECT = _get_project()
actions = {
"create": tpu_create,
"connect": tpu_connect,
diff --git a/pyproject.toml b/pyproject.toml
index 0221728..08b0472 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -23,10 +23,10 @@ tpu = ["jax[tpu]"]
gpu = ["jax[cuda12]"]
[project.scripts]
-needle = "src.cli:main"
+needle = "needle.cli:main"
[tool.setuptools.packages.find]
-include = ["src*"]
+include = ["needle*"]
[build-system]
requires = ["setuptools>=68.0"]
diff --git a/src/ui/__init__.py b/src/ui/__init__.py
deleted file mode 100644
index e69de29..0000000