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.

restructure

HenryNdubuaku37c9e021bed5
diff --git a/.gitignore b/.gitignore
index 8a9b9a2..1afe2fe 100644
--- a/.gitignore
+++ b/.gitignore
@@ -90,4 +90,5 @@ wandb/
.data_cache/
tokenizer/
data/
-voice_samples/
\ No newline at end of file
+voice_samples/
+needle-ui.*
\ No newline at end of file
diff --git a/README.md b/README.md
index 00288c7..89cca9b 100644
--- a/README.md
+++ b/README.md
@@ -4,16 +4,17 @@
│ ┌─┐┌─┐┌─┐┌┬┐┬ ┬┌─┐ ┌┐┌┌─┐┌─┐┌┬┐┬ ┌─┐ │
│ │ ├─┤│ │ │ │└─┐ │││├┤ ├┤ │││ ├┤ │
│ └─┘┴ ┴└─┘ ┴ └─┘└─┘ ┘└┘└─┘└─┘─┴┘┴─┘└─┘ │
- │ ...the tiny model to rule them all... │
+ │ ...a 26m function call model for edge... │
└────────────────────────────────────────────────────────┘
+```
- Architecture
- ────────────
+# Simple Attention Networks
- Pure-attention encoder-decoder. No feedforward layers — each block is
- just gated self-attention (encoder) or gated self + cross attention
- (decoder). All mixing happens through attention.
+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.
+```
+d=512, 8H/4KV, BPE=8192
┌──────────────┐
│ Tool Call │
└──────┬───────┘
@@ -27,7 +28,7 @@
│ ZCRMSNorm │
└─────┬─────┘
┌────────┴────────┐
- │ Decoder x 12 │
+ │ Decoder x 8 │
│┌───────────────┐│
││ ZCRMSNorm ││
││ Masked Self ││
@@ -46,302 +47,201 @@
│ │ (no FFN) │ │ │[EOS]<tool_call>│
│ └──────────┘ │ │ + answer │
│ │ └───────────────-┘
- │ DW Conv ↓2 │ stride-2 depthwise-separable
- │ + Pointwise │ (speech pathway only)
└──────┬───────┘
│
- ┌────┴──────┐ ┌──────────────┐
- │ Embedding │ │ Mel Proj │
- │ (text) │ │ (speech) │
- └────┬──────┘ └──────┬───────┘
- │ │
- ┌────┴──────┐ ┌──────┴───────┐
- │ Text │ │ Audio │
- │ query │ │ waveform │
- └───────────┘ └──────────────┘
-
- Heads
- ─────
- ┌─────────────────────────────────────────────────────────────┐
- │ │
- │ Contrastive Head CLIP-style tool retrieval │
- │ encoder → mean_pool → Dense(d_model/4) → ReLU │
- │ → Dense(contrastive_dim) → L2-normalize │
- │ learnable temperature (log_temp) │
- │ │
- │ Confidence Head cloud routing / hybrid inference │
- │ encoder → mean_pool → Dense(d_model/4) │
- │ → ReLU → Dense(1) → sigmoid → [0, 1] │
- │ trained post-hoc on perplexity-derived labels │
- │ high = handle locally, low = route to cloud │
- │ │
- └─────────────────────────────────────────────────────────────┘
-
- Training Pipeline
- ─────────────────
- ┌─────────────────────────────────────────────────────────────┐
- │ Contrastive loss + token-level weighting + z-loss │
- │ Grad clip (norm 1.0) · Muon (2D kernels) · AdamW (rest) │
- │ WSD LR schedule (warmup → hold → cosine decay) │
- │ Grammar-constrained decoding (trie-based token masking) │
- └─────────────────────────────────────────────────────────────┘
-
- d=512 · 12 enc / 12 dec layers · GQA (8H / 4KV) · QK-norm
- no FFN (pure attention) · gated residuals (init=0.5)
- SentencePiece BPE (8192) · ZCRMSNorm · RoPE
- text + speech encoder · <tool_call> task routing
- CLIP contrastive retrieval · confidence-based cloud routing
- token-level loss weighting · grammar-constrained decoding
-
- Data Pipeline (needle generate-data → needle tokenize → needle train)
- ─────────────────────────────────────────────────────────────────────
-
- ┌─────────────────────────────────────────────────────────────┐
- │ needle generate-data │
- │ │
- │ Gemini synthesis → Cactus-Compute/tool-calls (HuggingFace) │
- │ parallel workers · dedup · auto-merge · auto-upload │
- └─────────────────────────────────────────────────────────────┘
- │
- ▼
- ┌─────────────────────────────────────────────────────────────┐
- │ needle tokenize │
- │ │
- │ GCS download (gs://cactus-dataset/tool_calls/) │
- │ │ │
- │ ▼ │
- │ Unified dataset (.arrow) │
- │ │ │
- │ ▼ │
- │ ┌──────────────┐ │
- │ │ SentencePiece│ trains tokenizer from corpus │
- │ │ BPE tokenize │ special: <tool_call> <tools> │
- │ │ (8192 vocab) │ byte_fallback, identity normalization │
- │ └──────┬───────┘ │
- │ │ │
- │ ▼ │
- │ ┌───────────────────────┐ ┌───────────────────────┐ │
- │ │ enc_inputs.npy │ │ query_only.npy │ │
- │ │ dec_inputs.npy │ │ tool_individual.npy │ │
- │ │ dec_targets.npy │ │ tool_ex_idx.npy │ │
- │ │ loss_mask.npy │ │ tool_is_pos.npy │ │
- │ │ kept_idx.npy │ │ (contrastive arrays) │ │
- │ │ tool_count.npy │ └───────────────────────┘ │
- │ └──────┬────────────────┘ │
- │ ▼ │
- │ {split}_metadata.json → .data_cache/ │
- │ uploads tokenizer + arrays to GCS │
- └─────────────────────────────────────────────────────────────┘
- │
- ▼
- ┌─────────────────────────────────────────────────────────────┐
- │ needle train │
- │ │
- │ load_prepared_data(mmap=True) │
- │ │ │
- │ ▼ │
- │ ┌──────────────────────┐ ┌──────────────────────┐ │
- │ │ PrefetchIterator │ │ Contrastive batches │ │
- │ │ text batches (4) │ │ query-tool pairs │ │
- │ │ mmap → per-batch idx │ │ CLIP in-batch neg │ │
- │ └──────────┬───────────┘ └──────────┬───────────┘ │
- │ ▼ ▼ │
- │ text + contrastive tool-call training (jax.pmap) │
- └─────────────────────────────────────────────────────────────┘
-
- Hybrid Inference (confidence-based cloud routing)
- ─────────────────────────────────────────────────
-
- ┌─────────────────────────────────────────────────────────────┐
- │ │
- │ query + tools │
- │ │ │
- │ ▼ │
- │ ┌──────────┐ │
- │ │ Encoder │ │
- │ └────┬─────┘ │
- │ │ │
- │ ├──────────────────┐ │
- │ ▼ ▼ │
- │ ┌──────────┐ ┌──────────────┐ │
- │ │Confidence│ │ (encoder │ │
- │ │ Head │ │ output) │ │
- │ └────┬─────┘ └──────┬───────┘ │
- │ │ │ │
- │ ▼ │ │
- │ confidence > threshold?│ │
- │ │ │ │
- │ ┌──┴──┐ │ │
- │ │ yes │──────────────┤ │
- │ └─────┘ ▼ │
- │ ┌──────────┐ │
- │ │ Decoder │──▶ tool calls (local) │
- │ └──────────┘ │
- │ ┌─────┐ │
- │ │ no │──▶ route to cloud (Gemini) ──▶ tool calls │
- │ └─────┘ (skip decoder entirely) │
- │ │
- └─────────────────────────────────────────────────────────────┘
+ ┌────┴──────┐
+ │ Embedding │
+ └────┬──────┘
+ │
+ ┌────┴──────┐
+ │ Text │
+ │ query │
+ └───────────┘
```
-## Usage
+## 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.
+
+## Training
+
+- 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).
+
+## Test Needle & Finetune Locally On Your Mac
```
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.
-source ./setup
-needle [command]
+## Needle CLI
+```
┌───────────────────────────────────────────────────────────────────┐
│ │
+ │ ui Web UI for inference + finetuning │
+ │ --checkpoint PATH Model checkpoint (optional, │
+ │ auto-downloads from HuggingFace) │
+ │ --port INT Server port (default: 7860) │
+ │ --host STR Bind address (default: 127.0.0.1) │
+ │ │
+ │ run │
+ │ --checkpoint PATH Path to model checkpoint (required)│
+ │ --query STR Query text for tool-call generation│
+ │ --tools STR Tools JSON for tool-call generation│
+ │ --max-len INT Max tokens to generate (default:512│
+ │ --seed INT Random seed (default: 0) │
+ │ --no-constrained Disable constrained decoding │
+ │ │
│ train │
- │ --epochs INT Training epochs (default: 1) │
- │ --batch-size INT Batch size (default: 32) │
- │ --lr FLOAT AdamW learning rate (default: 3e-5) │
- │ --muon-lr FLOAT Muon learning rate (default: 0.02) │
- │ --d-model INT Model dim (default: 512) │
- │ --num-heads INT Attention heads (default: 8) │
- │ --num-kv-heads INT KV heads for GQA (default: 4) │
- │ --num-layers INT Encoder layers (default: 12) │
- │ --num-dec-layers INT Decoder layers (default: 12) │
- │ --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 enabled) │
- │ --mat-factors INT [...] FFN shrink factors (if FFN enabled) │
- │ --sparsity-ratio FLOAT Block prune ratio (default: 0.0) │
- │ --group-size INT Quant/prune group size (default: 32) │
- │ --prune-interval INT Steps between mask updates (def: 100)│
- │ --prune-start-frac FL Start pruning at frac (def: 0.33) │
- │ --prune-end-frac FL Lock mask at this frac (def: 0.67) │
- │ --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) │
- │ --contrastive-dim INT Projection dim (default: 128) │
- │ --w-name FLOAT Loss weight: tool names (def: 2.0) │
- │ --w-value FLOAT Loss weight: arg values (def: 4.0) │
- │ --w-key FLOAT Loss weight: arg keys (def: 1.5) │
- │ --wandb Enable W&B logging │
- │ --checkpoint PATH Resume from checkpoint │
- │ --checkpoint-dir DIR Checkpoint directory │
- │ --dtype STR float32|bfloat16 (default: bfloat16) │
- │ --seed INT Random seed (default: 42) │
+ │ --name STR Experiment name (default: baseline)│
+ │ --checkpoint PATH Resume from checkpoint │
+ │ --init-from PATH Init params from pretrained base │
+ │ --epochs INT Training epochs (default: 1) │
+ │ --batch-size INT Batch size (default: 64) │
+ │ --lr FLOAT AdamW learning rate (default: 3e-5)│
+ │ --muon-lr FLOAT Muon learning rate (default: 0.02) │
+ │ --d-model INT Model dim (default: 512) │
+ │ --num-heads INT Attention heads (default: 8) │
+ │ --num-kv-heads INT KV heads for GQA (default: 4) │
+ │ --num-layers INT Encoder layers (default: 12) │
+ │ --num-dec-layers INT Decoder layers (default: 8) │
+ │ --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) │
+ │ --contrastive-dim INT Projection dim (default: 128) │
+ │ --w-name FLOAT Loss weight: tool names (def: 2.0) │
+ │ --w-value FLOAT Loss weight: arg values (def: 4.0) │
+ │ --w-key FLOAT Loss weight: arg keys (def: 1.5) │
+ │ --wandb Enable W&B logging │
+ │ --checkpoint-dir DIR Checkpoint directory │
+ │ --dtype STR float32|bfloat16 (default: bfloat16│
+ │ --seed INT Random seed (default: 42) │
│ │
- │ tokenize │
- │ --max-samples INT Limit samples per split (dev/test) │
- │ --max-enc-len INT Max encoder seq len (default: 1024) │
- │ --max-dec-len INT Max decoder seq len (default: 512) │
- │ --shuffle-tools Shuffle tool order (default: on) │
- │ --no-shuffle-tools Disable tool shuffling │
- │ --max-tool-len INT Max tool desc tokens (default: 256) │
+ │ pretrain │
+ │ --name STR Experiment name (default: pretrain) │
+ │ --checkpoint PATH Resume from checkpoint │
+ │ --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)│
+ │ --muon-lr FLOAT Muon learning rate (default: 0.02) │
+ │ --max-steps INT Stop after N steps (default: full) │
+ │ --save-every INT Checkpoint interval (default: 1000)│
+ │ --wandb Enable W&B logging │
+ │ (also accepts --d-model, --num-heads, etc. same as train) │
│ │
- │ run │
- │ --checkpoint PATH Path to model checkpoint (required) │
- │ --query STR Query text for tool-call generation │
- │ --tools STR Tools JSON for tool-call generation │
- │ --audio PATH [...] Audio files for voice-to-tool-call │
- │ --max-len INT Max tokens to generate (default: 512)│
- │ --seed INT Random seed (default: 0) │
- │ --no-constrained Disable constrained decoding │
+ │ tokenize │
+ │ --max-samples INT Limit samples per split (dev/test) │
+ │ --max-enc-len INT Max encoder seq len (default: 1024)│
+ │ --max-dec-len INT Max decoder seq len (default: 512) │
+ │ --shuffle-tools Shuffle tool order (default: on) │
+ │ --no-shuffle-tools Disable tool shuffling │
+ │ --max-tool-len INT Max tool desc tokens (default: 256)│
│ │
│ eval │
- │ --checkpoint PATH Path to model checkpoint (required) │
- │ --batch-size INT Batch size (default: 32) │
- │ --max-eval-samples INT Evaluation samples (default: 5000) │
- │ --max-enc-len INT Max encoder length (default: 1024) │
- │ --max-dec-len INT Max decoder length (default: 512) │
- │ --max-gen-len INT Max generation length (default: 512) │
- │ --throughput-runs INT Throughput runs (default: 10) │
- │ --tool-call-samples INT Tool-call eval samples (default: 200)│
- │ --no-constrained Disable constrained decoding │
+ │ --checkpoint PATH Path to model checkpoint (required)│
+ │ --batch-size INT Batch size (default: 32) │
+ │ --max-eval-samples INT Evaluation samples (default: 5000) │
+ │ --max-enc-len INT Max encoder length (default: 1024) │
+ │ --max-dec-len INT Max decoder length (default: 512) │
+ │ --max-gen-len INT Max generation length (default:512)│
+ │ --throughput-runs INT Throughput runs (default: 10) │
+ │ --tool-call-samples INT Tool-call eval samples (default:200│
+ │ --no-constrained Disable constrained decoding │
│ │
│ generate-data │
- │ --num-samples INT Samples to generate (default: 5000) │
- │ --batch-size INT Examples per Gemini call (default:10)│
- │ --workers INT Parallel Gemini calls (default: 8) │
- │ --model STR Gemini model override │
- │ --dry-run Generate only, skip upload │
- │ --output-jsonl PATH Also save raw generations to JSONL │
- │ --upload-every INT Merge+upload interval (def: 30000) │
- │ │
- │ evaluate │
- │ --checkpoint PATH Path to model checkpoint (required) │
- │ --benchmarks [...] wikitext2 lambada hellaswag arc_easy │
- │ --max-samples INT Samples per benchmark (default: 500) │
+ │ --num-samples INT Samples to generate (default: 500) │
+ │ --batch-size INT Examples per Gemini call (default:25│
+ │ --workers INT Parallel Gemini calls (default: 8) │
+ │ --model STR Gemini model override │
+ │ --dry-run Generate only, skip upload │
+ │ --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 │
- │ 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 │
+ │ 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 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 from GCS
- gs://cactus-dataset/
- ──────────────────────────────────────────
-
- ┌────────────────────┬──────────┬──────────┬──────────┐
- │ │ 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 │
- └────────────────────┴──────────┴──────────┴──────────┘
-```
-
-## Finetuning
-
-See [src/ui/README.md](src/ui/README.md) for finetuning needle on your own tools, via the web UI or CLI.
-
## 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 needle-488623`
+- Setup gcloud 4: else, set the project with `gcloud config set [PROJECT NAME]`
- Setup gcloud 5: run `gcloud help` and read carefully
-## Example Workflow
-
-### Single-host (v6e-8) — SSH into instance
+### Single-host (v6e-8) -SSH into instance
```
1. Create an instance (auto: finds zone → installs Claude Code → connects via SSH)
@@ -364,7 +264,7 @@ See [src/ui/README.md](src/ui/README.md) for finetuning needle on your own tools
5. Login to Hugging Face (required for private datasets)
hf auth login
- (paste your HF token — get one at https://huggingface.co/settings/tokens)
+ (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
@@ -374,18 +274,17 @@ See [src/ui/README.md](src/ui/README.md) for finetuning needle on your own tools
--- back on your Mac ---
-9. Stop when done (saves disk, stops billing)
+7. Stop when done (saves disk, stops billing)
needle tpu stop my-experiment
-10. (Optional) Delete instance when no longer needed
- needle tpu delete my-experiment
+8. (Optional) Delete instance when no longer needed
+ needle tpu delete my-experiment
```
-### Multi-host (v6e-16+) — run from your Mac
+### Multi-host (v6e-16+) -run from your Mac
-For multi-host TPUs (v6e-16 = 4 workers, v6e-32 = 8 workers), you drive
-everything from your Mac. The CLI syncs code and launches training across
-all workers automatically.
+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)
@@ -410,4 +309,4 @@ all workers automatically.
7. Stop/delete when done
needle tpu stop my-experiment
needle tpu delete my-experiment
-```
\ No newline at end of file
+```
diff --git a/dataset_readme.md b/dataset_readme.md
deleted file mode 100644
index 5c1a23e..0000000
--- a/dataset_readme.md
+++ /dev/null
@@ -1,211 +0,0 @@
----
-dataset_info:
- features:
- - name: query
- dtype: string
- - name: answers
- dtype: string
- - name: tools
- dtype: string
- - name: source
- dtype: string
- - name: model
- dtype: string
- splits:
- - name: train
- num_examples: 2996257
- - name: validation
- num_examples: 10000
- download_size: 2160782760
-configs:
-- config_name: default
- data_files:
- - split: train
- path: data/train-*
- - split: validation
- path: data/validation-*
-license: apache-2.0
-task_categories:
-- text-generation
-language:
-- en
-tags:
-- tool-calling
-- function-calling
-- on-device
-- assistant
-- synthetic
-pretty_name: On-Device Tool Calls
-size_categories:
-- 1M<n<10M
----
-
-# On-Device Tool Calls
-
-A large-scale synthetic dataset for training compact tool-calling models. Designed for on-device assistants that run on phones, wearables, smart home hubs, and laptops — where latency and model size matter.
-
-Built for [Needle](https://github.com/Cactus-Compute/needle), a 32M-parameter encoder-decoder transformer that achieves 92% single-call F1 and 78% multi-call F1 on tool-call generation.
-
-## Overview
-
-| | |
-|---|---|
-| **Examples** | 2,996,257 train / 10,000 validation |
-| **Unique tool names** | ~1.75M (232 curated + millions from open-source sources) |
-| **Tool categories** | 23 on-device domains |
-| **Languages** | English (primary), some multilingual queries |
-| **License** | Apache 2.0 |
-
-## Schema
-
-Each example has 5 fields:
-
-| Field | Type | Description |
-|---|---|---|
-| `query` | string | Natural language user request (e.g. *"Set a timer for 10 minutes"*) |
-| `tools` | string | JSON array of available tool definitions with names, descriptions, and parameter schemas |
-| `answers` | string | JSON array of tool calls the assistant should make (e.g. `[{"name": "set_timer", "arguments": {"time_human": "10 minutes"}}]`) |
-| `source` | string | Data source identifier |
-| `model` | string | Model used for generation |
-
-### Example
-
-```json
-{
- "query": "Turn off the bedroom lights and lock the front door",
- "tools": "[{\"name\":\"control_lights\",\"description\":\"Turn lights on or off in a specific room.\",\"parameters\":{\"room\":{\"type\":\"string\"},\"action\":{\"type\":\"string\"}}},{\"name\":\"lock_door\",\"description\":\"Lock or unlock a smart door lock.\",\"parameters\":{\"door\":{\"type\":\"string\"},\"action\":{\"type\":\"string\"}}}]",
- "answers": "[{\"name\":\"control_lights\",\"arguments\":{\"room\":\"bedroom\",\"action\":\"off\"}},{\"name\":\"lock_door\",\"arguments\":{\"door\":\"front door\",\"action\":\"lock\"}}]",
- "source": "synth-gemini-assistant",
- "model": "gemini-3.1-flash-lite-preview"
-}
-```
-
-## Data Sources
-
-The dataset is a blend of four sources, each contributing different strengths:
-
-### synth-gemini-assistant (1.10M examples, 36.8%)
-
-Custom synthetic data generated with Gemini Flash Lite using a curated pool of **232 tools across 23 on-device categories**. Each batch is generated with a randomized subset of tools and a specified call type (single, multi, or no-call). Queries span ultra-terse commands (*"timer 5"*), conversational requests, indirect intent (*"it's dark in here"*), and multilingual input.
-
-**Tool categories (232 tools):**
-
-| Category | Tools | Examples |
-|---|---|---|
-| Time & Productivity | 15 | `set_timer`, `set_alarm`, `create_reminder`, `create_calendar_event` |
-| Lists & Notes | 21 | `create_list_item`, `create_note`, `mark_list_item_done`, `pin_note` |
-| Messaging | 10 | `send_instant_message`, `make_phone_call`, `send_email`, `send_sms` |
-| Device Control | 14 | `set_brightness`, `set_volume`, `toggle_wifi`, `toggle_bluetooth` |
-| Media | 14 | `play_music`, `pause_media`, `play_podcast`, `cast_media` |
-| Navigation | 9 | `get_directions`, `find_nearby`, `share_location`, `start_navigation` |
-| Smart Home | 12 | `set_thermostat`, `control_lights`, `lock_door`, `start_robot_vacuum` |
-| Utility | 15 | `evaluate_js`, `web_search`, `translate_text`, `get_weather` |
-| Camera & Photos | 10 | `take_photo`, `record_video`, `share_photo`, `search_photos` |
-| Fitness & Health | 10 | `start_workout`, `log_water_intake`, `get_step_count`, `log_meal` |
-| System | 7 | `toggle_airplane_mode`, `clear_notifications`, `check_battery` |
-| Finance | 10 | `send_payment`, `check_balance`, `convert_currency`, `get_stock_price` |
-| Reading & News | 10 | `get_news_headlines`, `read_aloud`, `summarize_page`, `open_ebook` |
-| Accessibility | 4 | `set_font_size`, `toggle_screen_reader`, `toggle_magnifier` |
-| Shopping | 3 | `search_product`, `add_to_cart`, `check_order_status` |
-| Social | 10 | `post_status_update`, `like_post`, `comment_on_post`, `follow_user` |
-| Ride & Delivery | 6 | `request_ride`, `order_food`, `track_food_delivery` |
-| File Management | 7 | `open_file`, `share_file`, `move_file`, `compress_files` |
-| Wearable | 10 | `check_heart_rate`, `find_my_phone`, `change_watch_face` |
-| Desktop | 13 | `split_screen`, `toggle_vpn`, `print_document`, `kill_process` |
-| Browser | 6 | `open_tab`, `bookmark_page`, `clear_browsing_data` |
-| Emergency & Safety | 8 | `call_emergency_services`, `share_emergency_location` |
-| Digital Wellbeing | 8 | `check_screen_time`, `set_app_timer`, `toggle_bedtime_mode` |
-
-### synth-pleias (1.00M examples, 33.5%)
-
-Reprompted from [Pleias](https://huggingface.co/Pleias) open-source tool-calling data. Original examples were reprompted through Gemini to normalize tool schemas and query styles to match the on-device assistant domain. Provides diverse query patterns and broader tool coverage.
-
-### synth-gcs (832K examples, 27.8%)
-
-Reprompted from [Toucan](https://huggingface.co/datasets/Salesforce/Toucan) (Salesforce) tool-calling data via Gemini. Contributes high multi-call density (68.8% multi-call) and diverse tool combinations from the Salesforce ecosystem.
-
-### xlam-function-calling-60k (58K examples, 1.9%)
-
-Human-curated examples from [xLAM](https://huggingface.co/datasets/Salesforce/xlam-function-calling-60k) (Salesforce). High-quality ground truth with verified tool calls. Provides a quality anchor for the synthetic majority.
-
-## Distribution
-
-### Call Type
-
-```
-Single-call (1 tool): 1,064,063 (35.5%)
-Multi-call (2+ tools): 1,761,740 (58.8%)
-No-call (empty []): 170,454 ( 5.7%)
-```
-
-### Calls Per Example
-
-```
-0 calls: 170,454 ( 5.7%) ░░░░░░
-1 call: 1,064,063 (35.5%) ████████████████████████████████████
-2 calls: 1,445,299 (48.2%) ████████████████████████████████████████████████
-3 calls: 261,474 ( 8.7%) █████████
-4 calls: 38,057 ( 1.3%) █
-5+ calls: 16,910 ( 0.6%) ░
-```
-
-### Available Tools Per Example
-
-The tool count distribution has been rebalanced from its original skewed form (28% at 3 tools, 27% at 10 tools) to a near-uniform distribution across 1-10 tools. This was done by trimming uncalled tools from over-represented bins while preserving all called tools and answer correctness.
-
-```
- 0 tools: 101,974 ( 3.4%) ███
- 1 tool: 334,077 (11.1%) ███████████
- 2 tools: 361,916 (12.1%) ████████████
- 3 tools: 280,541 ( 9.4%) █████████
- 4 tools: 234,639 ( 7.8%) ████████
- 5 tools: 280,186 ( 9.4%) █████████
- 6 tools: 284,218 ( 9.5%) █████████
- 7 tools: 292,442 ( 9.8%) ██████████
- 8 tools: 281,952 ( 9.4%) █████████
- 9 tools: 278,085 ( 9.3%) █████████
-10 tools: 266,224 ( 8.9%) █████████
-```
-
-### Call Type by Source
-
-| Source | Single | Multi | No-call |
-|---|---|---|---|
-| synth-gemini-assistant | 31.2% | 60.0% | 8.8% |
-| synth-pleias | 43.8% | 49.4% | 6.8% |
-| synth-gcs | 30.6% | 68.8% | 0.6% |
-| xlam | 46.0% | 54.0% | 0.0% |
-
-### Field Lengths (characters)
-
-| Field | Mean | Median | P95 |
-|---|---|---|---|
-| query | 210 | 121 | 670 |
-| answers | 210 | 161 | 510 |
-| tools | 1,936 | 1,884 | 3,611 |
-
-## Intended Use
-
-This dataset is designed for training **small, fast tool-calling models** (10M-200M parameters) that run on-device. The model receives a user query and a set of available tool definitions, then generates the appropriate JSON tool calls.
-
-**Target architecture:** Encoder-decoder transformer where the encoder processes `[query <tools> tool_definitions]` and the decoder generates `[<tool_call> JSON_tool_calls]`.
-
-**Not intended for:** General-purpose language modeling, chat, or instruction following.
-
-## Known Limitations
-
-- **Synthetic data:** ~98% of examples are LLM-generated. While filtered for schema validity, some argument values may be unrealistic.
-- **English-centric:** Queries are predominantly English with occasional multilingual examples.
-- **Multi-call with few tools:** The hardest setting (1-3 tools, 2+ calls with different argument values) is underrepresented relative to its difficulty. Targeted generation of these examples is ongoing.
-- **No audio:** The dataset is text-only. Audio-to-tool-call requires separate speech data.
-
-## Citation
-
-```bibtex
-@misc{cactus-compute-tool-calls-2025,
- title={On-Device Tool Calls: A Large-Scale Synthetic Dataset for Compact Tool-Calling Models},
- author={Cactus Compute},
- year={2025},
- url={https://huggingface.co/datasets/Cactus-Compute/tool-calls}
-}
-```
diff --git a/debug_nan.py b/debug_nan.py
deleted file mode 100644
index f3338b8..0000000
--- a/debug_nan.py
+++ /dev/null
@@ -1,104 +0,0 @@
-"""Debug why train.py produces NaN from step 0. Run on a TPU worker."""
-import pickle
-import jax
-import jax.numpy as jnp
-import numpy as np
-import optax
-
-from src.model import (
- EncoderDecoderTransformer, TransformerConfig,
- make_packing_mask, make_causal_packing_mask, make_cross_packing_mask,
-)
-from src.data import load_prepared_data
-
-print("=" * 60)
-print("Loading checkpoint...")
-with open("checkpoints/needle_base.pkl", "rb") as f:
- ckpt = pickle.load(f)
-config = TransformerConfig(**ckpt["config"])
-params = jax.tree.map(jnp.array, ckpt["params"])
-print(f" config: d={config.d_model} heads={config.num_heads} layers={config.num_encoder_layers}/{config.num_decoder_layers}")
-print(f" dtype={config.dtype} no_ff={config.no_feedforward}")
-
-print("Loading data...")
-data = load_prepared_data("train", mmap=True)
-bs = 4
-src = jnp.asarray(data["packed_enc"][:bs], dtype=jnp.int32)
-tgt_in = jnp.asarray(data["packed_dec_in"][:bs], dtype=jnp.int32)
-tgt_out = jnp.asarray(data["packed_dec_tgt"][:bs], dtype=jnp.int32)
-enc_seg = jnp.asarray(data["packed_enc_seg"][:bs], dtype=jnp.int32)
-dec_seg = jnp.asarray(data["packed_dec_seg"][:bs], dtype=jnp.int32)
-lm = jnp.asarray(data["packed_loss"][:bs], dtype=jnp.int32)
-
-print(f" src: shape={src.shape} range=[{int(src.min())}, {int(src.max())}]")
-print(f" tgt_in: shape={tgt_in.shape} range=[{int(tgt_in.min())}, {int(tgt_in.max())}]")
-print(f" tgt_out: shape={tgt_out.shape} range=[{int(tgt_out.min())}, {int(tgt_out.max())}]")
-print(f" enc_seg: range=[{int(enc_seg.min())}, {int(enc_seg.max())}] nnz_rows={int((enc_seg.sum(axis=-1) > 0).sum())}/{bs}")
-print(f" dec_seg: range=[{int(dec_seg.min())}, {int(dec_seg.max())}] nnz_rows={int((dec_seg.sum(axis=-1) > 0).sum())}/{bs}")
-print(f" lm: range=[{int(lm.min())}, {int(lm.max())}]")
-
-print("=" * 60)
-print("Checking params for NaN/Inf...")
-any_bad = False
-for path, leaf in jax.tree_util.tree_leaves_with_path(params):
- n_bad = int(jnp.sum(~jnp.isfinite(leaf)))
- if n_bad:
- any_bad = True
- print(f" BAD {path}: {n_bad} nonfinite")
-if not any_bad:
- print(" all params finite")
-
-print("=" * 60)
-print("Building masks...")
-src_mask = make_packing_mask(enc_seg)
-tgt_mask = make_causal_packing_mask(dec_seg)
-cross_mask = make_cross_packing_mask(enc_seg, dec_seg)
-print(f" src_mask: {src_mask.shape} true_frac={float(src_mask.mean()):.3f}")
-print(f" tgt_mask: {tgt_mask.shape} true_frac={float(tgt_mask.mean()):.3f}")
-print(f" cross_mask: {cross_mask.shape} true_frac={float(cross_mask.mean()):.3f}")
-
-# Check if any attention row is all-False
-def all_false_rows(m):
- # m: (B, 1, T_q, T_k)
- return int((~m.any(axis=-1)).sum())
-print(f" src_mask all-False rows: {all_false_rows(src_mask)}")
-print(f" tgt_mask all-False rows: {all_false_rows(tgt_mask)}")
-print(f" cross_mask all-False rows: {all_false_rows(cross_mask)}")
-
-print("=" * 60)
-print("Running __call__ forward (no dropout)...")
-model = EncoderDecoderTransformer(config)
-logits = model.apply({"params": params}, src, tgt_in,
- src_mask=src_mask, tgt_mask=tgt_mask, cross_mask=cross_mask)
-print(f" logits: shape={logits.shape} dtype={logits.dtype}")
-print(f" NaN={int(jnp.sum(jnp.isnan(logits)))} Inf={int(jnp.sum(jnp.isinf(logits)))}")
-print(f" min={float(jnp.min(logits)):+.3g} max={float(jnp.max(logits)):+.3g}")
-
-logits_f32 = logits.astype(jnp.float32)
-ce = optax.softmax_cross_entropy_with_integer_labels(logits_f32, tgt_out)
-print(f" CE: NaN={int(jnp.sum(jnp.isnan(ce)))} min={float(jnp.min(ce)):+.3g} max={float(jnp.max(ce)):+.3g}")
-padding = (dec_seg > 0).astype(jnp.float32)
-num_tok = jnp.sum(padding)
-ce_loss = jnp.sum(ce * padding) / jnp.maximum(num_tok, 1.0)
-print(f" masked CE loss: {float(ce_loss):.4f} (num_tok={float(num_tok):.0f})")
-
-# Check z_loss
-lse = jax.nn.logsumexp(logits_f32, axis=-1)
-print(f" logsumexp: NaN={int(jnp.sum(jnp.isnan(lse)))} min={float(jnp.min(lse)):+.3g} max={float(jnp.max(lse)):+.3g}")
-z_loss = 1e-4 * jnp.mean(lse ** 2)
-print(f" z_loss: {float(z_loss):.4f}")
-
-print("=" * 60)
-print("Running forward_masked (with dropout)...")
-ffn_mask = jnp.ones((bs, config.d_ff), dtype=config.jax_dtype)
-logits2, _ = model.apply(
- {"params": 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": jax.random.PRNGKey(0)},
-)
-print(f" logits: NaN={int(jnp.sum(jnp.isnan(logits2)))} Inf={int(jnp.sum(jnp.isinf(logits2)))}")
-print(f" min={float(jnp.min(logits2)):+.3g} max={float(jnp.max(logits2)):+.3g}")
-
-ce2 = optax.softmax_cross_entropy_with_integer_labels(logits2.astype(jnp.float32), tgt_out)
-print(f" CE: NaN={int(jnp.sum(jnp.isnan(ce2)))} min={float(jnp.min(ce2)):+.3g} max={float(jnp.max(ce2)):+.3g}")
diff --git a/notes/architecture.txt b/notes/architecture.txt
deleted file mode 100644
index 2d2c838..0000000
--- a/notes/architecture.txt
+++ /dev/null
@@ -1,144 +0,0 @@
-Architecture: Attention-Only Encoder-Decoder
-============================================
-
-Supports main.txt sections 2.1-2.2, 3.1-3.2.
-Core architectural reasoning for the paper.
-
-
-## 1. The No-FFN Argument
-
-We distill Gemini's tool-calling capability into a ~25M parameter
-model. The central architectural bet: the student doesn't need FFN
-because the task it's learning (structured generation from a teacher)
-is retrieval-and-assembly, not reasoning.
-
-Four observations:
-
- (1) Softmax is nonlinear. Each attention layer computes
- softmax(QK^T/sqrt(d)) * V - a data-dependent nonlinear mixing
- operation. An MLP transforms features element-wise; attention
- transforms features by routing information between positions.
- For a task that IS about routing information (query -> tool
- alignment), attention is the right primitive.
-
- (2) Tool calling is structured retrieval-and-assembly. The model
- must: (a) match query to tool name, (b) extract argument values
- from the query, (c) assemble valid JSON. All three are about
- aligning and copying between input and output - exactly what
- cross-attention does. No step requires per-position feature
- transformation (which is what FFN provides).
-
- (3) 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 the same budget spent
- on more attention layers (deeper cross-attention = better
- query-tool alignment).
-
- (4) Fewer parameters = faster inference. Removing FFN cuts per-layer
- parameters by ~2/3, directly reducing the memory bandwidth
- bottleneck that dominates latency on edge devices.
-
-
-## 2. Block Structure
-
-Encoder block (x12):
- g = sigmoid(gate) # learnable scalar, init=0 -> g=0.5
- x = x + g * SelfAttn(ZCRMSNorm(x)) # GQA + RoPE + gated residual
-
-Decoder block (x12):
- g_s = sigmoid(self_attn_gate)
- g_c = sigmoid(cross_attn_gate)
- x = x + g_s * SelfAttn(ZCRMSNorm(x)) # causal, GQA + RoPE
- x = x + g_c * CrossAttn(ZCRMSNorm(x)) # attends to encoder output
-
-No feedforward, no activation function in the backbone. The only
-nonlinearities are softmax (attention) and sigmoid (gates).
-
-d=512, 8H/4KV (GQA), tied embeddings, RoPE, BPE 8192.
-
-
-## 3. Gated Residuals
-
-Without FFN, there is no per-position nonlinear rewriting per layer.
-This makes the residual connection design critical:
-
- Standard residual (x = x + Attn(Norm(x))):
- Attention can only ADD a delta. Without FFN to do the "rewriting,"
- forcing attention into a purely additive role 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.
-
-
-## 4. 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: at init, the entire block is 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.
-
-
-## 5. Why Encoder-Decoder
-
- (a) 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.
-
- (b) 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.
-
- (c) Natural fit for multi-head design. The encoder output feeds the
- decoder (generation), contrastive head (tool filtering), and
- confidence head (cloud routing). Clean separation.
-
-
-## 6. 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.
-
-
-## 7. Token-Level Loss Weighting
-
-Cross-entropy with structured weighting:
- - Base (JSON structure): 1.0
- - Tool name tokens: 2.0
- - Argument key tokens: 1.5
- - Argument value tokens: 4.0
-
-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, contrastive loss at 0.1x.
-
-
-## 8. Ablations (maps to main.txt 4.4)
-
- A. FFN vs No-FFN [MUST-HAVE - this is the paper]
- B. Gated vs Standard vs No Residual [MUST-HAVE]
- C. Encoder-Decoder vs Decoder-Only [MUST-HAVE]
- D. Gate Value Analysis [STRONG]
- E. Depth vs Width Scaling [STRONG]
- F. Token-Level Weight Ablation [STRONG]
diff --git a/notes/cloud-fallback.txt b/notes/cloud-fallback.txt
deleted file mode 100644
index 701193b..0000000
--- a/notes/cloud-fallback.txt
+++ /dev/null
@@ -1,122 +0,0 @@
-Cloud Routing: Confidence Head for Hybrid Inference
-====================================================
-
-Supports main.txt section 2.4.
-The student knows when it can't reproduce the teacher.
-
-
-## 1. Problem
-
-A distilled model will fail on queries outside its training
-distribution or beyond its capacity. The question is: how does it
-know when to defer to the cloud (the teacher or a comparable model)?
-
-
-## 2. Design Options
-
- Option A - Special token (<cloud> instead of <tool_call>):
- Asks the decoder to learn meta-cognition through the same
- autoregressive mechanism it uses for generation. Two very
- different skills in one pathway.
-
- Option B - Synthetic routing tool (route_to_cloud as a fake tool):
- Same problem plus pollutes the tool namespace.
-
- Option C - Confidence head on encoder output (ours):
- Separate head predicts confidence BEFORE the decoder runs.
- Dedicated head, dedicated signal (perplexity). When confidence
- is low, skip decoding entirely.
-
-
-## 3. Architecture
-
-Small MLP on the encoder output:
-
- encoder_output (B, T, d_model)
- -> mean_pool -> (B, d_model)
- -> Dense(d_model // 4) -> ReLU -> Dense(1) -> sigmoid
- -> confidence in [0, 1]
-
-Same encoder output that feeds the decoder. When confidence < threshold,
-skip the decoder entirely and route to cloud. Encoder compute is not
-wasted - it was needed for the confidence prediction anyway.
-
-MLP (not linear) because the encoder has no FFN - same argument as
-the contrastive head (see tool-selection.txt section 3).
-
-
-## 4. Training Signal
-
-The model already tells you what it can't handle. High decoder
-perplexity = struggling. Low perplexity = confident. Free,
-automatic labeling - no manual "should route" annotations needed.
-
-Sigmoid mapping calibrated to the model's own PPL distribution:
-
- confidence = sigmoid(-k * (log(ppl) - log(mu)))
-
- mu = median perplexity on training set
- k = steepness (default: 3.0)
-
-
-## 5. Post-Hoc Training
-
-Trained AFTER the main model, not jointly:
-
- 1. Train full encoder-decoder as normal
- 2. Freeze encoder + decoder
- 3. Forward pass: compute per-example decoder PPL
- 4. Map PPL -> confidence labels via sigmoid calibration
- 5. Train only confidence head (2 Dense layers) with MSE loss
-
-Why not end-to-end:
- (a) Early-training PPL is noisy (reflects learning progress, not
- true difficulty).
- (b) Jointly-trained head would bias encoder gradients toward easy
- examples.
- (c) Simplicity: retrain head without touching main model.
-
-
-## 6. Deployment
-
-The threshold is a runtime knob:
- threshold=0.4: aggressive routing, save device compute
- threshold=0.8: prefer local, only route when very uncertain
- threshold=0.0: never route (offline mode)
-
-Continuous confidence lets the deployer choose their operating point
-on the accuracy-cost curve.
-
-When routing, the decoder never runs. Encoder is the cheaper half
-(no causal masking, no autoregressive loop). For 30% routing rate,
-~18% net compute reduction on-device.
-
-
-## 7. Relationship to Contrastive Head
-
-Both heads operate on mean-pooled encoder output:
-
- Contrastive head: "which tools are relevant?" (filters WHAT)
- Confidence head: "can I handle this locally?" (decides WHETHER)
-
-Full pipeline:
- 1. Encode query + tools
- 2. Contrastive: retrieve top-k tools
- 3. Re-encode with focused context
- 4. Confidence: can I handle this?
- 5. If yes -> decode locally. If no -> route to cloud.
-
-
-## 8. Ablations (maps to main.txt 4.5)
-
- A. Calibration Quality [MUST-HAVE]
- Reliability diagram, accuracy per PPL bucket.
-
- B. Routing Accuracy Curve [MUST-HAVE]
- Sweep threshold 0.1-0.9, measure % local and local accuracy.
-
- C. Compute Savings [STRONG]
- Wall-clock encoder-only vs full pass at each threshold.
-
- D. vs Decoder-Based Routing [STRONG]
- Compare to Option B (route_to_cloud as synthetic tool).
diff --git a/notes/dataset.txt b/notes/dataset.txt
deleted file mode 100644
index 20a1d5f..0000000
--- a/notes/dataset.txt
+++ /dev/null
@@ -1,133 +0,0 @@
-Dataset: Distillation Pipeline from Gemini
-==========================================
-
-Supports main.txt section 3.
-This IS the distillation - the dataset is how we transfer Gemini's
-tool-calling knowledge into the student model.
-
-
-## 1. Problem
-
-No large-scale public dataset exists for on-device assistant tool
-calling that is:
- (a) Focused on device tools (timers, smart home, messages - not
- enterprise APIs)
- (b) Diverse in query style (direct, indirect, disfluent, garbled)
- (c) Diverse in tool count (1-10 per example)
- (d) Diverse in call patterns (single, multi, none)
- (e) High quality with validated JSON
-
-Existing datasets (xlam-60k, ToolBench, API-Bank) are too small,
-focused on web APIs, or lack query diversity.
-
-
-## 2. Distillation via Gemini
-
-We distill Gemini's tool-calling behavior by generating (query, tools,
-answer) triples. Gemini acts as the teacher: given tools and a scenario,
-it produces the query a user would ask and the correct tool call(s).
-The student model learns to reproduce these outputs.
-
-The quality of the student is upper-bounded by the teacher. If Gemini
-gets a tool call wrong, the student learns that error. This is an
-explicit trade: we get millions of examples cheaply at the cost of
-being limited by Gemini's accuracy on tool calling (which is high but
-not perfect).
-
-
-## 3. Diversity Control
-
-The key contribution is not "we used Gemini to generate data" - it's
-how we control diversity along multiple axes to produce a robust
-training distribution.
-
-### 3.1 Tool Pools
-
-33 hand-crafted tool pools covering on-device domains (~350 tools).
-Tools are hand-written to ensure schema quality - Gemini generates
-QUERIES and ANSWERS, not the tool definitions themselves.
-
-### 3.2 Tool Synthesis
-
-~10% of examples use SYNTHESIZED tool definitions - Gemini invents
-novel tools in random domains. Prevents memorizing the fixed pools,
-forces generalization to unseen schemas at inference.
-
-### 3.3 Tool Count Distribution
-
-Weighted sampling: front-loaded toward 3-5 tools (common real-world
-case), 1-2 and 6-10 covered at lower frequency. Adjustable post-hoc
-via `needle rebalance-tools`.
-
-### 3.4 Call Types
-
-Sampled per-example from a weighted distribution:
-
- single (19%): exactly 1 tool call
- multi (19%): 2-3 calls to different tools
- multi_few_tools(25%): 2-4 calls reusing 1-3 tools, different args
- multi_long (12%): 2-3 calls with verbose argument values
- none ( 6%): no matching tools -> answer = []
- near_miss ( 6%): related but unsatisfiable -> answer = []
- indirect (11%): implicit intent ("it's freezing" -> set_thermostat)
- disfluent (10%): speech disfluencies (um, uh, false starts)
- garbled ( 9%): typos and ASR errors
- no_tools ( 2%): no tools provided -> answer = []
-
-This is the key dataset design decision. The model sees:
- - Clean commands (common case)
- - Noisy/disfluent/garbled queries (realistic speech input)
- - Implicit requests (natural human behavior)
- - Negative examples (teaches when NOT to call)
- - Multi-call patterns (batch operations)
-
-### 3.5 Scenario Seeds
-
-~200 hand-crafted scenarios biasing generation toward specific patterns.
-Hints, not templates - same scenario produces diverse queries across
-Gemini calls.
-
-### 3.6 Validation and Rephrasing
-
-Every example validated: JSON parse, schema, tool name, argument key,
-deduplication. Tool descriptions randomly rephrased per-example to
-prevent memorizing description strings.
-
-
-## 4. External Data
-
-Salesforce/xlam-60k merged for API-style tools and cross-domain
-diversity. Deduplicated, uploaded to HuggingFace (Cactus-Compute/
-tool-calls).
-
-
-## 5. Tokenization
-
- Encoder (max 1024): [query_tokens... <tools> tool1... tool2...]
- Decoder (max 512): [EOS <tool_call> answer_tokens...]
-
-Tools shuffled to prevent positional bias. Token-level loss mask
-labels each decoder token as base/name/value/key for structured
-weighting during training (see architecture.txt section 7).
-
-Sequence packing with segment IDs for block-diagonal attention.
-Contrastive data extracted separately: query-only tokens, individual
-tool tokens, positive/negative labels.
-
-
-## 6. Ablations (maps to main.txt 4.4)
-
- A. Data Scale Curve [MUST-HAVE]
- 10%, 25%, 50%, 100% of dataset. Shows data efficiency.
-
- B. Call Type Distribution [MUST-HAVE]
- Single-only vs clean-only vs full distribution. Proves query
- diversity is necessary for robust inference.
-
- C. Negative Example Importance [MUST-HAVE]
- With vs without negatives. Proves the model needs to learn when
- NOT to produce a call.
-
- D. Synthesized vs Curated-Only Tools [STRONG]
- Eval on seen and novel tools. Proves synthesis prevents
- overfitting to the training tool catalog.
diff --git a/notes/main.txt b/notes/main.txt
deleted file mode 100644
index 32849de..0000000
--- a/notes/main.txt
+++ /dev/null
@@ -1,380 +0,0 @@
-Needle: Attention-Only Encoder-Decoder for On-Device Tool Calling
-=================================================================
-
-Target: NeurIPS 2026
-
-
-## Core Claim
-
-We distill a large cloud model's (Gemini) tool-calling capability into
-a ~25M parameter attention-only encoder-decoder designed specifically
-for this task. The key architectural finding: feedforward layers are
-unnecessary for structured generation at small scale. Removing them
-cuts 2/3 of per-layer parameters without losing quality, because tool
-calling is retrieval-and-assembly, not reasoning, and attention alone
-is sufficient for alignment and copying between input and output.
-
-
-## What This Is
-
-This is task-specific distillation with an architecture co-designed for
-the distillation target. We are NOT claiming to train a model that
-independently reasons about tools. We are claiming:
-
- 1. Tool calling can be distilled into a much smaller model than
- previously demonstrated (25M vs 500M+ for existing approaches)
-
- 2. The receiving architecture matters - an attention-only
- encoder-decoder absorbs this knowledge more efficiently than a
- standard transformer at the same parameter budget, because the
- task structure (alignment, copying, constrained output) maps
- directly onto what attention does
-
- 3. The resulting model is small enough and fast enough for real
- on-device deployment with practical latency
-
-The training data is synthesized by Gemini. The model's capability is
-upper-bounded by Gemini's tool-calling ability. We are compressing that
-capability into a form factor that can run on a phone.
-
-
-## Why This Matters
-
-On-device tool calling (voice assistants, smart home, wearables) needs
-models that are small, fast, and accurate. Current approaches either:
- (a) Use large cloud models (accurate but slow, expensive, requires
- connectivity)
- (b) Distill into standard small transformers (still carry FFN
- parameters that don't help for this task)
- (c) Use heuristic/rule-based systems (brittle, can't generalize)
-
-We show that a purpose-built architecture for distilling structured
-generation achieves better compression than naive distillation into a
-standard transformer, because the architecture matches the task.
-
-
-## Paper Structure
-
-### 1. Introduction
-
-On-device tool calling is a constrained structured generation task.
-The model sees a query and tool definitions, and must output valid JSON
-tool calls. This is fundamentally different from open-ended text
-generation:
- - The output vocabulary is constrained (tool names, parameter keys,
- JSON syntax)
- - The output content is extractive (argument values come from the
- query or are simple transforms of it)
- - The core operation is alignment (match query intent to tool, match
- query fragments to parameter slots)
-
-These properties suggest that FFN - which provides per-position feature
-transformation - may be unnecessary when the model is learning to
-reproduce a teacher's structured outputs. Attention alone provides the
-cross-position alignment and information routing that the task requires.
-
-We validate this by distilling Gemini's tool-calling behavior into a
-pure-attention encoder-decoder that removes FFN entirely and compensates
-with gated residuals and task-specific heads. The architecture is
-co-designed with the distillation target: structured generation from a
-strong teacher into the smallest possible student.
-
-
-### 2. Architecture
-
-#### 2.1 Attention-Only Blocks
-
-Encoder: x = x + sigmoid(gate) * SelfAttn(ZCRMSNorm(x))
-Decoder: x = x + g_s * SelfAttn(ZCRMSNorm(x))
- x = x + g_c * CrossAttn(ZCRMSNorm(x))
-
-No FFN. Per-sublayer learnable scalar gate initialized to 0 (sigmoid
-= 0.5 at init). Model learns which layers matter.
-
-Why gated residuals are necessary for attention-only: without FFN,
-there is no per-position nonlinear rewriting. Standard residual forces
-attention into a purely additive role. Gated residual lets the model
-modulate per-layer contribution - can suppress unhelpful layers (g->0)
-or amplify important ones (g->1).
-
-#### 2.2 Encoder-Decoder
-
-Bidirectional encoder for tool definitions (structured objects benefit
-from seeing the full definition at once). Causal decoder for output
-generation. Encoder output shared across three heads:
-
- Decoder: generates tool calls
- Contrastive head: retrieves relevant tools from large catalogs
- Confidence head: predicts whether to handle locally or route to cloud
-
-#### 2.3 Contrastive Head (Tool Filtering)
-
-Real deployments have 50-200 tools. They don't fit in 1024 encoder
-tokens. Rather than adding a separate retrieval model, we reuse the
-encoder: a lightweight MLP head projects mean-pooled encoder output
-into a contrastive space for tool ranking.
-
- mean_pool -> Dense(d_model/4) -> ReLU -> Dense(128) -> L2-norm
-
-CLIP-style training (0.1x weight, every 1000 steps). At inference,
-encode the query and all candidate tools, rank by cosine similarity,
-pass only top-k to the encoder for generation. No second model, no
-extra memory, tool embeddings can be precomputed and cached.
-
-#### 2.4 Confidence Head (Hybrid Routing)
-
-MLP on mean-pooled encoder output:
- mean_pool -> Dense(d_model/4) -> ReLU -> Dense(1) -> sigmoid -> [0,1]
-
-Trained post-hoc on decoder perplexity as self-supervised labels:
- confidence = sigmoid(-k * (log(ppl) - log(median_ppl)))
-
-When confidence < threshold, skip decoder entirely and route to cloud.
-Saves all decoder compute on queries the model can't handle.
-
-#### 2.5 Constrained Decoding
-
-Character-level trie-based logit masking during generation. JSON state
-machine constrains tool names and argument keys to valid options from
-the input. Guarantees structural validity with zero accuracy cost.
-
-
-### 3. Training
-
-Distillation from Gemini: synthetic (query, tools, answer) triples
-with controlled diversity across 10 call types, 33 tool pools, and
-10% synthesized tools. The dataset IS the distillation - we are
-transferring Gemini's tool-calling behavior into the student.
-See dataset.txt for the full pipeline.
-
-Token-level loss weighting: base 1.0, names 2.0, keys 1.5, values 4.0.
-Matches the error distribution (values > names > keys > structure).
-See architecture.txt section 7.
-
-Muon optimizer for attention projections (prevents representation
-collapse in deep linear stacks), AdamW for everything else.
-See architecture.txt section 6.
-
-
-### 4. Evaluation Plan
-
-This is the critical section. Without strong external evaluation the
-paper is dead on arrival.
-
-#### 4.1 External Benchmarks [MUST-HAVE]
-
- BFCL (Berkeley Function Calling Leaderboard):
- Standard benchmark. Scope mismatch (web APIs vs on-device) but
- necessary. If we do well despite never training on API-style tools,
- that's a generalization result. If we do poorly, we need to be
- honest about it and explain scope.
-
- Action items:
- - Adapt BFCL input format to encoder-decoder
- - Run all BFCL categories
- - Report alongside published results for other models
-
- ToolBench / API-Bank / ToolAlpaca:
- Secondary benchmarks. Less standardized but provide additional
- external validation.
-
-#### 4.2 Head-to-Head vs Small LLMs [MUST-HAVE]
-
- Run small models on tool calling (either BFCL or a shared eval set):
-
- | Model | Params | call_f1 | exact_match | tok/s | Memory |
- |------------------|--------|---------|-------------|-------|--------|
- | Needle (ours) | ~25M | | | | |
- | Qwen 2.5 0.5B | 500M | | | | |
- | Gemma 2 2B | 2B | | | | |
- | LLaMA 3.2 1B | 1B | | | | |
- | LLaMA 3.2 3B | 3B | | | | |
- | Phi-3-mini | 3.8B | | | | |
-
- We are 20-100x smaller. The story is NOT "we beat them" (we probably
- don't on general tool calling). The story is:
- - On in-scope tasks (on-device assistant), we are competitive despite
- being 20-100x smaller
- - We are 10-50x faster on edge hardware
- - We fit in <100MB memory vs 1-8GB for these models
-
- If we're within 10-15% of Qwen 0.5B at 1/20th the size, that's a
- strong result. If we're within 5% of Gemma 2B at 1/80th the size on
- on-device tasks, that's excellent.
-
-#### 4.3 Latency on Real Hardware [MUST-HAVE]
-
- Without this, "on-device" is just a claim. Need actual numbers:
-
- | Device | Model | Latency (ms) | Memory (MB) |
- |------------------|-------------|--------------|-------------|
- | Pixel 8 (CPU) | Needle | | |
- | Pixel 8 (CPU) | Qwen 0.5B | | |
- | Raspberry Pi 5 | Needle | | |
- | Apple M-series | Needle | | |
-
- This is the deployment story. If Needle runs in <50ms on a phone CPU
- while Qwen 0.5B takes >500ms, that's the practical contribution.
-
- Action items:
- - Export model to ONNX or TFLite
- - Benchmark on 2-3 real devices
- - Include memory footprint
-
-#### 4.4 Ablations on Internal Val Set [MUST-HAVE]
-
- These use our synthetic val set but that's OK for ablations -
- we're comparing our own variants against each other, not claiming
- absolute performance.
-
- A. FFN vs No-FFN (THE critical ablation):
- Same parameter budget, same data, same recipe.
- | Condition | Params | call_f1 | exact_match | tok/s |
- Must show no-FFN is not worse. If it's better, even stronger.
-
- B. Gated vs Standard vs No Residual:
- | Condition | Converges? | Final PPL | call_f1 |
- Must show gated is necessary for attention-only.
-
- C. Encoder-Decoder vs Decoder-Only:
- Same budget, same data.
- | Architecture | call_f1 | exact_match |
- Must show enc-dec wins on tool calling.
-
- D. With vs Without Contrastive:
- lambda=0.1 vs lambda=0, generation metrics only.
- | Condition | name_f1 | call_f1 |
- Shows contrastive helps generation, not just retrieval.
-
- E. Constrained vs Unconstrained Decoding:
- | Condition | name_f1 | key_acc | call_f1 |
- Shows free accuracy from structural constraints.
-
-#### 4.5 Analysis [STRONG]
-
- A. Gate value analysis: which layers matter? Do early/late/middle
- layers behave differently? Are any gates near 0 (dormant)?
-
- B. Confidence calibration: reliability diagram (predicted vs actual
- accuracy). Routing accuracy curve at various thresholds.
-
- C. Retrieval quality: Recall@k, MRR on val set. Stratified by tool
- count.
-
- D. Depth vs width: 6+6 d=768 vs 12+12 d=512 vs 24+24 d=256 at
- fixed budget. Informs scaling for attention-only.
-
-
-### 5. Related Work
-
- Knowledge distillation:
- Hinton et al. 2015, DistilBERT, TinyBERT. We distill from a
- generative teacher (Gemini) into a task-specific student, not a
- general-purpose one. The novelty is not distillation itself but
- the receiving architecture being co-designed for the task.
-
- Tool calling models:
- Gorilla, ToolLLaMA, NexusRaven, Toolformer - all decoder-only,
- all >1B params. We use encoder-decoder at 25M. These are trained
- on human-curated or self-generated data; we use teacher distillation
- explicitly.
-
- Attention-only / FFN-free:
- Limited prior work. Some theoretical results on attention
- expressiveness (Yun et al. 2020 - transformers are universal
- approximators, but the proof uses FFN). We show empirically that
- for structured generation distillation, attention alone suffices.
-
- Hybrid inference / routing:
- Speculative decoding, mixture-of-experts routing. Our confidence
- head is simpler - binary local/cloud decision based on encoder
- output. The student knows when it can't reproduce the teacher.
-
- Constrained decoding:
- PICARD (SQL), grammar-constrained generation (Scholak et al.).
- We apply character-level trie masking to tool-call JSON.
-
-
-### 6. Limitations
-
- - This is distillation, not independent learning. The model's
- capability is upper-bounded by Gemini's tool-calling ability.
- If Gemini gets a tool call wrong in training data, the student
- learns that error.
- - Evaluated primarily on on-device assistant tasks. May not
- generalize to complex multi-step API orchestration.
- - The no-FFN finding may be specific to structured generation.
- Open-ended text generation likely still needs FFN. We claim
- task-specific sufficiency, not general sufficiency.
- - Confidence head calibration depends on training data distribution.
- Out-of-distribution queries may have poorly calibrated confidence.
- - Small vocab (8192) limits applicability beyond tool calling.
- - The architecture is purpose-built. It cannot be repurposed for
- general text generation, summarization, or reasoning tasks without
- fundamental changes (re-adding FFN at minimum).
-
-
-## Reviewer Objections and Responses
-
- Q: "Evaluation is only on synthetic data."
- A: We evaluate on BFCL, head-to-head vs small LLMs, and on real
- hardware. The synthetic val set is used only for ablations
- (comparing our own variants). Absolute performance claims are
- backed by external benchmarks.
-
- Q: "This is just distillation from Gemini."
- A: Yes, it is. We say so explicitly. The contribution is not the
- distillation itself but the receiving architecture. Given the SAME
- teacher data, an attention-only encoder-decoder absorbs tool-calling
- knowledge more efficiently than a standard transformer (ablation A).
- The question isn't "can you distill?" - it's "what's the best
- student architecture for structured generation distillation?"
-
- Q: "No-FFN only works because the task is easy."
- A: Tool calling is not easy - BFCL leaderboard shows even large
- models make errors. It is STRUCTURED, which is different from
- easy. The claim is that structure enables attention-only, not
- that the task is trivial.
-
- Q: "The model is too small to be useful."
- A: [Show latency numbers on phone.] This runs in <Xms on a phone
- CPU. No other tool-calling model can do that. Size is the point.
-
- Q: "Too many components, no single deep contribution."
- A: The contribution is the co-design. We make three specific claims:
- (1) FFN is unnecessary for structured generation at small scale
- (ablation A), (2) shared contrastive training improves generation
- (ablation D), (3) encoder-based confidence routing saves compute
- without losing accuracy (Sec 4.5B). Everything else is recipe.
-
- Q: "The no-FFN argument is hand-wavy."
- A: We make an empirical claim, not a theoretical one. We do not
- prove attention alone is sufficient in general. We show it is
- sufficient for this task at this scale. The ablation is the proof.
-
-
-## Action Items
-
-Priority order:
-
- 1. Run the FFN ablation. This is the paper.
- If no-FFN loses badly, there is no paper.
-
- 2. Run BFCL. Need external benchmark numbers.
- Adapt input format, run all categories, report honestly.
-
- 3. Run Qwen 0.5B / Gemma 2B / LLaMA 3.2 1B on tool calling.
- Need the comparison table.
-
- 4. Get latency on real hardware.
- Export to ONNX/TFLite. Benchmark on phone + RPi.
-
- 5. Run remaining ablations (gated residual, enc-dec vs dec-only,
- contrastive, constrained).
-
- 6. Gate value analysis and confidence calibration plots.
-
- 7. Write the paper.
-
-Items 1-4 are blocking. Without them, no submission.
-Items 5-6 strengthen but don't make or break.
diff --git a/notes/sparsification.txt b/notes/sparsification.txt
deleted file mode 100644
index dbf6ef4..0000000
--- a/notes/sparsification.txt
+++ /dev/null
@@ -1,521 +0,0 @@
-Group-Aligned Sparsification for Quantized Edge Deployment
-===========================================================
-
-## 1. Problem
-
-Needle targets tiny edge devices (phones, microcontrollers, wearables)
-where memory, compute, and battery are constrained. Two standard
-compression techniques exist independently:
-
- (a) Quantization: reduce weight precision (FP16 → INT4), 4x memory savings
- (b) Pruning: zero out weights, skip multiplications, save compute + energy
-
-The problem: these are typically applied independently, with mismatched
-granularity. Standard unstructured pruning zeros individual weights,
-but quantization operates on groups (32 consecutive weights share one
-scale factor). A group with 31 zeros and 1 nonzero still needs its
-full scale factor, full memory, and full compute — the sparsity is
-invisible to the quantization kernel.
-
-
-## 2. Key Insight: Align Pruning Groups with Quantization Groups
-
-If pruning and quantization use the same group structure, an entire
-pruned group becomes a contiguous block of zeros that hardware can
-skip completely:
-
- Weight matrix W: (in_features, out_features)
-
- Group-aligned view (group_size=32):
- ┌────────────────────────────────────────────┐
- │ group 0: [w_0, w_1, ..., w_31] scale_0 │ ← LIVE (has nonzeros)
- │ group 1: [0, 0, ..., 0] scale_1 │ ← DEAD (all zeros)
- │ group 2: [w_64, w_65, ..., w_95] scale_2 │ ← LIVE
- │ group 3: [0, 0, ..., 0] scale_3 │ ← DEAD
- │ ... │
- └────────────────────────────────────────────┘
-
- Unstructured sparsity (misaligned):
- ┌────────────────────────────────────────────┐
- │ group 0: [w_0, 0, w_2, 0, ..., 0, w_31] │ ← half zeros, but
- │ scale_0 still needed │ can't skip group
- │ all 32 multiplications still run │
- └────────────────────────────────────────────┘
-
- Group-aligned sparsity:
- ┌────────────────────────────────────────────┐
- │ group 1: [0, 0, 0, 0, ..., 0, 0] │ ← entire group zero
- │ scale_1 can be skipped │ skip 32 MACs
- │ skip memory load for 32 weights │ skip scale load
- │ skip 32 multiplications │ zero energy
- └────────────────────────────────────────────┘
-
-When a full group is zero:
- - Skip loading 32 INT4 weights from memory (16 bytes saved per group)
- - Skip loading the group scale factor (2 bytes saved)
- - Skip 32 multiply-accumulate operations
- - Skip the dequantization step for that group
- - On battery-powered devices: fewer memory accesses = less energy
-
-The key: our QAT and pruning both use group_size=32. This is not
-coincidence — they are co-designed to produce hardware-friendly
-compressed models.
-
-
-## 3. Architecture
-
-Three components: group-wise magnitude scoring, cubic gradual schedule,
-and mask application.
-
-### 3a. Group-Wise Magnitude Scoring
-
-For each weight matrix, divide the input dimension into groups of 32:
-
- W ∈ R^{in × out} → W_grouped ∈ R^{num_groups × 32 × out}
-
- Score each group by the L1 norm of its elements:
-
- score_g = Σ_{i=0}^{31} Σ_{j=0}^{out-1} |W_grouped[g, i, j]|
-
- This gives one score per group. Groups with low total magnitude
- contribute least to the output and are pruned first.
-
-Global threshold: all group scores across ALL weight matrices are
-collected and sorted. The threshold is set at the s-th percentile,
-where s is the target sparsity. This means pruning is globally
-balanced — a layer with many unimportant groups loses more than a
-layer with all important groups.
-
- all_scores = concat([scores from every weight matrix])
- threshold = percentile(all_scores, sparsity * 100)
- mask[g] = 1 if score[g] > threshold else 0
-
-Binary mask: the mask has the same shape as the weight matrix.
-All 32 weights in a pruned group are zeroed together.
-
- mask_grouped[g, :, :] = broadcast(score[g] > threshold)
- mask = mask_grouped.reshape(in_features, out_features)
-
-### 3b. Handling nn.scan Parameters
-
-nn.scan stacks layer parameters as 3D tensors: (num_layers, in, out).
-Each layer is pruned independently — different layers can have different
-sparsity patterns, but the global threshold is shared.
-
- For W ∈ R^{num_layers × in × out}:
- for each layer l:
- W[l] → group → score → collect into global pool
- global threshold from all scores across all layers and all matrices
- for each layer l:
- W[l] → group → mask using global threshold
-
-This ensures pruning pressure is distributed based on actual weight
-magnitude, not layer position.
-
-
-### 3c. Cubic Gradual Schedule
-
-One-shot pruning (remove 50% of groups instantly) causes irrecoverable
-accuracy loss. Instead, gradually increase sparsity following a cubic
-schedule (Zhu & Gupta 2017):
-
- s(t) = s_final × (1 - (1 - (t - t_start) / (t_end - t_start))³)
-
- ┌─────────────────────────────────────────────────┐
- │ sparsity │
- │ ▲ s_final ─── ─── ─── ─── ─── ──│
- │ │ ╱ │
- │ │ ╱ │
- │ │ ╱ ← fast ramp │
- │ │ ╱ │
- │ │ ╱ │
- │ │ _╱ ← slow start │
- │ │ __╱ │
- │ │ ___╱ │
- │ │ ────╱ │
- │ 0%─────┬──────────────────┬─────────────→ step │
- │ t_start (33%) t_end (67%) │
- └─────────────────────────────────────────────────┘
-
- Default schedule within pruning epoch:
- t_start = 33% of epoch steps (first third: no pruning)
- t_end = 67% of epoch steps (middle third: gradual pruning)
- remaining third: mask locked, fine-tune surviving weights
-
- Mask recomputation: every prune_interval=100 steps during the
- ramp, recompute the mask at the current sparsity level. Between
- recomputations, the mask is frozen — weights can recover.
-
-Why cubic (not linear):
- - Slow start: remove only the most obviously unimportant groups first.
- The model barely notices.
- - Fast middle: bulk of pruning happens here, while the model has
- already adapted to losing some groups.
- - Slow end: final fine-grained pruning. The remaining groups are
- closer in importance — take care removing the last few.
-
-After pruning epoch completes:
- - Mask is permanently locked
- - All subsequent training respects the mask (w = w * mask after each step)
- - The model fine-tunes only the surviving weights
-
-
-### 3d. Mask Application in Training Loop
-
-The mask is applied after each gradient update, not during:
-
- # In _train_step:
- state = state.apply_gradients(grads=grads) # update ALL weights
- new_params = cond(
- do_prune,
- lambda: tree_map(lambda w, m: w * m, state.params, prune_mask),
- lambda: state.params,
- )
- state = state.replace(params=new_params)
-
-This is "mask-after-update" (not "mask-before-gradient"). Both are
-used in practice, but mask-after-update has an advantage: the optimizer
-state (momentum, variance estimates) remains valid for pruned weights.
-If we ever want to "un-prune" during the gradual schedule (a group
-recovers importance), the optimizer can immediately use its momentum —
-no cold start.
-
-In practice, during the cubic ramp, groups can be un-pruned: a group
-zeroed at 20% sparsity might survive at 25% sparsity if the global
-threshold shifts. This is a natural consequence of global thresholding
-with recomputation.
-
-
-## 4. Co-Design with INT4 Quantization
-
-### 4a. Shared Group Size
-
-Both QAT and pruning use group_size=32. This is the critical co-design:
-
- Quantization groups:
- W_grouped = W.reshape(num_groups, 32, out_features)
- scale[g] = max(|W_grouped[g]|) / 7 (one scale per group)
- W_q[g] = clip(round(W_grouped[g] / scale[g]), -8, 7)
-
- Pruning groups:
- W_grouped = W.reshape(num_groups, 32, out_features)
- score[g] = sum(|W_grouped[g]|)
- mask[g] = score[g] > threshold
-
- Same reshape. Same groups. The pruned groups are exactly the groups
- the quantization kernel operates on.
-
-### 4b. Hardware Execution Model
-
-On edge INT4 kernels (ARM NEON, Apple AMX, RISC-V V):
-
- For each output element y[j]:
- for each group g in [0, num_groups):
- if mask[g] == 0: ← group is pruned
- continue ← skip entirely: no load, no compute
- load scale[g] ← 2 bytes
- load W_q[g, :, j] ← 16 bytes (32 × 4-bit)
- dequant = W_q * scale ← 32 multiplies
- y[j] += dot(dequant, x[g*32:(g+1)*32]) ← 32 MACs
- end
-
- With 50% group sparsity:
- - 50% fewer memory loads (weights + scales)
- - 50% fewer multiply-accumulate operations
- - ~50% less energy (memory access dominates energy on edge)
- - Model size: 50% fewer groups × (16 bytes weights + 2 bytes scale)
- = 50% size reduction ON TOP of 4x from INT4
-
- Combined compression:
- FP16 baseline: 100% (2 bytes per weight)
- INT4 only: 25% (0.5 bytes per weight + scale overhead)
- INT4 + 50% sparse: ~13% (half the INT4 groups)
-
- For a 50M parameter model:
- FP16: 100 MB
- INT4: 25 MB (+ ~2 MB scales)
- INT4 + 50% sparse: ~14 MB
-
-
-### 4c. Why Group Size 32
-
- - ARM NEON: 128-bit SIMD → 32 INT4 values per register
- - Apple AMX: operates on blocks that are multiples of 32
- - CUDA: warp size 32, INT4 tensor cores operate on 32-element groups
- - RISC-V V: typical VLEN=128+ → 32+ INT4 elements per vector register
-
-Group size 32 means each pruned group corresponds to exactly one
-hardware vector operation that can be skipped. Smaller groups (16)
-waste half the register; larger groups (64) are too coarse for
-fine-grained pruning. 32 is the hardware-natural sweet spot.
-
-
-## 5. Comparison with Other Pruning Approaches
-
-### vs. Unstructured Pruning (SparseGPT, Wanda)
-
- Unstructured: zeros individual weights anywhere in the matrix.
- 50% unstructured sparsity → every group still has ~half its weights.
- No group can be skipped. Requires sparse matmul kernels (CSR/CSC),
- which have poor hardware utilization on edge devices.
-
- Group-aligned: zeros entire groups. 50% sparsity → 50% of groups
- are completely empty. Dense matmul kernels skip entire groups.
- No sparse format overhead. No index storage.
-
- Accuracy comparison:
- Unstructured can achieve slightly better accuracy at the same
- sparsity level (finer granularity → more choices). But the
- speedup is often zero on real hardware without sparse kernel support.
-
- Our trade: slightly coarser pruning for guaranteed hardware speedup.
-
-### vs. N:M Structured Sparsity (2:4 on NVIDIA Ampere+)
-
- N:M sparsity: exactly N zeros in every M consecutive elements.
- 2:4 sparsity on Ampere/Hopper: hardware-native 2x speedup.
-
- Limitations:
- - Only available on NVIDIA Ampere+ GPUs (not edge devices)
- - Fixed 50% sparsity (can't do 30% or 70%)
- - Fixed pattern (2:4) — no flexibility
- - Not compatible with INT4 group quantization grouping
-
- Our approach: works on any hardware with vector instructions.
- Variable sparsity (0-90%). Compatible with INT4 group quantization.
- No special hardware required.
-
-### vs. Channel/Filter Pruning
-
- Channel pruning: removes entire rows/columns of weight matrices.
- Maximally structured (every output using that channel is affected).
-
- Limitation: too coarse. Removing an entire channel of d_model=512
- is a huge capacity hit. For small models, even removing one channel
- is noticeable.
-
- Our group pruning: operates at the granularity of 32 input features
- per output. Much finer than channel pruning. A matrix can lose
- some groups in one region while keeping others — the pruning
- pattern adapts to the weight distribution.
-
-
-## 6. Experiment Design
-
-### Exp 1: Group-Aligned vs Unstructured Sparsity [MUST-HAVE]
-
-Setup:
- - Same model, same training, three pruning modes:
- (a) Group-aligned (group_size=32, our approach)
- (b) Unstructured (individual weight magnitude pruning)
- (c) No pruning (baseline)
- - Sparsity levels: 0%, 25%, 50%, 70%, 90%
- - All with QAT (INT4, group_size=32)
-
-Metrics:
- | Sparsity | Mode | val_ppl | call_f1 | quant_ppl | actual_speedup |
- |----------|---------------|---------|---------|-----------|----------------|
- | 0% | baseline | | | | 1.0x |
- | 25% | unstructured | | | | |
- | 25% | group-aligned | | | | |
- | 50% | unstructured | | | | |
- | 50% | group-aligned | | | | |
- | 70% | unstructured | | | | |
- | 70% | group-aligned | | | | |
- | 90% | unstructured | | | | |
- | 90% | group-aligned | | | | |
-
- actual_speedup: measured on target edge device (ARM CPU with NEON)
-
-Hypothesis:
- - Unstructured has slightly better accuracy at same sparsity (~1-2%)
- - Group-aligned has MUCH better actual speedup (near-linear with sparsity)
- - Unstructured has ~1x speedup (no hardware skip support on edge)
- - Group-aligned at 50% matches unstructured at 50% accuracy but with
- real 1.8-2x speedup
- - The quant_ppl gap between aligned/unstructured is small because QAT
- adapts to both patterns
-
-What this shows:
- - Group alignment is essential for actual deployment speedup
- - The small accuracy cost is worth the massive efficiency gain
- - Unstructured sparsity is a "paper metric" — looks good, no real speedup
-
-
-### Exp 2: Gradual vs One-Shot Pruning [MUST-HAVE]
-
-Setup:
- - Same target sparsity (50%), three schedules:
- (a) Gradual cubic (our approach: 0% → 50% over 33%-67% of epoch)
- (b) One-shot at epoch start (prune to 50% immediately, then train)
- (c) One-shot at epoch end (train, then prune to 50%)
- - Same total training budget
-
-Metrics:
- | Schedule | val_ppl | call_f1 | name_f1 | value_acc |
-
- Also: val_ppl convergence curve (how quickly accuracy recovers)
-
-Hypothesis:
- - Gradual cubic is best (model adapts smoothly)
- - One-shot at start: worst (massive capacity loss before adaptation)
- - One-shot at end: middle (full training, then sudden pruning)
- - Gradual reaches same final quality 30-50% faster than one-shot-start
-
-What this shows:
- - Gradual pruning is necessary for small models
- - The cubic schedule is justified (smooth ramp > abrupt cut)
-
-
-### Exp 3: Group Size Sweep [MUST-HAVE]
-
-Setup:
- - Group sizes: 8, 16, 32, 64, 128
- - QAT group size always matches pruning group size
- - 50% target sparsity
-
-Metrics:
- | group_size | val_ppl | call_f1 | quant_ppl | model_size(MB) | tok/s(edge) |
- |------------|---------|---------|-----------|----------------|-------------|
- | 8 | | | | | |
- | 16 | | | | | |
- | 32 | | | | | |
- | 64 | | | | | |
- | 128 | | | | | |
-
-Hypothesis:
- - group_size=8: best accuracy (finest granularity), worst speedup
- (groups don't fill hardware vectors)
- - group_size=32: sweet spot (matches hardware vector width)
- - group_size=128: worst accuracy (too coarse), but fastest per-group
- skip (fewer groups to iterate)
- - Quantization overhead (scale storage) is lowest at group_size=128
- but accuracy suffers
-
-What this shows:
- - group_size=32 is the right choice (hardware-natural + good accuracy)
- - Justifies the co-design: QAT and pruning both at 32
-
-
-### Exp 4: Combined Compression Frontier [STRONG]
-
-Setup:
- - Sweep the sparsity-quantization space:
- FP16 + {0%, 25%, 50%, 70%} sparsity
- INT8 + {0%, 25%, 50%, 70%} sparsity
- INT4 + {0%, 25%, 50%, 70%} sparsity
- - All with QAT (matched to quantization level)
- - Report model size, inference speed, and accuracy
-
-Metrics:
- Plot: model_size(MB) vs call_f1 (Pareto frontier)
- Plot: tok/s(edge) vs call_f1 (Pareto frontier)
-
- Annotate each point with (quant_level, sparsity%)
-
-Hypothesis:
- - INT4 + 50% sparse dominates the Pareto frontier for edge
- - FP16 + 0% is best accuracy but impractical (too large/slow)
- - INT4 + 0% is a strong baseline but leaving performance on table
- - INT4 + 70% pushes into extreme compression with acceptable loss
-
-What this shows:
- - Quantization and sparsification are complementary (multiplicative compression)
- - The co-designed approach (shared group_size) maximizes both
- - Practical deployment recipe: INT4 + 50% sparse ≈ 8x compression
- with <5% accuracy loss
-
-
-### Exp 5: Energy Measurement on Edge Device [STRONG]
-
-Setup:
- - Deploy on target edge device (e.g. Raspberry Pi 5, Pixel phone)
- - Measure per-inference energy (joules) using hardware power monitor
- - Compare: FP16 baseline, INT4-only, INT4+50% group-sparse
-
-Metrics:
- | Condition | Energy(mJ) | Latency(ms) | call_f1 | Model size |
- |-------------------|------------|-------------|---------|------------|
- | FP16 baseline | | | | |
- | INT4 | | | | |
- | INT4 + 50% sparse | | | | |
-
- Also: energy breakdown by component (memory load, compute, other)
-
-Hypothesis:
- - Memory loads dominate energy on edge (>60% of total)
- - INT4 + 50% sparse reduces memory energy by ~87% (4x quant × 2x sparse)
- - Compute energy scales linearly with sparsity (skip zero groups)
- - Total energy reduction: 5-8x vs FP16 baseline
-
-What this shows:
- - Group-aligned sparsity directly maps to energy savings
- - This is the deployment story: same model, 5-8x less energy per inference
- - Battery life argument for edge devices
-
-
-### Exp 6: Pruning Schedule Ablation [STRONG]
-
-Setup:
- - Vary pruning schedule parameters:
- start_frac: {0.1, 0.2, 0.33, 0.5}
- end_frac: {0.5, 0.67, 0.8, 0.9}
- interval: {10, 50, 100, 500}
- - 50% target sparsity
-
-Metrics:
- - Final call_f1 for each combination
- - Training efficiency: steps to reach 90% of final accuracy
-
-Hypothesis:
- - start_frac=0.33, end_frac=0.67 (middle third) is near-optimal
- - Too early start (0.1): model hasn't learned enough to identify
- unimportant groups
- - Too late end (0.9): not enough fine-tuning time after pruning
- - Interval=100 is sufficient (mask doesn't need per-step updates)
-
-What this shows:
- - The default schedule is well-chosen
- - Pruning during the "middle" of training is optimal (model has
- learned structure but still has time to adapt)
-
-
-### Exp 7: Sparsity Pattern Visualization [NICE-TO-HAVE]
-
-Setup:
- - Visualize the pruning mask at 50% sparsity
- - Heat maps: which groups survive in each layer
- - Compare encoder vs decoder patterns
-
-Presentation:
- - Matrix visualization: rows = input groups, columns = output features
- - Color: white = pruned, black = kept
- - One plot per layer type (encoder self-attn, decoder cross-attn, FFN)
-
-Hypothesis:
- - FFN layers are more prunable than attention projections
- - Encoder FFN: earlier layers keep more groups (basic features)
- - Decoder cross-attention: keeps groups aligned with tool-relevant
- encoder positions
- - Symmetric pattern in attention Q/K but asymmetric in V/O
-
-What this shows:
- - The model learns which groups matter
- - Visual evidence that global thresholding distributes sparsity
- intelligently across layers
-
-
-### Priority
-
-Must-have (core claims):
- 1. Group-aligned vs unstructured (Exp 1) — proves hardware speedup
- 2. Gradual vs one-shot (Exp 2) — proves schedule necessity
- 3. Group size sweep (Exp 3) — proves group_size=32 choice
-
-Strong additions:
- 4. Combined compression frontier (Exp 4) — deployment Pareto
- 5. Energy measurement (Exp 5) — real-world edge impact
- 6. Schedule ablation (Exp 6) — hyperparameter justification
-
-Nice-to-have:
- 7. Sparsity pattern visualization (Exp 7) — interpretability
diff --git a/notes/tool-selection.txt b/notes/tool-selection.txt
deleted file mode 100644
index 409fe65..0000000
--- a/notes/tool-selection.txt
+++ /dev/null
@@ -1,116 +0,0 @@
-Tool Selection: Contrastive Filtering and Constrained Decoding
-==============================================================
-
-Supports main.txt sections 2.3, 2.5.
-Two mechanisms that narrow the output space: filtering tools before
-generation, constraining tokens during generation.
-
-
-## 1. Problem
-
- (a) Context pressure: 1024 encoder tokens, real deployments have
- 50-200 tools - they don't fit.
- (b) Structural validity: the model can hallucinate invalid function
- names or argument keys despite high JSON parse rates.
-
-
-## 2. Contrastive Head (Tool Filtering)
-
-Real deployments have too many tools for the context window. Rather
-than adding a separate retrieval model, we reuse the encoder: a
-lightweight MLP projects mean-pooled encoder output into a contrastive
-space for tool ranking.
-
- encoder -> mean_pool -> Dense(d_model/4) -> ReLU -> Dense(128) -> L2-norm
-
-CLIP-style training (0.1x weight, every 1000 steps, in-batch
-negatives, learnable temperature). At inference: encode query and
-candidate tools, rank by cosine similarity, pass only top-k to the
-encoder for generation.
-
- - No separate retrieval model - same encoder, same parameters
- - Tool embeddings can be precomputed and cached
- - Contrastive head adds <0.1% parameters
- - For small catalogs (<=5 tools): skip retrieval, pass all directly
-
-
-## 3. Why MLP Instead of Linear Projection
-
-Our encoder has NO feedforward layers. The only nonlinearities are
-softmax (attention) and sigmoid (gates). A linear contrastive
-projection can only rotate and scale the mean-pooled representation.
-
-In a standard transformer with FFN, the encoder output has been through
-N layers of nonlinear per-position processing - a linear projection
-often suffices. In our pure-attention encoder, the output has been mixed
-extensively but never nonlinearly transformed per-position.
-
-The MLP provides the per-position nonlinearity that the encoder lacks,
-specifically for the retrieval task. Same argument applies to the
-confidence head (cloud-fallback.txt section 3).
-
-
-## 4. Constrained Decoding
-
-After filtering selects top-k tools, the decoder generates tool calls.
-We enforce structural validity via character-level trie-based logit
-masking:
-
-A JSON state machine tracks position in the output:
- - IN_NAME: constrain to valid tool names
- - IN_KEY: constrain to valid parameter names per selected tool
- - IN_VALUE: unconstrained
-
-Character-level (not token-level) because BPE tokens don't align with
-name boundaries. "get_weather" might tokenize as ["get", "_we", "ather"]
-or ["get_", "weather"]. Character-level trie works regardless of
-tokenization.
-
-Guarantees syntactically valid output with zero accuracy cost.
-
-
-## 5. The Funnel
-
-Filtering and constrained decoding are complementary stages:
-
- 200 tools -> contrastive filter top-5 -> encode 5 tools
- -> constrain to 5 names -> constrain to valid params per name
- -> free-form values
-
-Each stage narrows the output space. The model's actual "choice" is
-just: which of 5 tools to call, and what values to fill in.
-
-
-## 6. vs. Alternatives
-
- vs. Separate retrieval model:
- One model, shared representations, no distribution shift.
-
- vs. Stuffing all tools in context:
- 50 tools x ~50 tokens = 2500 tokens, exceeds 1024 context.
- Even if they fit, attention dilution over irrelevant tools.
-
-
-## 7. Ablations (maps to main.txt 4.4-4.5)
-
- A. Retrieval Quality [MUST-HAVE]
- Recall@k, MRR. Stratify by tool count.
-
- B. With vs Without Contrastive [MUST-HAVE]
- lambda=0.1 vs lambda=0, generation metrics only (no retrieval
- at inference). Tests whether contrastive training helps the
- encoder build more discriminative tool representations.
-
- C. Retrieve-then-Generate vs Full Context [MUST-HAVE]
- Synthetic large catalogs (20, 50, 100 tools).
- All-in-context vs retrieved top-5 vs oracle top-5.
-
- D. Constrained vs Unconstrained Decoding [MUST-HAVE]
- Unconstrained vs name-only vs full constraint.
-
- E. Linear vs MLP Head [STRONG]
- Tests whether head nonlinearity matters more for attention-only
- encoder.
-
- F. Contrastive Weight Sweep [STRONG]
- lambda in {0, 0.01, 0.05, 0.1, 0.2, 0.5}.
diff --git a/pyproject.toml b/pyproject.toml
index 99eef8b..0221728 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -8,10 +8,10 @@ dependencies = [
"flax",
"optax",
"datasets",
+ "huggingface_hub",
"transformers",
"wandb",
"sentencepiece",
- "soundfile",
"scipy",
"gcsfs",
"tqdm",
diff --git a/requirements.txt b/requirements.txt
index a84051c..eaf2d02 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -3,12 +3,10 @@ jaxlib
flax
optax
datasets
+huggingface_hub
gcsfs
transformers
wandb
pyyaml
sentencepiece
-google-cloud-texttospeech
-google-genai
-audiomentations
-gcsfs
\ No newline at end of file
+google-genai
\ No newline at end of file
diff --git a/src/cli.py b/src/cli.py
index 026ec30..4c325e2 100644
--- a/src/cli.py
+++ b/src/cli.py
@@ -98,7 +98,7 @@ os.environ.setdefault("TF_CPP_MIN_LOG_LEVEL", "2")
os.environ.setdefault("GRPC_VERBOSITY", "ERROR")
_install_xla_log_filter()
-from .data import DEFAULT_MAX_ENC_LEN, DEFAULT_MAX_DEC_LEN, DEFAULT_MAX_GEN_LEN
+from .dataset.tokenizer import DEFAULT_MAX_ENC_LEN, DEFAULT_MAX_DEC_LEN, DEFAULT_MAX_GEN_LEN
def main():
@@ -138,16 +138,8 @@ 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("--sparsity-ratio", type=float, default=0.0)
- p.add_argument("--group-size", type=int, default=32)
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("--prune-interval", type=int, default=100,
- help="Steps between mask updates during gradual pruning (default: 100)")
- p.add_argument("--prune-start-frac", type=float, default=0.33,
- help="Fraction of epoch to train before starting gradual pruning (default: 0.33)")
- p.add_argument("--prune-end-frac", type=float, default=0.67,
- help="Fraction of epoch at which pruning finishes and mask locks (default: 0.67)")
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)")
@@ -213,7 +205,6 @@ def main():
p.add_argument("--checkpoint", type=str, required=True)
p.add_argument("--query", type=str, default=None, help="Query text for tool-call generation")
p.add_argument("--tools", type=str, default=None, help="Tools JSON for tool-call generation")
- p.add_argument("--audio", type=str, nargs="*", help="Audio file paths for voice-to-tool-call")
p.add_argument("--max-len", type=int, default=512)
p.add_argument("--seed", type=int, default=0)
p.add_argument("--no-constrained", action="store_true",
@@ -248,7 +239,7 @@ def main():
p.add_argument("--max-samples", type=int, default=500)
p = sub.add_parser("ui", add_help=False)
- p.add_argument("--checkpoint", type=str, required=True)
+ 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")
@@ -312,39 +303,36 @@ def main():
sys.exit(0)
if args.command == "tokenize":
- from .tokenize_data import tokenize
+ from .dataset.tokenize import tokenize
tokenize(args)
elif args.command == "pretrain":
import jax
if os.path.exists("/dev/accel0"):
jax.distributed.initialize()
- from .pretrain import pretrain
+ from .training.pretrain import pretrain
pretrain(args)
elif args.command == "train":
import jax
if os.path.exists("/dev/accel0"):
jax.distributed.initialize()
- from .train import train
+ from .training.train import train
train(args)
elif args.command == "run":
- from .run import main as run_main
+ from .model.run import main as run_main
run_main(args)
elif args.command == "eval":
- from .eval import main as eval_main_fn
+ from .training.eval import main as eval_main_fn
eval_main_fn(args)
elif args.command == "generate-data":
- from .generate_data import main as gendata_main, MODEL as _MODEL, UPLOAD_EVERY as _UE
+ from .dataset.generate import main as gendata_main, MODEL as _MODEL, UPLOAD_EVERY as _UE
if args.model is None:
args.model = _MODEL
if args.upload_every is None:
args.upload_every = _UE
gendata_main(args)
- elif args.command == "evaluate":
- from .evaluate import main as eval_main
- eval_main(args)
elif args.command == "ui":
from .ui.server import main as ui_main
ui_main(args)
elif args.command == "tpu":
- from .tpu import tpu_dispatch
+ from .utils.tpu import tpu_dispatch
tpu_dispatch(args)
diff --git a/src/dataset/__init__.py b/src/dataset/__init__.py
new file mode 100644
index 0000000..022e8de
--- /dev/null
+++ b/src/dataset/__init__.py
@@ -0,0 +1,2 @@
+from .tokenizer import * # noqa: F401,F403
+from .dataset import * # noqa: F401,F403
diff --git a/src/data.py b/src/dataset/dataset.py
similarity index 91%
rename from src/data.py
rename to src/dataset/dataset.py
index 1e0b23d..fb185b8 100644
--- a/src/data.py
+++ b/src/dataset/dataset.py
@@ -12,7 +12,7 @@ logging.getLogger("transformers").setLevel(logging.ERROR)
logging.getLogger("huggingface_hub").setLevel(logging.ERROR)
import numpy as np
-from datasets import Audio, Dataset, load_from_disk
+from datasets import Dataset, load_from_disk
from tqdm import tqdm
import sentencepiece as spm
@@ -253,12 +253,7 @@ def _load_split_dataset(split="train"):
def _set_audio_backend(ds):
- """Disable automatic audio decoding to avoid torchcodec dependency.
-
- Audio is decoded manually via soundfile in load_tool_call_audio().
- """
- if "audio" in ds.column_names:
- ds = ds.cast_column("audio", Audio(sampling_rate=16000, decode=False))
+ """No-op kept for compatibility."""
return ds
@@ -748,101 +743,6 @@ def pack_sequences(cache_path, enc_vl, dec_in_vl, dec_tgt_vl, loss_vl):
-def load_tool_call_audio(split="train", max_samples=None):
- """Return dataset-local indices for the given split.
-
- Audio is NOT loaded into memory.
- """
- ds = _load_split_dataset(split)
- n = len(ds)
- indices = list(range(n))
- if max_samples:
- indices = indices[:max_samples]
- return indices
-
-
-def load_example_with_audio(idx, split="train"):
- """Load a dataset example by index within a split.
-
- Returns dict with {query, answers, tools, audio_array, sampling_rate}.
- Audio fields are None for text-only datasets.
- """
- ds = _load_split_dataset(split)
- if idx < 0 or idx >= len(ds):
- raise IndexError(f"Index {idx} out of range (split has {len(ds)} rows)")
- ex = ds[idx]
-
- audio, sr = None, None
- audio_val = ex.get("audio")
- if audio_val is not None:
- import io
- import soundfile as sf
-
- raw_bytes = None
- if isinstance(audio_val, dict):
- raw_bytes = audio_val.get("bytes")
- elif isinstance(audio_val, bytes):
- raw_bytes = audio_val
- if raw_bytes is not None:
- audio, sr = sf.read(io.BytesIO(raw_bytes), dtype="float32")
- if audio.ndim > 1:
- audio = audio.mean(axis=1)
- audio = audio.astype(np.float32)
-
- return {
- "query": ex["query"],
- "answers": ex["answers"],
- "tools": ex["tools"],
- "audio_array": audio,
- "sampling_rate": sr,
- }
-
-
-def compute_mel_spectrogram(audio, sr=16000, n_mels=80, n_fft=400, hop_length=160):
- """Compute log-mel spectrogram using numpy/scipy. Returns (T_mel, n_mels) float32.
-
- 25ms window (n_fft=400 at 16kHz), 10ms hop (hop_length=160) -> ~100 frames/sec.
- """
- from scipy.signal import windows as scipy_windows
- from scipy.fft import rfft
-
- audio = np.append(audio[0], audio[1:] - 0.97 * audio[:-1])
-
- window = scipy_windows.hann(n_fft, sym=False).astype(np.float32)
- num_frames = 1 + (len(audio) - n_fft) // hop_length
- if num_frames <= 0:
- return np.zeros((1, n_mels), dtype=np.float32)
-
- frames = np.lib.stride_tricks.as_strided(
- audio,
- shape=(num_frames, n_fft),
- strides=(audio.strides[0] * hop_length, audio.strides[0]),
- ).copy()
- frames = frames * window
- spectrum = np.abs(rfft(frames, n=n_fft, axis=-1)) ** 2
-
- fmin, fmax = 0.0, sr / 2.0
- mel_low = 2595.0 * np.log10(1.0 + fmin / 700.0)
- mel_high = 2595.0 * np.log10(1.0 + fmax / 700.0)
- mel_points = np.linspace(mel_low, mel_high, n_mels + 2)
- hz_points = 700.0 * (10.0 ** (mel_points / 2595.0) - 1.0)
- bin_points = np.floor((n_fft + 1) * hz_points / sr).astype(np.int32)
-
- filterbank = np.zeros((n_mels, n_fft // 2 + 1), dtype=np.float32)
- for m in range(n_mels):
- f_left, f_center, f_right = bin_points[m], bin_points[m + 1], bin_points[m + 2]
- for k in range(f_left, f_center):
- if f_center > f_left:
- filterbank[m, k] = (k - f_left) / (f_center - f_left)
- for k in range(f_center, f_right):
- if f_right > f_center:
- filterbank[m, k] = (f_right - k) / (f_right - f_center)
-
- mel_spec = spectrum @ filterbank.T
- log_mel = np.log(np.maximum(mel_spec, 1e-10))
- return log_mel.astype(np.float32)
-
-
class VarLenArray:
"""Variable-length storage with on-demand padding to fixed max_len.
diff --git a/src/generate_data.py b/src/dataset/generate.py
similarity index 99%
rename from src/generate_data.py
rename to src/dataset/generate.py
index 5783084..cc358b0 100644
--- a/src/generate_data.py
+++ b/src/dataset/generate.py
@@ -1741,7 +1741,7 @@ def _load_existing():
print(f"Loaded existing dataset: {len(ds)} rows")
else:
print(f"Downloading existing dataset from {HF_DATASET_REPO}...")
- from .data import download_hf_split
+ from .dataset import download_hf_split
ds = download_hf_split("train", HF_DATASET_REPO)
# Save locally so subsequent chunks don't re-download
os.makedirs(local, exist_ok=True)
diff --git a/src/tokenize_data.py b/src/dataset/tokenize.py
similarity index 98%
rename from src/tokenize_data.py
rename to src/dataset/tokenize.py
index 2ed6f29..793ed6d 100644
--- a/src/tokenize_data.py
+++ b/src/dataset/tokenize.py
@@ -12,7 +12,7 @@ Usage:
import os
import shutil
-from .data import (
+from .dataset import (
CACHE_DIR,
DEFAULT_MAX_DEC_LEN,
DEFAULT_MAX_ENC_LEN,
@@ -70,7 +70,7 @@ def _clear_local_caches():
def _download_synth_dataset():
"""Download synthesized tool-calling dataset (train + validation) from HuggingFace."""
- from .data import download_hf_split
+ from .dataset import download_hf_split
print("Downloading dataset from HuggingFace (Cactus-Compute/tool-calls)...")
for split in ("train", "validation"):
diff --git a/src/tokenizer.py b/src/dataset/tokenizer.py
similarity index 99%
rename from src/tokenizer.py
rename to src/dataset/tokenizer.py
index 79991dd..a29c8ed 100644
--- a/src/tokenizer.py
+++ b/src/dataset/tokenizer.py
@@ -119,7 +119,7 @@ def train_tokenizer(vocab_size=8192, max_samples=None, force=False):
os.makedirs(TOKENIZER_DIR, exist_ok=True)
from datasets import concatenate_datasets
- from .data import _load_split_dataset
+ from .dataset import _load_split_dataset
train_ds = _load_split_dataset("train")
val_ds = _load_split_dataset("validation")
diff --git a/src/model/__init__.py b/src/model/__init__.py
new file mode 100644
index 0000000..8a306ad
--- /dev/null
+++ b/src/model/__init__.py
@@ -0,0 +1,9 @@
+from .architecture import * # noqa: F401,F403
+from .quantize import _quantize_params # noqa: F401
+from .export import export_submodel, slice_params # noqa: F401
+from .run import ( # noqa: F401
+ generate, generate_batch, load_checkpoint,
+ normalize_tools, restore_tool_names,
+ encode_for_retrieval, retrieve_tools,
+ _get_decode_fn,
+)
diff --git a/src/model.py b/src/model/architecture.py
similarity index 72%
rename from src/model.py
rename to src/model/architecture.py
index 2e926c2..6a2a701 100644
--- a/src/model.py
+++ b/src/model/architecture.py
@@ -45,12 +45,16 @@ class TransformerConfig:
dtype: str = "bfloat16"
activation: str = "drelu"
num_memory_slots: int = 64
- n_mels: int = 80
dropout_rate: float = 0.1
contrastive_dim: int = 128
- enable_speech: bool = False
no_feedforward: bool = True
+ def __init__(self, **kwargs):
+ valid = {f.name for f in self.__dataclass_fields__.values()}
+ for k, v in kwargs.items():
+ if k in valid:
+ setattr(self, k, v)
+
@property
def jax_dtype(self):
return DTYPE_MAP[self.dtype]
@@ -148,51 +152,6 @@ class FeedForward(nn.Module):
return nn.Dense(self.d_model, dtype=self.dtype, use_bias=False, kernel_init=residual_init(self.num_layers), name="down_proj")(h)
-class SpeechSubsampling(nn.Module):
- """FastConformer-style 8x depthwise-separable convolutional subsampling.
-
- Input: (B, T, n_mels) raw mel spectrogram.
- Output: (B, T//8, d_model) subsampled features.
-
- Architecture (3 stages of stride-2 = 8x total):
- Conv2D(1 -> C, k=3, s=2) + ReLU
- DW-Conv2D(C, k=3, s=2) + PW-Conv2D(C -> C, k=1) + ReLU
- DW-Conv2D(C, k=3, s=2) + PW-Conv2D(C -> C, k=1) + ReLU
- Reshape(C * F') + Linear -> d_model
- """
- d_model: int
- conv_channels: int = 256
- dtype: jnp.dtype = jnp.bfloat16
-
- @nn.compact
- def __call__(self, mel):
- x = mel[..., None]
-
- x = nn.Conv(features=self.conv_channels, kernel_size=(3, 3), strides=(2, 2),
- padding='SAME', dtype=self.dtype, use_bias=False, name="conv1")(x)
- x = nn.relu(x)
-
- x = nn.Conv(features=self.conv_channels, kernel_size=(3, 3), strides=(2, 2),
- padding='SAME', feature_group_count=self.conv_channels,
- dtype=self.dtype, use_bias=False, name="dw_conv2")(x)
- x = nn.Conv(features=self.conv_channels, kernel_size=(1, 1),
- dtype=self.dtype, use_bias=False, name="pw_conv2")(x)
- x = nn.relu(x)
-
- x = nn.Conv(features=self.conv_channels, kernel_size=(3, 3), strides=(2, 2),
- padding='SAME', feature_group_count=self.conv_channels,
- dtype=self.dtype, use_bias=False, name="dw_conv3")(x)
- x = nn.Conv(features=self.conv_channels, kernel_size=(1, 1),
- dtype=self.dtype, use_bias=False, name="pw_conv3")(x)
- x = nn.relu(x)
-
- B, T, F, C = x.shape
- x = x.reshape(B, T, F * C)
- x = nn.Dense(self.d_model, dtype=self.dtype, use_bias=False,
- kernel_init=default_init(), name="out_proj")(x)
- return x
-
-
class EncoderBlock(nn.Module):
"""Pre-norm self-attention + pre-norm FFN with gated residual connections."""
num_heads: int
@@ -364,41 +323,6 @@ class Decoder(nn.Module):
return x
-class SpecAugment(nn.Module):
- """SpecAugment: time and frequency masking for speech regularization."""
- num_time_masks: int = 2
- max_time_width: int = 100
- num_freq_masks: int = 1
- max_freq_width: int = 27
-
- @nn.compact
- def __call__(self, mel, deterministic=True):
-
- if deterministic:
- return mel
-
- B, T, F = mel.shape
- rng = self.make_rng('specaugment')
-
- x = mel
-
- for i in range(self.num_time_masks):
- rng, k1, k2 = jax.random.split(rng, 3)
- width = jax.random.randint(k1, (), 0, jnp.minimum(self.max_time_width, T))
- start = jax.random.randint(k2, (), 0, jnp.maximum(T - width, 1))
- time_mask = (jnp.arange(T) >= start) & (jnp.arange(T) < start + width)
- x = x * (1.0 - time_mask[None, :, None].astype(x.dtype))
-
- for i in range(self.num_freq_masks):
- rng, k1, k2 = jax.random.split(rng, 3)
- width = jax.random.randint(k1, (), 0, jnp.minimum(self.max_freq_width, F))
- start = jax.random.randint(k2, (), 0, jnp.maximum(F - width, 1))
- freq_mask = (jnp.arange(F) >= start) & (jnp.arange(F) < start + width)
- x = x * (1.0 - freq_mask[None, None, :].astype(x.dtype))
-
- return x
-
-
class EncoderDecoderTransformer(nn.Module):
"""Encoder-decoder transformer with shared embeddings, tied output, RoPE, and bfloat16."""
config: TransformerConfig
@@ -406,10 +330,6 @@ class EncoderDecoderTransformer(nn.Module):
def setup(self):
self.embedding = nn.Embed(self.config.vocab_size, self.config.d_model, embedding_init=jinit.normal(stddev=0.02))
self.embed_scale = math.sqrt(self.config.d_model)
- if self.config.enable_speech:
- self.spec_augment = SpecAugment()
- self.speech_subsample = SpeechSubsampling(
- self.config.d_model, dtype=self.config.jax_dtype, name="speech_subsample")
self.encoder = Encoder(self.config)
self.decoder = Decoder(self.config)
self.contrastive_hidden = nn.Dense(
@@ -421,15 +341,6 @@ class EncoderDecoderTransformer(nn.Module):
use_bias=False, kernel_init=default_init(), name="contrastive_proj",
)
self.log_temp = self.param("log_temp", jinit.zeros, ())
-
- # self.confidence_hidden = nn.Dense(
- # self.config.d_model, dtype=self.config.jax_dtype,
- # kernel_init=default_init(), name="confidence_hidden",
- # )
- # self.confidence_out = nn.Dense(
- # 1, dtype=jnp.float32,
- # kernel_init=jinit.zeros, name="confidence_out",
- # )
def _rope(self, seq_len):
head_dim = self.config.d_model // self.config.num_heads
@@ -444,23 +355,6 @@ class EncoderDecoderTransformer(nn.Module):
"""Backward-compatible alias for encode_text."""
return self.encode_text(src, src_mask=src_mask)
- def encode_speech(self, mel, src_mask=None, ffn_mask=None, deterministic=True):
- assert self.config.enable_speech, "Speech is disabled in config"
- mel = self.spec_augment(mel, deterministic=deterministic)
- # FastConformer-style 8x subsampling: (B, T, 80) -> (B, T//8, d_model)
- x = self.speech_subsample(mel) * self.embed_scale
- if src_mask is not None:
- T_new = x.shape[1]
- # Downsample mask by 8x: group frames and keep valid if any in group
- T_mask = src_mask.shape[-1]
- pad_needed = (8 - T_mask % 8) % 8
- if pad_needed > 0:
- src_mask = jnp.pad(src_mask, ((0, 0), (0, 0), (0, 0), (0, pad_needed)))
- src_mask = src_mask.reshape(src_mask.shape[0], 1, 1, -1, 8).any(axis=-1)
- src_mask = src_mask[..., :T_new]
- rope = self._rope(x.shape[1])
- return self.encoder(x, mask=src_mask, rope=rope, ffn_mask=ffn_mask, deterministic=deterministic)
-
def decode(self, tgt, encoder_out, self_mask=None, cross_mask=None, deterministic=True):
"""Decode from encoder output with cross_mask for variable-length encoder output."""
x = self.embedding(tgt) * self.embed_scale
@@ -480,18 +374,6 @@ class EncoderDecoderTransformer(nn.Module):
counts = jnp.maximum(jnp.sum(mask_2d, axis=1, keepdims=True), 1.0)
return summed / counts
- # def predict_confidence(self, encoder_out, enc_mask):
- # """Predict confidence score [0, 1] from encoder output."""
- # pooled = self._mean_pool(encoder_out, enc_mask)
- # h = nn.relu(self.confidence_hidden(pooled))
- # return nn.sigmoid(self.confidence_out(h)).squeeze(-1)
-
- # def forward_confidence(self, src, src_mask=None):
- # """End-to-end confidence prediction from token input."""
- # encoder_out, enc_mask = self.encode_text(src, src_mask=src_mask)
- # confidence = self.predict_confidence(encoder_out, enc_mask)
- # return confidence, encoder_out, enc_mask
-
def encode_contrastive(self, tokens, deterministic=True):
"""Encode tokens and project to L2-normalized contrastive space. Returns (B, contrastive_dim)."""
src_mask = make_padding_mask(tokens, self.config.pad_token_id)
@@ -532,13 +414,6 @@ class EncoderDecoderTransformer(nn.Module):
logits = x_f32 @ self.embedding.embedding.T
return logits, 0.0
- def forward_speech_masked(self, mel, tgt, src_mask=None, tgt_mask=None, ffn_mask=None, deterministic=True):
- """Single speech forward with per-batch-item FFN masking. Returns (logits, slot_div)."""
- encoder_out, enc_mask = self.encode_speech(mel, src_mask=src_mask, ffn_mask=ffn_mask, deterministic=deterministic)
- x_f32 = self._run_decoder(encoder_out, tgt, tgt_mask=tgt_mask, cross_mask=enc_mask, ffn_mask=ffn_mask, deterministic=deterministic)
- logits = x_f32 @ self.embedding.embedding.T
- return logits, 0.0
-
def _make_eval_ffn_mask(self, ff_width, B, dtype):
"""Default prefix FFN mask for eval: first ff_width neurons active."""
mask = (jnp.arange(self.config.d_ff) < ff_width).astype(dtype)
@@ -567,35 +442,12 @@ class EncoderDecoderTransformer(nn.Module):
return logits, 0.0, mat_logits
- def forward_speech_with_aux(self, mel, tgt, src_mask=None, tgt_mask=None, mat_ff_widths=None, deterministic=True):
- """Eval-only: separate per-width speech forwards for reporting per-width PPL."""
- emb = self.embedding.embedding
- B = mel.shape[0]
-
- encoder_out, enc_mask = self.encode_speech(mel, src_mask=src_mask, deterministic=deterministic)
- x_f32 = self._run_decoder(encoder_out, tgt, tgt_mask=tgt_mask, cross_mask=enc_mask)
- logits = x_f32 @ emb.T
-
- mat_logits = []
- if mat_ff_widths is not None:
- for ff_w in mat_ff_widths:
- mask = self._make_eval_ffn_mask(ff_w, B, x_f32.dtype)
- enc_m, enc_m_mask = self.encode_speech(mel, src_mask=src_mask, ffn_mask=mask, deterministic=deterministic)
- x_m = self._run_decoder(enc_m, tgt, tgt_mask=tgt_mask, cross_mask=enc_m_mask, ffn_mask=mask)
- mat_logits.append(x_m @ emb.T)
-
- return logits, 0.0, mat_logits
-
- def init_all(self, src, tgt, mel=None):
- """Dummy forward through text (and optionally speech) pathways to initialize all params."""
+ def init_all(self, src, tgt):
+ """Dummy forward through text pathway to initialize all params."""
src_mask = make_padding_mask(src, self.config.pad_token_id)
tgt_mask = make_causal_mask(tgt.shape[1]) & make_padding_mask(tgt, self.config.pad_token_id)
text_out, text_enc_mask = self.encode_text(src, src_mask=src_mask)
_ = self._run_decoder(text_out, tgt, tgt_mask=tgt_mask, cross_mask=text_enc_mask)
- if self.config.enable_speech and mel is not None:
- mel_mask = make_mel_padding_mask(mel)
- speech_out, speech_enc_mask = self.encode_speech(mel, src_mask=mel_mask, deterministic=True)
- _ = self._run_decoder(speech_out, tgt, tgt_mask=tgt_mask, cross_mask=speech_enc_mask)
_ = self.encode_contrastive(src)
return jnp.zeros(())
@@ -610,12 +462,6 @@ def make_padding_mask(tokens, pad_token_id):
return mask[:, None, None, :]
-def make_mel_padding_mask(mel):
- """Create padding mask from mel spectrogram: non-zero frames are valid."""
- mask = jnp.any(mel != 0, axis=-1)
- return mask[:, None, None, :]
-
-
def make_packing_mask(seg_ids):
"""Block-diagonal self-attention mask from segment IDs.
diff --git a/src/constrained.py b/src/model/constrained.py
similarity index 100%
rename from src/constrained.py
rename to src/model/constrained.py
diff --git a/src/export.py b/src/model/export.py
similarity index 99%
rename from src/export.py
rename to src/model/export.py
index 694775d..4fc7185 100644
--- a/src/export.py
+++ b/src/model/export.py
@@ -13,7 +13,7 @@ import jax
import jax.numpy as jnp
import numpy as np
-from .model import TransformerConfig
+from .architecture import TransformerConfig
_FFN_KERNEL_NAMES = {"gate_proj", "up_proj", "down_proj"}
diff --git a/src/model/quantize.py b/src/model/quantize.py
new file mode 100644
index 0000000..dc449e6
--- /dev/null
+++ b/src/model/quantize.py
@@ -0,0 +1,68 @@
+import jax
+import jax.numpy as jnp
+
+
+def _fake_quantize_int4(w, group_size=32):
+ """Symmetric group-wise INT4 fake quantization with STE.
+
+ Divides the input dimension (axis 0) into groups of `group_size` elements,
+ each with its own scale factor. Falls back to per-channel if in_features < group_size.
+ """
+ in_feat, out_feat = w.shape
+ gs = min(group_size, in_feat)
+
+ pad = (gs - in_feat % gs) % gs
+ if pad > 0:
+ w_padded = jnp.pad(w, ((0, pad), (0, 0)))
+ else:
+ w_padded = w
+
+ num_groups = w_padded.shape[0] // gs
+ w_grouped = w_padded.reshape(num_groups, gs, out_feat)
+
+ scale = jnp.max(jnp.abs(w_grouped), axis=1, keepdims=True) / 7.0
+ scale = jnp.maximum(scale, 1e-8)
+ w_q = jnp.clip(jnp.round(w_grouped / scale), -8, 7) * scale
+
+ w_q = w_q.reshape(-1, out_feat)[:in_feat]
+
+ return w + jax.lax.stop_gradient(w_q - w)
+
+
+def _fake_quantize_int8(w, group_size=32):
+ """Symmetric group-wise INT8 fake quantization with STE.
+
+ Same structure as INT4 but with [-128, 127] range (8-bit signed).
+ """
+ in_feat, out_feat = w.shape
+ gs = min(group_size, in_feat)
+
+ pad = (gs - in_feat % gs) % gs
+ if pad > 0:
+ w_padded = jnp.pad(w, ((0, pad), (0, 0)))
+ else:
+ w_padded = w
+
+ num_groups = w_padded.shape[0] // gs
+ w_grouped = w_padded.reshape(num_groups, gs, out_feat)
+
+ scale = jnp.max(jnp.abs(w_grouped), axis=1, keepdims=True) / 127.0
+ scale = jnp.maximum(scale, 1e-8)
+ w_q = jnp.clip(jnp.round(w_grouped / scale), -128, 127) * scale
+
+ w_q = w_q.reshape(-1, out_feat)[:in_feat]
+
+ return w + jax.lax.stop_gradient(w_q - w)
+
+
+def _quantize_params(params, group_size=32, precision="int4"):
+ """Fake-quantize all Dense kernels in the param tree."""
+ qfn = _fake_quantize_int8 if precision == "int8" else _fake_quantize_int4
+ def _maybe_quantize(path, leaf):
+ name = path[-1].key if hasattr(path[-1], "key") else str(path[-1])
+ if name == "kernel" and leaf.ndim == 3:
+ return jax.vmap(lambda w: qfn(w, group_size=group_size), in_axes=(0,))(leaf)
+ if name == "kernel" and leaf.ndim == 2:
+ return qfn(leaf, group_size=group_size)
+ return leaf
+ return jax.tree_util.tree_map_with_path(_maybe_quantize, params)
diff --git a/src/run.py b/src/model/run.py
similarity index 63%
rename from src/run.py
rename to src/model/run.py
index 537d434..e07d459 100644
--- a/src/run.py
+++ b/src/model/run.py
@@ -8,13 +8,12 @@ import jax
import jax.numpy as jnp
import numpy as np
-from .data import get_tokenizer, compute_mel_spectrogram, to_snake_case, DEFAULT_MAX_ENC_LEN, DEFAULT_MAX_GEN_LEN
-from .model import (
+from ..dataset.dataset import get_tokenizer, to_snake_case, DEFAULT_MAX_ENC_LEN, DEFAULT_MAX_GEN_LEN
+from .architecture import (
EncoderDecoderTransformer,
TransformerConfig,
make_causal_mask,
make_padding_mask,
- make_mel_padding_mask,
)
@@ -180,86 +179,6 @@ def generate(model, params, tokenizer, query, tools="[]", max_gen_len=DEFAULT_MA
return result
-def generate_with_confidence(model, params, tokenizer, query, tools="[]",
- max_gen_len=DEFAULT_MAX_GEN_LEN, max_enc_len=DEFAULT_MAX_ENC_LEN,
- seed=0, stream=True, normalize=True, constrained=True,
- confidence_threshold=None):
- """Generate tool calls with confidence score.
-
- Returns (result, confidence) where confidence is a float in [0, 1].
- If confidence_threshold is set and confidence is below it, returns
- (None, confidence) without running the decoder — saving compute for
- queries that should be routed to cloud.
- """
- name_map = {}
- if normalize:
- tools, name_map = normalize_tools(tools)
-
- enc_tokens = _build_encoder_input(tokenizer, query, tools, max_enc_len)
- enc_input = jnp.array([enc_tokens])
- pad_id = tokenizer.pad_token_id
- src_mask = make_padding_mask(enc_input, pad_id)
-
- # Get confidence + encoder output in one pass
- confidence, encoder_out, enc_mask = model.apply(
- {"params": params}, enc_input, src_mask=src_mask,
- method="forward_confidence",
- )
- confidence_val = float(confidence[0])
-
- # Early exit if below threshold — skip decoder entirely
- if confidence_threshold is not None and confidence_val < confidence_threshold:
- return None, confidence_val
-
- # Proceed with normal decoding using already-computed encoder output
- eos_id = tokenizer.eos_token_id
- dec_buffer = jnp.full((1, max_gen_len), pad_id, dtype=jnp.int32)
- dec_buffer = dec_buffer.at[0, 0].set(eos_id)
-
- decode_fn = _get_decode_fn(model, max_gen_len)
-
- constrained_decoder = None
- if constrained:
- from .constrained import build_constrained_decoder
- constrained_decoder = build_constrained_decoder([tools], tokenizer)
-
- if stream:
- sys.stdout.write(f"\n")
- sys.stdout.flush()
-
- logits = decode_fn(params, dec_buffer, encoder_out, enc_mask)
- generated_tokens = []
-
- for i in range(0, max_gen_len - 1):
- next_logits = logits[0, i]
- if constrained_decoder and constrained_decoder.is_active(0):
- logits_np = np.array(next_logits)
- logits_np = constrained_decoder.constrain_logits(logits_np, 0)
- next_token = int(np.argmax(logits_np))
- else:
- next_token = int(jnp.argmax(next_logits))
- if constrained_decoder:
- constrained_decoder.update(0, next_token)
- if next_token == eos_id:
- break
- generated_tokens.append(next_token)
- dec_buffer = dec_buffer.at[0, i + 1].set(next_token)
- if stream:
- sys.stdout.write(tokenizer.decode([next_token]))
- sys.stdout.flush()
- logits = decode_fn(params, dec_buffer, encoder_out, enc_mask)
-
- if stream:
- sys.stdout.write("\n")
-
- result = tokenizer.decode(generated_tokens)
- if result.startswith("<tool_call>"):
- result = result[len("<tool_call>"):]
- if normalize and name_map:
- result = restore_tool_names(result, name_map)
- return result, confidence_val
-
-
def generate_batch(model, params, tokenizer, queries, tools_list, max_gen_len=DEFAULT_MAX_GEN_LEN, max_enc_len=DEFAULT_MAX_ENC_LEN, normalize=True, constrained=True):
"""Batch-generate tool-call outputs for multiple examples at once.
@@ -346,93 +265,6 @@ def generate_batch(model, params, tokenizer, queries, tools_list, max_gen_len=DE
return results
-def load_audio(path, target_sr=16000):
- """Load an audio file and resample to target_sr. Returns (audio_array, sr)."""
- import soundfile as sf
- audio, sr = sf.read(path, dtype="float32")
- if audio.ndim > 1:
- audio = audio.mean(axis=1)
- if sr != target_sr:
- from scipy.signal import resample
- num_samples = int(len(audio) * target_sr / sr)
- audio = resample(audio, num_samples).astype(np.float32)
- sr = target_sr
- return audio, sr
-
-
-def generate_from_audio(model, params, tokenizer, audio_array, sr=16000, tools="[]", max_gen_len=DEFAULT_MAX_GEN_LEN, seed=0, stream=True, constrained=True):
- """Generate tool-call output from audio using the speech encoder pathway.
-
- mel -> encode_speech -> decoder [BOS, <tool_call>, tools_tokens...] -> greedy decode.
- Same structure as generate() but uses speech encoder + mel padding mask.
- """
- n_mels = model.config.n_mels
- mel = compute_mel_spectrogram(audio_array, sr=sr, n_mels=n_mels)
- mel_input = jnp.array(mel)[None, :, :] # (1, T_mel, n_mels)
-
- pad_id = tokenizer.pad_token_id
- eos_id = tokenizer.eos_token_id
- tool_call_id = tokenizer.tool_call_token_id
-
- src_mask = make_mel_padding_mask(mel_input)
- encoder_out, enc_mask = model.apply(
- {"params": params}, mel_input, src_mask=src_mask, deterministic=True, method="encode_speech"
- )
-
- tools_tokens = tokenizer.encode(tools)
- prefix = [eos_id, tool_call_id] + tools_tokens
- prefix_len = min(len(prefix), max_gen_len)
-
- dec_buffer = jnp.full((1, max_gen_len), pad_id, dtype=jnp.int32)
- for j, tok in enumerate(prefix[:max_gen_len]):
- dec_buffer = dec_buffer.at[0, j].set(tok)
-
- decode_fn = _get_decode_fn(model, max_gen_len)
-
- generated_tokens = []
-
- constrained_decoder = None
- if constrained:
- from .constrained import build_constrained_decoder
- constrained_decoder = build_constrained_decoder([tools], tokenizer)
-
- if stream:
- sys.stdout.write("\n")
- sys.stdout.flush()
-
- logits = decode_fn(params, dec_buffer, encoder_out, enc_mask)
-
- for i in range(prefix_len - 1, max_gen_len - 1):
- next_logits = logits[0, i]
-
- if constrained_decoder and constrained_decoder.is_active(0):
- logits_np = np.array(next_logits)
- logits_np = constrained_decoder.constrain_logits(logits_np, 0)
- next_token = int(np.argmax(logits_np))
- else:
- next_token = int(jnp.argmax(next_logits))
-
- if constrained_decoder:
- constrained_decoder.update(0, next_token)
-
- if next_token == eos_id:
- break
-
- generated_tokens.append(next_token)
- dec_buffer = dec_buffer.at[0, i + 1].set(next_token)
-
- if stream:
- sys.stdout.write(tokenizer.decode([next_token]))
- sys.stdout.flush()
-
- logits = decode_fn(params, dec_buffer, encoder_out, enc_mask)
-
- if stream:
- sys.stdout.write("\n")
-
- return tokenizer.decode(generated_tokens)
-
-
def main(args):
print(f"Loading checkpoint: {args.checkpoint}")
params, config = load_checkpoint(args.checkpoint)
@@ -445,27 +277,6 @@ def main(args):
use_constrained = not getattr(args, "no_constrained", False)
- audio_files = getattr(args, "audio", None)
- if audio_files:
- tools = getattr(args, "tools", None) or "[]"
- for i, audio_path in enumerate(audio_files):
- print(f"\nVoice-to-tool-call: {audio_path}")
- print(f"Tools: {tools[:80]}{'...' if len(tools) > 80 else ''}")
- audio, sr = load_audio(audio_path)
- generate_from_audio(
- model,
- params,
- tokenizer,
- audio,
- sr=sr,
- tools=tools,
- max_gen_len=args.max_len,
- seed=args.seed + i,
- stream=True,
- constrained=use_constrained,
- )
- return
-
query = getattr(args, "query", None)
tools = getattr(args, "tools", None) or "[]"
@@ -538,7 +349,6 @@ def parse_args():
parser.add_argument("--checkpoint", type=str, default="checkpoints/checkpoint_epoch3.pkl")
parser.add_argument("--query", type=str, default=None, help="Query text for tool-call generation")
parser.add_argument("--tools", type=str, default=None, help="Tools JSON for tool-call generation")
- parser.add_argument("--audio", type=str, nargs="*", help="Audio file paths for voice-to-tool-call")
parser.add_argument("--max-len", type=int, default=512)
parser.add_argument("--seed", type=int, default=0)
return parser.parse_args()
diff --git a/src/quantize.py b/src/quantize.py
deleted file mode 100644
index 6f86eb8..0000000
--- a/src/quantize.py
+++ /dev/null
@@ -1,133 +0,0 @@
-import jax
-import jax.numpy as jnp
-
-
-def _fake_quantize_int4(w, group_size=32):
- """Symmetric group-wise INT4 fake quantization with STE.
-
- Divides the input dimension (axis 0) into groups of `group_size` elements,
- each with its own scale factor. Falls back to per-channel if in_features < group_size.
- """
- in_feat, out_feat = w.shape
- gs = min(group_size, in_feat)
-
- pad = (gs - in_feat % gs) % gs
- if pad > 0:
- w_padded = jnp.pad(w, ((0, pad), (0, 0)))
- else:
- w_padded = w
-
- num_groups = w_padded.shape[0] // gs
- w_grouped = w_padded.reshape(num_groups, gs, out_feat)
-
- scale = jnp.max(jnp.abs(w_grouped), axis=1, keepdims=True) / 7.0
- scale = jnp.maximum(scale, 1e-8)
- w_q = jnp.clip(jnp.round(w_grouped / scale), -8, 7) * scale
-
- w_q = w_q.reshape(-1, out_feat)[:in_feat]
-
- return w + jax.lax.stop_gradient(w_q - w)
-
-
-def _fake_quantize_int8(w, group_size=32):
- """Symmetric group-wise INT8 fake quantization with STE.
-
- Same structure as INT4 but with [-128, 127] range (8-bit signed).
- """
- in_feat, out_feat = w.shape
- gs = min(group_size, in_feat)
-
- pad = (gs - in_feat % gs) % gs
- if pad > 0:
- w_padded = jnp.pad(w, ((0, pad), (0, 0)))
- else:
- w_padded = w
-
- num_groups = w_padded.shape[0] // gs
- w_grouped = w_padded.reshape(num_groups, gs, out_feat)
-
- scale = jnp.max(jnp.abs(w_grouped), axis=1, keepdims=True) / 127.0
- scale = jnp.maximum(scale, 1e-8)
- w_q = jnp.clip(jnp.round(w_grouped / scale), -128, 127) * scale
-
- w_q = w_q.reshape(-1, out_feat)[:in_feat]
-
- return w + jax.lax.stop_gradient(w_q - w)
-
-
-def _quantize_params(params, group_size=32, precision="int4"):
- """Fake-quantize all Dense kernels in the param tree."""
- qfn = _fake_quantize_int8 if precision == "int8" else _fake_quantize_int4
- def _maybe_quantize(path, leaf):
- name = path[-1].key if hasattr(path[-1], "key") else str(path[-1])
- if name == "kernel" and leaf.ndim == 3:
- return jax.vmap(lambda w: qfn(w, group_size=group_size), in_axes=(0,))(leaf)
- if name == "kernel" and leaf.ndim == 2:
- return qfn(leaf, group_size=group_size)
- return leaf
- return jax.tree_util.tree_map_with_path(_maybe_quantize, params)
-
-
-def _cubic_sparsity_schedule(step, t_start, t_end, s_final):
- """Cubic sparsity ramp (Zhu & Gupta 2017). Returns target sparsity at *step*."""
- if step < t_start:
- return 0.0
- if step >= t_end:
- return s_final
- frac = (step - t_start) / (t_end - t_start)
- return s_final * (1.0 - (1.0 - frac) ** 3)
-
-
-def _make_prune_mask(params, sparsity, group_size):
- """Compute block-prune mask entirely on-device (no numpy round-trips).
-
- Returns binary mask tree matching param shapes and dtypes.
- Handles both 2D (in, out) and 3D (num_layers, in, out) kernels from nn.scan.
- """
- all_scores = []
- for _, leaf in jax.tree_util.tree_leaves_with_path(params):
- if leaf.ndim == 2:
- in_feat, out_feat = leaf.shape
- gs = min(group_size, in_feat)
- pad = (gs - in_feat % gs) % gs
- w = jnp.pad(leaf, ((0, pad), (0, 0))) if pad else leaf
- scores = jnp.sum(jnp.abs(w.reshape(-1, gs, out_feat)), axis=1).ravel()
- all_scores.append(scores)
- elif leaf.ndim == 3:
- num_layers, in_feat, out_feat = leaf.shape
- gs = min(group_size, in_feat)
- pad = (gs - in_feat % gs) % gs
- for li in range(num_layers):
- w = jnp.pad(leaf[li], ((0, pad), (0, 0))) if pad else leaf[li]
- scores = jnp.sum(jnp.abs(w.reshape(-1, gs, out_feat)), axis=1).ravel()
- all_scores.append(scores)
-
- if not all_scores:
- return jax.tree.map(jnp.ones_like, params)
-
- threshold = jnp.percentile(jnp.concatenate(all_scores), sparsity * 100)
-
- def _leaf_mask(path, leaf):
- if leaf.ndim == 3:
- num_layers, in_feat, out_feat = leaf.shape
- gs = min(group_size, in_feat)
- pad = (gs - in_feat % gs) % gs
- masks = []
- for li in range(num_layers):
- w = jnp.pad(leaf[li], ((0, pad), (0, 0))) if pad else leaf[li]
- w_grouped = w.reshape(-1, gs, out_feat)
- block_keep = (jnp.sum(jnp.abs(w_grouped), axis=1, keepdims=True) > threshold)
- m = jnp.broadcast_to(block_keep, w_grouped.shape).reshape(-1, out_feat)[:in_feat]
- masks.append(m)
- return jnp.stack(masks, axis=0).astype(leaf.dtype)
- if leaf.ndim != 2:
- return jnp.ones_like(leaf)
- in_feat, out_feat = leaf.shape
- gs = min(group_size, in_feat)
- pad = (gs - in_feat % gs) % gs
- w = jnp.pad(leaf, ((0, pad), (0, 0))) if pad else leaf
- w_grouped = w.reshape(-1, gs, out_feat)
- block_keep = (jnp.sum(jnp.abs(w_grouped), axis=1, keepdims=True) > threshold)
- return jnp.broadcast_to(block_keep, w_grouped.shape).reshape(-1, out_feat)[:in_feat].astype(leaf.dtype)
-
- return jax.tree_util.tree_map_with_path(_leaf_mask, params)
diff --git a/src/training/__init__.py b/src/training/__init__.py
new file mode 100644
index 0000000..5732bd7
--- /dev/null
+++ b/src/training/__init__.py
@@ -0,0 +1,4 @@
+from .optim import create_train_state, _wsd_schedule # noqa: F401
+from .train import train # noqa: F401
+from .pretrain import pretrain # noqa: F401
+from .finetune import finetune_local # noqa: F401
diff --git a/src/eval.py b/src/training/eval.py
similarity index 98%
rename from src/eval.py
rename to src/training/eval.py
index 6fb1d31..330e157 100644
--- a/src/eval.py
+++ b/src/training/eval.py
@@ -7,8 +7,8 @@ import jax.numpy as jnp
import numpy as np
import optax
-from .data import get_tokenizer, load_tool_calls, load_prepared_data, DEFAULT_MAX_ENC_LEN, DEFAULT_MAX_DEC_LEN, DEFAULT_MAX_GEN_LEN
-from .model import (
+from ..dataset.dataset import get_tokenizer, load_tool_calls, load_prepared_data, DEFAULT_MAX_ENC_LEN, DEFAULT_MAX_DEC_LEN, DEFAULT_MAX_GEN_LEN
+from ..model.architecture import (
EncoderDecoderTransformer,
TransformerConfig,
make_causal_mask,
@@ -17,7 +17,7 @@ from .model import (
make_packing_mask,
make_cross_packing_mask,
)
-from .run import load_checkpoint, _get_decode_fn
+from ..model.run import load_checkpoint, _get_decode_fn
def compute_perplexity_packed(model, params, packed_data, batch_size):
@@ -129,7 +129,7 @@ def compute_repetition_rate(texts):
def benchmark_generation_quality(model, params, tokenizer, prompts, max_gen_len=128, temperature=0.8):
- from .run import generate
+ from ..model.run import generate
generations = []
for i, prompt in enumerate(prompts):
@@ -181,8 +181,8 @@ def compute_wer(hypotheses, references):
def benchmark_tool_calls(model, params, tokenizer, num_samples=200, max_gen_len=DEFAULT_MAX_GEN_LEN, max_enc_len=DEFAULT_MAX_ENC_LEN, constrained=True, ds=None):
"""Generate tool-call predictions and compute structured metrics."""
import json
- from .run import generate_batch, normalize_tools, restore_tool_names
- from .data import load_tool_calls, to_snake_case
+ from ..model.run import generate_batch, normalize_tools, restore_tool_names
+ from ..dataset.dataset import load_tool_calls, to_snake_case
if ds is None:
ds = load_tool_calls("validation", max_samples=num_samples)
@@ -456,7 +456,7 @@ def benchmark_retrieval(model, params, tokenizer, num_samples=500, max_len=256,
and checks if the positive (called) tools appear in top-k.
"""
import json
- from .run import encode_for_retrieval
+ from ..model.run import encode_for_retrieval
if ds is None:
ds = load_tool_calls("validation", max_samples=num_samples)
diff --git a/src/finetune.py b/src/training/finetune.py
similarity index 96%
rename from src/finetune.py
rename to src/training/finetune.py
index 77c7498..b962a1a 100644
--- a/src/finetune.py
+++ b/src/training/finetune.py
@@ -7,8 +7,8 @@ import shutil
import tempfile
import time
-from . import data as data_mod
-from .data import _cache_key, _save_cache_metadata, get_tokenizer, pack_sequences, prepare_tool_call_pairs
+from ..dataset import dataset as data_mod
+from ..dataset.dataset import _cache_key, _save_cache_metadata, get_tokenizer, pack_sequences, prepare_tool_call_pairs
def _write_split(split, examples, tokenizer, cache_dir, max_enc_len, max_dec_len):
@@ -60,7 +60,7 @@ def _call_key(c):
def _quick_tool_eval(model, params, tokenizer, examples, max_gen_len=512, max_enc_len=1024):
"""Tool-call eval matching needle's F1 methodology (TP/FP/FN)."""
- from .run import generate_batch
+ from ..model.run import generate_batch
samples = [ex for ex in examples
if ex.get("answers", "").strip() not in ("", "[]")]
@@ -222,7 +222,7 @@ def finetune_local(args):
if len(examples) < 3:
raise ValueError("finetune requires at least 3 examples for train/val/test splits")
- from .tokenizer import DEFAULT_MAX_ENC_LEN, DEFAULT_MAX_DEC_LEN
+ from ..dataset.tokenizer import DEFAULT_MAX_ENC_LEN, DEFAULT_MAX_DEC_LEN
max_enc_len = getattr(args, "max_enc_len", None) or DEFAULT_MAX_ENC_LEN
max_dec_len = getattr(args, "max_dec_len", None) or DEFAULT_MAX_DEC_LEN
@@ -276,8 +276,8 @@ def finetune_local(args):
val_ds = _Dataset.from_list(val_examples)
# Base model eval on TEST set (never seen by model)
- from .run import load_checkpoint
- from .model import EncoderDecoderTransformer
+ from ..model.run import load_checkpoint
+ from ..model.architecture import EncoderDecoderTransformer
print(f"Evaluating base model on {len(test_examples)} test examples...")
base_params, base_config = load_checkpoint(args.checkpoint)
base_model = EncoderDecoderTransformer(base_config)
@@ -310,20 +310,18 @@ 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),
- sparsity_ratio=0.0, group_size=32, precision="int4",
- prune_interval=100, prune_start_frac=0.33, prune_end_frac=0.67,
+ 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),
- enable_speech=cfg.get("enable_speech", False),
w_name=2.0, w_value=4.0, w_key=1.5,
no_feedforward=cfg.get("no_feedforward", True),
val_ds=val_ds,
)
- from .train import train
+ from ..training.train import train
train(train_args)
best_path = _ensure_best_checkpoint(args.checkpoint_dir, run_id)
diff --git a/src/optim.py b/src/training/optim.py
similarity index 94%
rename from src/optim.py
rename to src/training/optim.py
index 301402c..4ca0690 100644
--- a/src/optim.py
+++ b/src/training/optim.py
@@ -4,7 +4,7 @@ import jax
import jax.numpy as jnp
import optax
from flax.training import train_state
-from .model import EncoderDecoderTransformer
+from ..model.architecture import EncoderDecoderTransformer
def _newton_schulz(G, steps=5):
@@ -87,12 +87,9 @@ def create_train_state(rng, config, learning_rate, muon_lr, total_steps, warmup_
rng, init_rng = jax.random.split(rng)
dummy_src = jnp.ones((1, 128), dtype=jnp.int32)
dummy_tgt = jnp.ones((1, 128), dtype=jnp.int32)
- init_args = [dummy_src, dummy_tgt]
- if config.enable_speech:
- init_args.append(jnp.ones((1, 128, config.n_mels), dtype=jnp.float32))
variables = model.init(
{"params": init_rng},
- *init_args,
+ dummy_src, dummy_tgt,
method="init_all",
)
diff --git a/src/pretrain.py b/src/training/pretrain.py
similarity index 98%
rename from src/pretrain.py
rename to src/training/pretrain.py
index 94d852d..668ff4d 100644
--- a/src/pretrain.py
+++ b/src/training/pretrain.py
@@ -22,15 +22,15 @@ import numpy as np
import optax
from tqdm import tqdm
-from .tokenizer import get_tokenizer, EOS_ID, TOOLS_ID, PAD_ID
-from .model import (
+from ..dataset.tokenizer import get_tokenizer, EOS_ID, TOOLS_ID, PAD_ID
+from ..model.architecture import (
EncoderDecoderTransformer,
TransformerConfig,
make_padding_mask,
make_causal_mask,
)
from .optim import create_train_state, _wsd_schedule
-from .distributed import _replicate, _unreplicate, shard_batch, _upload_checkpoint
+from ..utils.distributed import _replicate, _unreplicate, shard_batch, _upload_checkpoint
_HF_PRETRAIN_REPO = "PleIAs/SYNTH"
@@ -235,7 +235,6 @@ def pretrain(args):
activation=getattr(args, "activation", "swiglu"),
no_feedforward=getattr(args, "no_feedforward", True),
contrastive_dim=getattr(args, "contrastive_dim", 128),
- enable_speech=False,
)
effective_batch_size = args.batch_size * num_devices
diff --git a/src/train.py b/src/training/train.py
similarity index 90%
rename from src/train.py
rename to src/training/train.py
index 4975c78..e147944 100644
--- a/src/train.py
+++ b/src/training/train.py
@@ -9,13 +9,13 @@ import numpy as np
import optax
from tqdm import tqdm
-from .data import (
+from ..dataset.dataset import (
get_batches, get_tokenizer,
load_prepared_data, load_tool_calls,
PrefetchIterator, count_batches,
get_contrastive_batches,
)
-from .model import (
+from ..model.architecture import (
EncoderDecoderTransformer,
TransformerConfig,
make_packing_mask,
@@ -23,16 +23,13 @@ from .model import (
make_cross_packing_mask,
)
from .optim import create_train_state, _wsd_schedule
-from .distributed import (
+from ..utils.distributed import (
_replicate, _unreplicate, shard_batch, _upload_checkpoint,
load_pretrained_params, partial_load_params,
)
-from .quantize import (
- _quantize_params, _cubic_sparsity_schedule, _make_prune_mask,
-)
+from ..model.quantize import _quantize_params
-_GROUP_SIZE = 32
_PRECISION = "int4"
_MAT_FACTORS = ()
_MAT_FF_WIDTHS = ()
@@ -58,7 +55,7 @@ def _text_loss_fn(state, params, src, tgt_in, tgt_out, ffn_mask, rng, loss_mask,
enc_seg_ids, dec_seg_ids):
q_params = jax.lax.cond(
do_quantize,
- lambda p: _quantize_params(p, group_size=_GROUP_SIZE, precision=_PRECISION),
+ lambda p: _quantize_params(p, precision=_PRECISION),
lambda p: p,
params,
)
@@ -96,7 +93,7 @@ def _contrastive_loss_fn(state, params, query_tokens, tool_tokens, rng, do_quant
"""Compute CLIP contrastive loss on query/tool pairs."""
q_params = jax.lax.cond(
do_quantize,
- lambda p: _quantize_params(p, group_size=_GROUP_SIZE, precision=_PRECISION),
+ lambda p: _quantize_params(p, precision=_PRECISION),
lambda p: p,
params,
)
@@ -129,8 +126,8 @@ def _make_ffn_mask(batch_size, d_ff, mat_ff_widths):
return jnp.concatenate(rows, axis=0)
-def _train_step(state, src, tgt_in, tgt_out, enc_seg_ids, dec_seg_ids, prune_mask, ffn_mask, rng, loss_mask, query_tokens, tool_tokens, cl_rng, do_quantize, do_contrastive, do_prune):
- """Unified train step with boolean flags for contrastive loss and pruning."""
+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):
+ """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,
@@ -147,12 +144,6 @@ def _train_step(state, src, tgt_in, tgt_out, enc_seg_ids, dec_seg_ids, prune_mas
text_loss = jax.lax.pmean(text_loss, axis_name="batch")
grad_norm = optax.global_norm(grads)
state = state.apply_gradients(grads=grads)
- new_params = jax.lax.cond(
- do_prune,
- lambda: jax.tree.map(lambda w, m: w * m, state.params, prune_mask),
- lambda: state.params,
- )
- state = state.replace(params=new_params)
return state, text_loss, grad_norm
@@ -213,15 +204,9 @@ def _estimate_mat_params(config, matryoshka_factor):
emb = v * d
attn = d * d + d * kv_dim * 2 + d * d
ffn = d * d_ff * 3
- speech_sub = 0
- if getattr(config, "enable_speech", True):
- C = 256
- n_mels = getattr(config, "n_mels", 80)
- freq_out = n_mels // 8
- speech_sub = (1 * C * 9) + (C * 9 + C * C) + (C * 9 + C * C) + (C * freq_out * d)
enc_block = attn + ffn
dec_block = attn * 2 + ffn
- total = emb + speech_sub + n_enc * enc_block + n_dec * dec_block
+ total = emb + n_enc * enc_block + n_dec * dec_block
return int(total)
@@ -316,12 +301,10 @@ def train(args):
activation=getattr(args, "activation", "drelu"),
num_memory_slots=getattr(args, "num_memory_slots", 64),
contrastive_dim=getattr(args, "contrastive_dim", 128),
- enable_speech=getattr(args, "enable_speech", False),
no_feedforward=getattr(args, "no_feedforward", True),
)
- global _GROUP_SIZE, _PRECISION, _MAT_FACTORS, _MAT_FF_WIDTHS, _D_FF, _CONTRASTIVE_WEIGHT, _LOSS_WEIGHT_MAP
- _GROUP_SIZE = getattr(args, "group_size", 32)
+ global _PRECISION, _MAT_FACTORS, _MAT_FF_WIDTHS, _D_FF, _CONTRASTIVE_WEIGHT, _LOSS_WEIGHT_MAP
_PRECISION = getattr(args, "precision", "int4")
_CONTRASTIVE_WEIGHT = getattr(args, "contrastive_weight", 0.1)
_LOSS_WEIGHT_MAP = jnp.array([
@@ -435,31 +418,11 @@ def train(args):
eval_model = EncoderDecoderTransformer(config)
last_val_ppl = None
- sparsity_ratio = getattr(args, "sparsity_ratio", 0.0)
- prune_mask = None
- gradual_sparsify_done = False
- # Dummy all-ones prune mask (replicated) — used when pruning is inactive
- _unrep_params = _unreplicate(state).params
- dummy_prune_mask = _replicate(jax.tree.map(jnp.ones_like, _unrep_params))
- del _unrep_params
# Dummy contrastive arrays — used when contrastive is inactive
dummy_cl_tokens = jnp.zeros((num_devices, args.batch_size, 128), dtype=jnp.int32)
dummy_cl_rng = jax.random.split(jax.random.PRNGKey(0), num_devices)
- prune_interval = getattr(args, "prune_interval", 100)
- prune_start_frac = getattr(args, "prune_start_frac", 0.33)
- prune_end_frac = getattr(args, "prune_end_frac", 0.67)
-
- weight_prune_epoch = 0 if sparsity_ratio > 0 else -1
-
for epoch in range(args.epochs):
- if epoch == weight_prune_epoch and not gradual_sparsify_done:
- t_start = int(num_batches * prune_start_frac)
- t_end = int(num_batches * prune_end_frac)
- print(f"\nGradual magnitude sparsification: 0% -> {sparsity_ratio*100:.0f}% over epoch {epoch+1} "
- f"(steps {t_start}-{t_end}/{num_batches}, interval={prune_interval}, group_size={_GROUP_SIZE})")
- epoch_step = 0
-
text_losses = []
text_batch_iter = PrefetchIterator(
lambda: get_batches(enc_inputs, dec_inputs, dec_targets, global_batch_size,
@@ -526,13 +489,11 @@ def train(args):
do_contrastive = False
do_cl = jnp.broadcast_to(jnp.array(do_contrastive), (num_devices,))
- do_prune = jnp.broadcast_to(jnp.array(prune_mask is not None), (num_devices,))
- cur_prune_mask = prune_mask if prune_mask is not None else dummy_prune_mask
state, loss, grad_norm = p_train_step(
state, src_b, tgt_in_b, tgt_out_b, enc_seg_b, dec_seg_b,
- cur_prune_mask, text_ffn_mask, text_rngs, lm_b,
- cl_q_b, cl_t_b, cl_rngs, do_qat, do_cl, do_prune,
+ text_ffn_mask, text_rngs, lm_b,
+ cl_q_b, cl_t_b, cl_rngs, do_qat, do_cl,
)
text_loss_val = float(loss.addressable_shards[0].data[0])
@@ -540,16 +501,6 @@ def train(args):
step_grad_norm = float(grad_norm.addressable_shards[0].data[0])
global_step += 1
- if epoch == weight_prune_epoch and not gradual_sparsify_done:
- epoch_step += 1
- current_sparsity = _cubic_sparsity_schedule(epoch_step, t_start, t_end, sparsity_ratio)
- if epoch_step >= t_start and epoch_step % prune_interval == 0 and current_sparsity > 0:
- ema_unr = _unreplicate(state.params)
- mask = _make_prune_mask(ema_unr, current_sparsity, _GROUP_SIZE)
- del ema_unr
- prune_mask = _replicate(mask)
- del mask
-
dt = time.perf_counter() - t0
eval_every = getattr(args, "eval_every", 100)
if is_main and (global_step % eval_every == 0 or global_step == total_steps):
@@ -577,11 +528,6 @@ def train(args):
"text_loss": f"{text_loss_val:.4f}",
"text_ppl": f"{last_val_ppl:.2f}" if last_val_ppl is not None else "?",
}
- if sparsity_ratio > 0:
- if epoch == weight_prune_epoch and not gradual_sparsify_done:
- postfix["sparsification"] = f"{current_sparsity*100:.1f}%"
- else:
- postfix["sparsification"] = "done"
pbar.set_postfix(**postfix)
if use_wandb and is_main:
@@ -593,8 +539,6 @@ def train(args):
"train/tokens_per_sec": tokens_per_batch / dt,
"train/step": global_step,
}
- if epoch == weight_prune_epoch and not gradual_sparsify_done:
- log_dict["train/scheduled_sparsity"] = current_sparsity
if global_step % eval_every == 0 or global_step == total_steps:
log_dict["val/text_ppl"] = last_val_ppl
wandb.log(log_dict)
@@ -603,23 +547,6 @@ def train(args):
if cl_batch_iter is not None:
cl_batch_iter.close()
- if epoch == weight_prune_epoch and not gradual_sparsify_done:
- gradual_sparsify_done = True
- if prune_mask is None:
- ema_unr = _unreplicate(state.params)
- mask = _make_prune_mask(ema_unr, sparsity_ratio, _GROUP_SIZE)
- del ema_unr
- prune_mask = _replicate(mask)
- del mask
- state = state.replace(
- params=jax.tree.map(lambda w, m: w * m, state.params, prune_mask))
- final_pruned = jax.tree.map(np.array, _unreplicate(state).params)
- total_p = sum(x.size for x in jax.tree.leaves(final_pruned))
- zero_p = sum(int(np.sum(np.abs(x) < 1e-6)) for x in jax.tree.leaves(final_pruned))
- print(f"\n Gradual sparsification complete — mask locked.")
- print(f" Final sparsity: {zero_p/total_p*100:.2f}% ({zero_p:,}/{total_p:,} near-zero)")
- del final_pruned
-
epoch_avg_loss = sum(text_losses) / len(text_losses) if text_losses else float("nan")
final_loss = text_losses[-1] if text_losses else float("nan")
final_ppl = math.exp(min(final_loss, 20)) if not math.isnan(final_loss) else float("nan")
@@ -630,12 +557,11 @@ def train(args):
# ── Host 0 only: val PPL + checkpoint save (fast) ──
quant_val_ppl = 0.0
mat_results = {}
- sparsity = 0.0
- total_params = near_zero = 0
+ total_params = 0
ckpt_path = ""
if is_main:
- q_params = _quantize_params(eval_params, group_size=_GROUP_SIZE, precision=_PRECISION)
+ q_params = _quantize_params(eval_params, precision=_PRECISION)
mat_vl_fns = {}
if _MAT_FACTORS:
_apply_fn = _unreplicate(state).apply_fn
@@ -680,8 +606,6 @@ def train(args):
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))
- near_zero = sum(int(np.sum(np.abs(x) < 1e-6)) for x in jax.tree.leaves(params_np))
- sparsity = near_zero / total_params * 100
ckpt_name = f"{experiment_name}_{args.num_layers}_{args.d_model}_{global_step}.pkl"
ckpt_path = os.path.join(args.checkpoint_dir, ckpt_name)
@@ -690,7 +614,7 @@ def train(args):
del params_np
# ── All hosts: distributed generation eval ──
- from .run import generate_batch
+ from ..model.run import generate_batch
import json as _json_mod
_pool_names = ["single", "multi"]
@@ -762,7 +686,7 @@ def train(args):
# Prepare generation model (all hosts)
if _MAT_FACTORS:
- from .export import slice_params
+ 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)
@@ -773,7 +697,7 @@ def train(args):
_gen_model = eval_model
_gen_label = "full"
- _mat_params = _quantize_params(_mat_params, group_size=_GROUP_SIZE, precision=_PRECISION)
+ _mat_params = _quantize_params(_mat_params, precision=_PRECISION)
_gen_label += f" {_PRECISION.upper()}"
# Split eval examples across hosts — each host generates its slice
@@ -1027,7 +951,7 @@ def train(args):
print(f" ** New best single call_f1={best_call_f1:.1%} → {best_ckpt_path}")
_upload_checkpoint(best_ckpt_path)
if _MAT_FACTORS:
- from .export import export_submodel
+ from ..model.export import export_submodel
for factor in _MAT_FACTORS:
d_ff_sub = config.d_ff // factor
mat_ckpt_path = os.path.join(
@@ -1039,7 +963,7 @@ def train(args):
retrieval_metrics = None
if has_contrastive and _CONTRASTIVE_WEIGHT > 0 and val_ds is not None:
- from .eval import benchmark_retrieval
+ from ..training.eval import benchmark_retrieval
retrieval_metrics = benchmark_retrieval(
eval_model, eval_params, tokenizer,
num_samples=min(500, getattr(args, "max_eval_samples", 500)),
@@ -1053,8 +977,7 @@ def train(args):
print(f" ─────────────────────────────────────")
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()} g{_GROUP_SIZE})")
- print(f" Sparsity {sparsity:>11.2f}% ({near_zero:,}/{total_params:,})")
+ print(f" Quant val ppl {quant_val_ppl:>12.2f} ({_PRECISION.upper()})")
if mat_results:
print(f" ─────────────────────────────────────")
print(f" Matryoshka sub-models:")
@@ -1136,7 +1059,6 @@ def train(args):
"epoch/text_loss": final_loss,
"epoch/text_val_ppl": last_val_ppl,
"epoch/quant_val_ppl": quant_val_ppl,
- "epoch/weight_sparsity": sparsity,
"epoch": epoch + 1,
}
for factor, (mat_ppl, mat_params, _) in mat_results.items():
diff --git a/src/ui/README.md b/src/ui/README.md
deleted file mode 100644
index 92601ff..0000000
--- a/src/ui/README.md
+++ /dev/null
@@ -1,77 +0,0 @@
-# Finetuning UI
-
-A local web interface for finetuning needle on your own tools.
-
-## Quick Start
-
-```bash
-needle ui --checkpoint <path/to/checkpoint.pkl>
-```
-
-Opens at `http://127.0.0.1:7860`. Use `--port` and `--host` to change.
-
-## What It Does
-
-1. **Load a base model** -- upload or specify a `.pkl` checkpoint
-2. **Define your tools** -- paste your tool definitions as JSON
-3. **Provide a Gemini API key** -- used to synthesize training data
-4. **Click finetune** -- the UI handles everything:
- - Generates ~120 examples per tool via Gemini
- - Validates the data (checks format, deduplication, per-tool coverage)
- - Evaluates the base model on a held-out test set
- - Trains for 3 epochs
- - Evaluates the finetuned model on the same test set
- - Bundles the result into a downloadable `.zip`
-
-## Tool Format
-
-```json
-[
- {
- "name": "get_weather",
- "description": "Get current weather for a city",
- "parameters": {
- "type": "object",
- "properties": {
- "city": { "type": "string", "description": "City name" }
- },
- "required": ["city"]
- }
- }
-]
-```
-
-## Download Bundle
-
-After finetuning completes, download a `.zip` containing:
-
-| File | Description |
-|------|-------------|
-| `checkpoint.pkl` | Finetuned model weights |
-| `tools.json` | Tool definitions used |
-| `train.jsonl` | Training split |
-| `val.jsonl` | Validation split (used for checkpoint selection) |
-| `test.jsonl` | Test split (held out, used for eval) |
-| `eval_report.json` | Base vs. finetuned metrics |
-| `README.md` | Summary with eval table |
-
-## CLI Alternative
-
-You can also finetune without the UI:
-
-```bash
-python -m src.finetune data.jsonl \
- --checkpoint <path/to/checkpoint.pkl> \
- --epochs 3 \
- --batch-size 32 \
- --max-enc-len 1024 \
- --max-dec-len 512
-```
-
-The JSONL file should have one example per line with `query`, `tools`, and `answers` fields.
-
-## Notes
-
-- All endpoints (finetune, upload, download) are localhost-only
-- Training times out after 2 hours
-- The base model stays loaded for interactive testing via the generate tab
diff --git a/src/ui/server.py b/src/ui/server.py
index 0680a88..726e3f1 100644
--- a/src/ui/server.py
+++ b/src/ui/server.py
@@ -263,7 +263,7 @@ _datagen_lock = threading.Lock()
def _generate_custom_data(tools_json, api_key, num_samples, data_file):
import json
- from .. import generate_data as gd
+ from ..dataset import generate as gd
tools = json.loads(tools_json)
@@ -431,7 +431,7 @@ class _Handler(BaseHTTPRequestHandler):
def _run_generate(query, tools, seed, max_gen_len, constrained):
- from ..run import generate
+ from ..model.run import generate
with _lock:
if _model is None or _params is None or _tokenizer is None:
@@ -456,9 +456,9 @@ def _run_generate(query, tools, seed, max_gen_len, constrained):
def _load_checkpoint(path, display_name=None):
global _model, _params, _tokenizer, _current_model, _current_model_path
- from ..data import get_tokenizer
- from ..model import EncoderDecoderTransformer
- from ..run import load_checkpoint
+ from ..dataset.dataset import get_tokenizer
+ from ..model.architecture import EncoderDecoderTransformer
+ from ..model.run import load_checkpoint
with _lock:
_params, config = load_checkpoint(path)
@@ -518,7 +518,7 @@ def _validate_training_data(data_file_path):
_SAMPLES_PER_TOOL = 120 # 100 train + 10 val + 10 test
-_EPOCHS = 3
+_EPOCHS = 1
def _start_finetune(tools_json, api_key):
@@ -586,7 +586,7 @@ def _start_finetune(tools_json, api_key):
proc = subprocess.Popen(
[
python, "-u",
- "-m", "src.finetune",
+ "-m", "src.training.finetune",
str(data_file),
"--epochs", str(_EPOCHS),
"--batch-size", str(batch_size),
@@ -648,7 +648,7 @@ def _start_finetune(tools_json, api_key):
# Assemble download bundle (same per-tool split as finetune)
import zipfile
- from ..finetune import _per_tool_split
+ from ..training.finetune import _per_tool_split
with open(data_file) as _df:
all_examples = [_json.loads(ln) for ln in _df if ln.strip()]
@@ -733,18 +733,46 @@ def _start_finetune(tools_json, api_key):
return True
+_HF_MODEL_REPO = "Cactus-Compute/needle"
+_HF_MODEL_FILE = "needle.pkl"
+
+
+def _resolve_checkpoint(checkpoint_arg):
+ """Resolve checkpoint path: download from HuggingFace if not provided or not local."""
+ if checkpoint_arg and os.path.exists(checkpoint_arg):
+ return checkpoint_arg
+ from huggingface_hub import hf_hub_download
+ local_dir = "checkpoints"
+ os.makedirs(local_dir, exist_ok=True)
+ filename = os.path.basename(checkpoint_arg) if checkpoint_arg else _HF_MODEL_FILE
+ repo = _HF_MODEL_REPO
+ local_path = os.path.join(local_dir, filename)
+ if os.path.exists(local_path):
+ return local_path
+ print(f"Downloading {filename} from {repo}...", file=sys.stderr)
+ path = hf_hub_download(
+ repo_id=repo,
+ filename=filename,
+ repo_type="model",
+ local_dir=local_dir,
+ )
+ print(f"Downloaded to {path}", file=sys.stderr)
+ return path
+
+
def main(args):
global _model, _params, _tokenizer, _current_model, _current_model_path
- from ..data import get_tokenizer
- from ..model import EncoderDecoderTransformer
- from ..run import load_checkpoint
+ from ..dataset.dataset import get_tokenizer
+ from ..model.architecture import EncoderDecoderTransformer
+ from ..model.run import load_checkpoint
- print(f"Loading checkpoint: {args.checkpoint}", file=sys.stderr)
- _params, config = load_checkpoint(args.checkpoint)
+ checkpoint_path = _resolve_checkpoint(args.checkpoint)
+ print(f"Loading checkpoint: {checkpoint_path}", file=sys.stderr)
+ _params, config = load_checkpoint(checkpoint_path)
_model = EncoderDecoderTransformer(config)
_tokenizer = get_tokenizer()
- _current_model = Path(args.checkpoint).name
- _current_model_path = args.checkpoint
+ _current_model = Path(checkpoint_path).name
+ _current_model_path = checkpoint_path
param_count = sum(x.size for x in __import__("jax").tree.leaves(_params))
print(f"Model parameters: {param_count:,}", file=sys.stderr)
diff --git a/src/utils/__init__.py b/src/utils/__init__.py
new file mode 100644
index 0000000..031bbde
--- /dev/null
+++ b/src/utils/__init__.py
@@ -0,0 +1,4 @@
+from .distributed import ( # noqa: F401
+ _replicate, _unreplicate, shard_batch, _upload_checkpoint,
+ load_pretrained_params, partial_load_params,
+)
diff --git a/src/distributed.py b/src/utils/distributed.py
similarity index 100%
rename from src/distributed.py
rename to src/utils/distributed.py
diff --git a/src/gcs.py b/src/utils/gcs.py
similarity index 100%
rename from src/gcs.py
rename to src/utils/gcs.py
diff --git a/src/tpu.py b/src/utils/tpu.py
similarity index 100%
rename from src/tpu.py
rename to src/utils/tpu.py