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.
bugfixes
HenryNdubuaku4f8c297d5c4a
diff --git a/notes/architecture.txt b/notes/architecture.txtindex bda9733..2d2c838 100644--- a/notes/architecture.txt+++ b/notes/architecture.txt@@ -1,57 +1,144 @@-Co-Designed Architecture & Training Recipe for Small-Scale Tool Calling-=======================================================================--## 1. Thesis--No single component is novel in isolation. The contribution is a-co-designed system: an encoder-decoder architecture trained with a-multi-objective recipe (generation + contrastive + Matryoshka +-structured weighting + QAT + pruning) that produces a small model-competitive with much larger decoder-only models on tool calling.--The architecture choices are interdependent:- - We do not need MLPs for tiny models- - Structured loss weighting targets the actual error distribution- - QAT provides regularisation eliminating the need for dropout- - softmax is a nonlinearity, so scaled dot-product attention (softmax(QK^T/√d) · V) is nonlinear.--------Our blocks (with no_feedforward=True) are essentially:-- # encoder:- x = x + Attention(Norm(x))-- # decoder:- x = x + SelfAttn(Norm(x))- x = x + CrossAttn(Norm(x))--The residual connection is the only pathway preserving information between layers.-Without FFN, there's no nonlinear feature transformation, each layer just incrementally mixes information via attention and adds it back.--The argument for Kimi-style residual bypass here would be: if you remove the residual, each attention layer gets to fully rewrite the representation rather than just adding a delta.-In a standard transformer with FFN, the FFN does the heavy "rewriting" work and the attention residual is fine as an additive refinement.-But in our attention-only setup, forcing attention into an additive role may be limiting, it can only nudge the representation, never reshape it.-Without FFN and without residuals, we lose the gradient highway entirely. Deep networks would struggle to train.-Kimi's technique likely works in models that still have FFN layers (or some other nonlinearity) providing an alternate signal path.--With the gated residual, each line becomes:-- # gated residual — each sublayer gate is a learnable scalar, initialized to 0- # sigmoid(0) = 0.5, so training starts as half-strength standard residual- # gate → 1 recovers the standard residual exactly-- # encoder (per layer)- g = sigmoid(gate)- x = x + g * Attention(Norm(x))-- # decoder (per layer)+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.+- x = x + g_s * SelfAttn(Norm(x))- x = x + g_c * CrossAttn(Norm(x))+## 8. Ablations (maps to main.txt 4.4)-The full residual is always preserved. The gate only scales the sublayer contribution.-At init (gate=0, g=0.5): half-strength sublayer addition.-gate → 1 (g=1): standard residual. gate → -inf (g=0): identity, sublayer ignored.\ No newline at end of file+ 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.txtnew file mode 100644index 0000000..701193b--- /dev/null+++ b/notes/cloud-fallback.txt@@ -0,0 +1,122 @@+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.txtindex e69de29..20a1d5f 100644--- a/notes/dataset.txt+++ b/notes/dataset.txt@@ -0,0 +1,133 @@+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.txtnew file mode 100644index 0000000..32849de--- /dev/null+++ b/notes/main.txt@@ -0,0 +1,380 @@+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/tool-selection.txt b/notes/tool-selection.txtindex 2b7dc3b..409fe65 100644--- a/notes/tool-selection.txt+++ b/notes/tool-selection.txt@@ -1,327 +1,116 @@-Contrastive Tool Selection via Shared Encoder-==============================================+Tool Selection: Contrastive Filtering and Constrained Decoding+==============================================================-## 1. Problem--Tool-calling models receive a set of tool definitions in-context and must-select the right tool(s) for a given query. Two challenges:-- (a) Context window pressure: with 1024 encoder tokens, fitting many- tool definitions alongside the query is tight. Real APIs can have- 50-200 endpoints — they simply don't fit.-- (b) Selection from large catalogs: even if tools fit, the model must- discriminate between semantically similar tools (e.g.,- search_flights vs search_hotels vs search_restaurants). This is a- retrieval problem, not a generation problem.-- (C) The model generates JSON tool calls autoregressively. While it learns- JSON structure well (99-100% parse rate), it can still hallucinate- invalid function names or argument keys. The valid tool definitions are- already in the encoder input — we can constrain the decoder to only- produce valid names/keys at inference time.--The standard approach is a separate retrieval model (e.g., embedding API)-to pre-filter tools before passing them to the generator. This adds a-second model, a second inference pass, and a mismatch between the-representations used for retrieval and generation.--## 2. Key Insight: Shared Encoder, Dual Use--Our encoder already processes both queries and tool definitions during-generation (encoder input = [query | <tools> | tools...]). The same-encoder representations that attend to tools during generation can be-repurposed for retrieval by adding a lightweight contrastive head.--Architecture:-- ┌─────────────┐ ┌─────────────┐- │ "What is │ │ {"name": │- │ the weather│ │ "get_weather│- │ in SF?" │ │ "params": │- │ │ │ {"location"│- └──────┬──────┘ │ : "string"}│- │ │ } │- ▼ └──────┬──────┘- ┌──────────────┐ │- │ │ │- │ Shared │◄──────────┘- │ Encoder │- │ (8 layers) │- │ │- └──────┬───────┘- │- ┌────┴────┐- │ │- ▼ ▼- ┌─────┐ ┌─────────┐- │Mean │ │Contras- │- │Pool │ │tive │- │ │ │Proj │- └──┬──┘ │(d→128) │- │ └────┬────┘- │ │- ▼ ▼- (d_model) (128-d, L2-normalized)- │ │- ▼ ▼- Cross- Cosine similarity- attention for retrieval- in decoder--The contrastive projection head is a single linear layer (d_model → 128)-followed by L2 normalization. It's trained with CLIP-style symmetric-cross-entropy loss: in each batch, the B queries are paired with B-positive tools, and the B²-B in-batch negatives provide contrastive signal.--This means:- - No separate retrieval model — same encoder, same parameters- - Retrieval representations are grounded in the same space used for- generation — what the encoder learns for cross-attention also helps- distinguish tools- - The contrastive head adds <0.01% parameters (one 512×128 matrix)---## 3. Training Details--CLIP-style loss with learnable temperature:-- loss = 0.5 * (CE(q·t^T/τ, labels) + CE(t·q^T/τ, labels))-- - q, t ∈ R^{B×128}, L2-normalized- - τ = exp(log_temp), clamped to [1/100, 100]- - labels = arange(B) (diagonal is positive)- - In-batch negatives: B-1 negatives per query, free--Training schedule:- - Contrastive loss weighted at 0.1× text loss- - Computed every 100 steps (not every step — saves compute, contrastive- signal is less noisy so doesn't need per-step updates)- - Uses the same encoder parameters as text generation (shared, not frozen)--Data construction:- - Each training example has a query, a list of tools, and the answer- (which tools were called)- - For contrastive training: extract (query, positive_tool) pairs where- positive_tool is any tool that was actually called- - Each query may have multiple positives; one is randomly sampled per batch- - Individual tools are tokenized separately (max 256 tokens each)---## 4. Inference Pipeline--Two-stage inference for large catalogs:-- Stage 1 — Retrieval:- encode_contrastive(query) → q_emb (128-d)- encode_contrastive(tools) → t_embs (N×128)- scores = q_emb @ t_embs.T- top_k = argsort(-scores)[:k]-- Stage 2 — Generation:- encoder_input = [query | <tools> | top_k_tools]- decoder generates tool calls with only the selected tools in context--This naturally handles the context window constraint: even with 200-available tools, we retrieve top-5 and fit them easily in 1024 tokens.-The retrieval and generation use the same encoder weights, so what the-retrieval stage selects is precisely what the generation stage can-attend to effectively.--For small catalogs (≤5 tools): skip retrieval, pass all tools directly.-The contrastive head is never used at inference in this case — it was-only useful as a training regularizer (the shared representations-benefit generation even without explicit retrieval).---## 5. Why This Design--### vs. Separate retrieval model (e.g., embed API + generator)- - One model instead of two → simpler deployment, less memory- - Shared representations → retrieval is aligned with generation- - No train/inference distribution shift between retriever and generator--### vs. Stuffing all tools in context- - Doesn't scale: 50 tools × ~50 tokens each = 2500 tokens, exceeds- 1024 encoder context- - Even if they fit, attention over many irrelevant tools dilutes signal- - Retrieval pre-filtering gives the generator a clean, focused context--### vs. Fine-tuning a separate contrastive model- - The encoder is already "seeing" tools during generation training- - Adding a projection head extracts what it already knows- - Multi-task learning: contrastive loss acts as regularizer for the- encoder, improving generation even on in-context tools--### The regularization effect- Even when retrieval isn't used at inference (small catalogs), the- contrastive objective during training forces the encoder to build- discriminative representations of tools. This helps cross-attention- in the decoder: the encoder outputs for each tool are more distinct,- making it easier for the decoder to attend to the right tool.---## 6. Experiment Design--### Exp 1: Retrieval Quality [MUST-HAVE]--Setup:- - Validation set, each example has query + tools + ground truth calls- - Encode query and all tools from that example contrastively- - Rank tools by cosine similarity, check if positive tools are in top-k--Metrics:- | k | Recall@k |- |-----|----------|- | 1 | |- | 3 | |- | 5 | |- | 10 | |+Supports main.txt sections 2.3, 2.5.+Two mechanisms that narrow the output space: filtering tools before+generation, constraining tokens during generation.- Also report MRR (mean reciprocal rank of first positive).-Stratify by:- - Number of tools per example (harder with more tools)- - Number of positive tools (multi-call examples)--What this shows:- - The shared encoder produces discriminative tool representations- - Recall@5 should be very high (>95%) — retrieval is nearly solved---### Exp 2: Ablation — Generation Quality With vs Without Contrastive [MUST-HAVE]--Setup:- - Train two models: with contrastive loss (λ=0.1) and without (λ=0)- - Same architecture, same data, same hyperparameters otherwise- - Evaluate generation metrics on val set (no retrieval at inference)+## 1. Problem-Metrics:- | Condition | name_f1 | call_f1 | exact_match | value_acc |+ (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.-Hypothesis:- - Even without using retrieval at inference, the contrastive-trained- model should have better name_f1 and call_f1- - The regularization effect: contrastive loss forces discriminative- encoder representations → better cross-attention → better generation-What this shows:- - Contrastive learning isn't just for retrieval — it improves generation- - This is the key insight: one objective helps two tasks+## 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.-### Exp 3: Retrieve-then-Generate vs Full Context [MUST-HAVE]+ encoder -> mean_pool -> Dense(d_model/4) -> ReLU -> Dense(128) -> L2-norm-Setup:- - Create synthetic scenarios with large tool catalogs (20, 50, 100 tools)- by combining tools from multiple validation examples- - Three conditions:- (a) All tools in context (may truncate)- (b) Top-5 retrieved tools in context- (c) Oracle top-5 (ground truth positive tools + random negatives)+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.-Metrics:- | Condition | 20 tools | 50 tools | 100 tools |- | | name_f1 call_f1| name_f1 call_f1| name_f1 call_f1|- |----------------|---------------|---------------|---------------|- | All in context | | | |- | Retrieved top-5| | | |- | Oracle top-5 | | | |+ - 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-Hypothesis:- - With 20 tools: "all in context" works but retrieved is comparable- - With 50+ tools: "all in context" degrades (truncation, attention dilution)- - Retrieved top-5 stays close to oracle → retrieval solves the scaling problem-What this shows:- - Retrieval is necessary for real-world tool catalogs- - The gap between retrieved and oracle quantifies retrieval errors- - The gap between all-context and retrieved quantifies context pressure+## 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.-### Exp 4: Contrastive Loss Weight Sweep [STRONG]+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.-Setup:- - Train models with λ ∈ {0, 0.01, 0.05, 0.1, 0.2, 0.5}- - Evaluate both retrieval (Recall@k) and generation (call_f1)+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).-Metrics (line plot, x=λ):- - Recall@5 (retrieval quality)- - call_f1 (generation quality)-Hypothesis:- - λ=0: no retrieval capability, generation baseline- - λ=0.01-0.1: retrieval improves rapidly, generation also improves- - λ>0.2: retrieval saturates, generation may degrade (contrastive- objective starts dominating, encoder optimizes for discrimination- over representation)+## 4. Constrained Decoding-What this shows:- - Sweet spot exists where both tasks benefit- - Justifies λ=0.1 as default+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-### Exp 5: Embedding Space Visualization [STRONG]+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.-Setup:- - Encode 500 queries and their associated tools- - Project to 2D via t-SNE or UMAP- - Color by: tool category / query intent / positive vs negative+Guarantees syntactically valid output with zero accuracy cost.-Presentation:- - Scatter plot showing query-tool alignment- - Highlight clusters where similar tools group together- - Show queries landing near their positive tools-What this shows:- - Visual evidence that the shared space is semantically meaningful- - Queries and their positive tools are close; negatives are far- - Tool clusters correspond to functional categories+## 5. The Funnel+Filtering and constrained decoding are complementary stages:-### Exp 6: Retrieval Latency [STRONG]+ 200 tools -> contrastive filter top-5 -> encode 5 tools+ -> constrain to 5 names -> constrain to valid params per name+ -> free-form values-Setup:- - Measure time to encode and retrieve from catalogs of varying size- - Compare: our model's encode_contrastive vs. a separate embedding API+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.-Metrics:- | Catalog size | Encode time | Retrieval time | Total |-What this shows:- - Retrieval adds negligible latency (single encoder pass + matmul)- - Amortization: tool embeddings can be precomputed and cached- - No network round-trip to a separate embedding service+## 6. vs. Alternatives+ vs. Separate retrieval model:+ One model, shared representations, no distribution shift.-### Exp 7: Contrastive Frequency Ablation [NICE-TO-HAVE]+ 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.-Setup:- - Vary how often contrastive loss is computed: every step, every 10,- every 100 (current), every 500- - Same total training budget-Metrics:- - Recall@5 convergence curve- - Final call_f1+## 7. Ablations (maps to main.txt 4.4-4.5)-What this shows:- - Contrastive signal is low-noise, doesn't need per-step updates- - Every-100 is sufficient (saves ~50% of contrastive compute)- - Justifies the design choice+ 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.-### Priority+ 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.-Must-have (core claims):- 1. Retrieval quality (Exp 1) — proves it works- 2. Ablation: with/without contrastive (Exp 2) — proves dual benefit- 3. Retrieve-then-generate scaling (Exp 3) — proves necessity+ D. Constrained vs Unconstrained Decoding [MUST-HAVE]+ Unconstrained vs name-only vs full constraint.-Strong additions:- 4. Loss weight sweep (Exp 4) — justifies hyperparameter- 5. Embedding visualization (Exp 5) — intuition and visual appeal- 6. Retrieval latency (Exp 6) — practical deployment story+ E. Linear vs MLP Head [STRONG]+ Tests whether head nonlinearity matters more for attention-only+ encoder.-Nice-to-have:- 7. Contrastive frequency ablation (Exp 7) — training efficiency+ F. Contrastive Weight Sweep [STRONG]+ lambda in {0, 0.01, 0.05, 0.1, 0.2, 0.5}.diff --git a/src/cli.py b/src/cli.pyindex 9f60261..d9a866f 100644--- a/src/cli.py+++ b/src/cli.py@@ -122,6 +122,8 @@ def main():p.add_argument("--dry-run", action="store_true", help="Preview without modifying")p = sub.add_parser("split-dataset", add_help=False)+ p.add_argument("--val-per-source", type=int, default=None,+ help="Validation samples per source (default: 2500)")p = sub.add_parser("evaluate", add_help=False)p.add_argument("--checkpoint", type=str, required=True)diff --git a/src/split_dataset.py b/src/split_dataset.pyindex dc0d184..40235a5 100644--- a/src/split_dataset.py+++ b/src/split_dataset.py@@ -16,28 +16,53 @@ from datasets import load_datasetHF_DATASET_REPO = "Cactus-Compute/tool-calls"-VAL_SIZE = 10000+VAL_PER_SOURCE = 2500SEED = 42def main(args=None):+ val_per_source = VAL_PER_SOURCE+ if args is not None and getattr(args, "val_per_source", None) is not None:+ val_per_source = args.val_per_source+print(f"Downloading full dataset from {HF_DATASET_REPO}...")- ds = load_dataset(HF_DATASET_REPO, split="train", token=True)+ ds = load_dataset(HF_DATASET_REPO, split="train", token=True,+ download_mode="force_redownload",+ verification_mode="no_checks")n = len(ds)print(f"Total rows: {n:,}")- # Shuffle with fixed seed so validation is representative of all sources- ds = ds.shuffle(seed=SEED)+ # Stratified split: equal samples per source for balanced validation+ from collections import Counter+ source_counts = Counter(ds["source"])+ print(f"\nSource distribution:")+ for src, cnt in source_counts.most_common():+ print(f" {src}: {cnt:,}")++ # Group indices by source+ source_indices = {}+ for i, src in enumerate(ds["source"]):+ source_indices.setdefault(src, []).append(i)++ import random+ rng = random.Random(SEED)- val_size = min(VAL_SIZE, int(n * 0.1))- train_ds = ds.select(range(n - val_size))- val_ds = ds.select(range(n - val_size, n))+ val_indices = []+ for src, indices in sorted(source_indices.items()):+ rng.shuffle(indices)+ take = min(val_per_source, len(indices))+ val_indices.extend(indices[:take])+ print(f" {src}: taking {take} for validation")- print(f"Train: {len(train_ds):,} rows")+ val_set = set(val_indices)+ train_indices = [i for i in range(n) if i not in val_set]++ train_ds = ds.select(train_indices)+ val_ds = ds.select(val_indices)++ print(f"\nTrain: {len(train_ds):,} rows")print(f"Validation: {len(val_ds):,} rows")- # Show source distribution in validation- from collections import Counterval_sources = Counter(val_ds["source"])print(f"\nValidation source distribution:")for src, cnt in val_sources.most_common():diff --git a/src/tokenize_data.py b/src/tokenize_data.pyindex 2e014e6..d50ede7 100644--- a/src/tokenize_data.py+++ b/src/tokenize_data.py@@ -75,7 +75,8 @@ def _download_synth_dataset():print("Downloading dataset from HuggingFace (Cactus-Compute/tool-calls)...")for split in ("train", "validation"):try:- ds = load_dataset("Cactus-Compute/tool-calls", split=split, token=True)+ ds = load_dataset("Cactus-Compute/tool-calls", split=split, token=True,+ verification_mode="no_checks")except Exception as e:raise FileNotFoundError(f"Dataset split '{split}' not found on HuggingFace (Cactus-Compute/tool-calls): {e}\n"