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.
fixes
jakmro0459cabe4671
diff --git a/README.md b/README.mdindex e638d91..00288c7 100644--- a/README.md+++ b/README.md@@ -327,6 +327,10 @@ needle [command]└────────────────────┴──────────┴──────────┴──────────┘```+## 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.diff --git a/src/constrained.py b/src/constrained.pyindex e650f7a..2e2f1cd 100644--- a/src/constrained.py+++ b/src/constrained.py@@ -3,17 +3,25 @@Constrains the decoder to only produce valid tool names and argument keysby tracking position in the output JSON and masking invalid tokens via acharacter-level trie built from the tool definitions.++Needle output format (compact JSON, no spaces):+ [{"name":"tool_name","arguments":{"key1":value1,"key2":value2}}]++Constrained regions:+ - Tool names after "name":" are constrained to known tool names+ - Argument keys after "arguments":{ are constrained to known param names+ - Argument values are unconstrained (strings, numbers, booleans, objects)"""import jsonimport logging-import warningsfrom enum import Enum, autoimport numpy as nplogger = logging.getLogger(__name__)+class TrieNode:__slots__ = ("children", "is_terminal")@@ -57,12 +65,17 @@ class Trie:_dfs(self.root, [])return result+class ToolConstraints:- """Holds one name trie and one param trie per function, built from tool JSON."""+ """Holds one name trie and one param trie per function, built from tool JSON.++ Extracts property names from JSON Schema ``parameters.properties``,+ not from the schema-level keys (``type``, ``properties``, ``required``).+ """def __init__(self, tools_json: str):self.name_trie = Trie()- self.param_tries: dict[str, Trie] = {}+ self.param_tries: dict[str, Trie] = {}try:tools = json.loads(tools_json)@@ -83,8 +96,10 @@ class ToolConstraints:params = tool.get("parameters", {})if isinstance(params, dict):param_trie = Trie()- for key in params:- param_trie.insert(key)+ props = params.get("properties")+ if isinstance(props, dict):+ for key in props:+ param_trie.insert(key)self.param_tries[name] = param_triedef get_param_trie(self, function_name: str) -> Trie | None:@@ -98,24 +113,29 @@ class JsonState(Enum):class JsonStateMachine:- """Tracks position in output JSON to know when to constrain decoding.+ """Tracks position in needle's compact JSON output to constrain decoding.++ Needle format: ``[{"name":"TOOL","arguments":{"key":val,...}},...]``- Transitions:- - ``"name":"`` suffix → IN_NAME- - ``"arguments":{`` suffix → sets in_arguments; then ``{"`` or ``,"``- at nesting depth 0 → IN_ARG_KEY- - Closing ``"`` while in constrained state → FREE+ Constrained spans:+ - After ``"name":"`` → IN_NAME (constrains to valid tool names)+ - After ``"arguments":{"`` or ``,"`` at arguments depth → IN_ARG_KEY+ (constrains to valid parameter names for the current tool)+ - Closing ``"`` in constrained state → FREE++ Depth tracking ensures nested objects/arrays in argument VALUES+ do not trigger false IN_ARG_KEY transitions."""def __init__(self):self.state = JsonState.FREE- self.buffer = ""- self.constrained_buf = ""- self.current_function = ""+ self.buffer = ""+ self.constrained_buf = ""+ self.current_function = ""self.in_arguments = False- self.arguments_depth = 0 # nesting depth of the arguments {+ self.arguments_depth = 0self.nesting_depth = 0- self.in_string_value = False+ self.in_string = Falseself.prev_char_escape = Falsedef feed(self, text: str):@@ -137,7 +157,7 @@ class JsonStateMachine:self.buffer += ch- if self.in_string_value:+ if self.in_string:if self.prev_char_escape:self.prev_char_escape = Falsereturn@@ -145,7 +165,7 @@ class JsonStateMachine:self.prev_char_escape = Truereturnif ch == '"':- self.in_string_value = False+ self.in_string = Falsereturnif ch in '{[':@@ -154,36 +174,36 @@ class JsonStateMachine:self.nesting_depth = max(0, self.nesting_depth - 1)if ch == '}' and self.in_arguments and self.nesting_depth < self.arguments_depth:self.in_arguments = False+ return- if self.buffer.endswith('"name":"'):+ if self.buffer.endswith('"name":"') and not self.in_arguments:self.state = JsonState.IN_NAMEself.constrained_buf = ""returnif self.buffer.endswith('"arguments":{'):self.in_arguments = True- self.arguments_depth = self.nesting_depth # depth of the arguments { itself+ self.arguments_depth = self.nesting_depthreturn- if self.in_arguments and self._at_arg_key_start():+ if (self.in_arguments+ and self.nesting_depth == self.arguments_depth+ and self._at_arg_key_start()):self.state = JsonState.IN_ARG_KEYself.constrained_buf = ""return- if ch == '"' and self._is_value_string_start():- self.in_string_value = True+ if ch == '"' and self._is_value_quote():+ self.in_string = Truedef _at_arg_key_start(self) -> bool:- """Check if buffer ends with ``{"`` or ``,"`` while in arguments."""+ """True if buffer ends with ``{"`` or ``,"`` — an arg key is opening."""if len(self.buffer) < 2:return Falsereturn self.buffer[-2:] in ('{"', ',"')- def _is_value_string_start(self) -> bool:- """Check if the current ``"`` opens a JSON string value (preceded by ``:``).-- Keys open after ``{`` or ``,``; values open after ``:``.- """+ def _is_value_quote(self) -> bool:+ """True if the current ``"`` opens a JSON string value (preceded by ``:``)."""for j in range(len(self.buffer) - 2, -1, -1):c = self.buffer[j]if c in ' \t\n\r':@@ -193,10 +213,13 @@ class JsonStateMachine:def build_token_strings(tokenizer) -> list[str]:- """Map each vocab ID to its decoded text.+ """Map each vocab ID to the exact characters it contributes to output.- Handles SentencePiece control tokens (IDs 0..N that decode to empty)- and byte-fallback pieces.+ SentencePiece uses ``▁`` (U+2581) as a word-boundary marker that becomes+ a space in decoded text. We convert ``▁`` → ``' '`` so that both the+ state machine and the trie matcher see consistent text. This correctly+ blocks ``▁``-prefixed tokens inside constrained spans (tool names and+ argument keys never contain spaces in needle's compact JSON format)."""vocab_size = tokenizer.vocab_sizesp = tokenizer.sp@@ -207,7 +230,6 @@ def build_token_strings(tokenizer) -> list[str]:elif sp.IsUnknown(i):strings.append("")elif sp.IsByte(i):- # Byte-fallback piece like <0x41>piece = sp.IdToPiece(i)try:byte_val = int(piece[1:-1], 16) if piece.startswith("<0x") else ord(piece)@@ -215,14 +237,13 @@ def build_token_strings(tokenizer) -> list[str]:except (ValueError, IndexError):strings.append("")else:- # Normal BPE piece — decode via SentencePiece- text = sp.Decode([i])- strings.append(text)+ piece = sp.IdToPiece(i)+ strings.append(piece.replace("\u2581", " "))return stringsclass TokenIndex:- """Maps first character → list of token IDs for fast candidate filtering."""+ """Maps first character -> list of token IDs for fast candidate filtering."""def __init__(self, token_strings: list[str]):self._index: dict[str, list[int]] = {}@@ -251,6 +272,8 @@ def _check_token_valid(token_text: str, trie_node: TrieNode) -> bool:The token text may contain a closing ``"`` which signals end of theconstrained span — at that point the trie node must be terminal.+ Characters after the closing ``"`` are not checked (they are structural+ JSON that the state machine handles separately)."""node = trie_nodefor i, ch in enumerate(token_text):@@ -259,7 +282,7 @@ def _check_token_valid(token_text: str, trie_node: TrieNode) -> bool:if ch not in node.children:return Falsenode = node.children[ch]- return True+ return Truedef apply_constraints(@@ -309,10 +332,17 @@ class ConstrainedDecoder:Holds per-example ``JsonStateMachine`` instances and shared tokenmetadata. Call ``constrain_logits`` between logit computation andargmax, then ``update`` after selecting the token.++ Both ``constrain_logits`` and ``update`` use the same ``token_strings``+ table (with ``▁`` → space) so the state machine and trie matcher see+ identical text. This correctly blocks ``▁``-prefixed tokens inside+ constrained spans, since spaces are never valid in tool names or+ argument keys."""def __init__(self, tool_constraints_list: list[ToolConstraints],- token_strings: list[str], token_index: TokenIndex):+ token_strings: list[str], token_index: TokenIndex,+ tokenizer=None):self.batch_size = len(tool_constraints_list)self.tool_constraints = tool_constraints_listself.machines = [JsonStateMachine() for _ in range(self.batch_size)]@@ -324,15 +354,7 @@ class ConstrainedDecoder:return self.machines[batch_idx].state != JsonState.FREEdef constrain_logits(self, logits: np.ndarray, batch_idx: int) -> np.ndarray:- """Apply grammar constraints to logits for a single batch element.-- Args:- logits: shape (vocab_size,) numpy array- batch_idx: index into the batch-- Returns:- Possibly-masked logits (same shape).- """+ """Apply grammar constraints to logits for a single batch element."""machine = self.machines[batch_idx]tc = self.tool_constraints[batch_idx]@@ -344,7 +366,7 @@ class ConstrainedDecoder:elif machine.state == JsonState.IN_ARG_KEY:trie = tc.get_param_trie(machine.current_function)if trie is None:- return logits+ return logitselse:return logitsdiff --git a/src/finetune.py b/src/finetune.pyindex 6b111b9..77c7498 100644--- a/src/finetune.py+++ b/src/finetune.py@@ -223,8 +223,8 @@ def finetune_local(args):raise ValueError("finetune requires at least 3 examples for train/val/test splits")from .tokenizer import DEFAULT_MAX_ENC_LEN, DEFAULT_MAX_DEC_LEN- max_enc_len = DEFAULT_MAX_ENC_LEN- max_dec_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_owns_cache = args.cache_dir is Nonecache_dir = args.cache_dir or tempfile.mkdtemp(prefix="needle-finetune-cache-")@@ -232,19 +232,18 @@ def finetune_local(args):train_examples, val_examples, test_examples = _per_tool_split(examples)- # If not enough data for 3-way split, merge test into val- if len(train_examples) == 0 and len(test_examples) > 0:- val_examples = val_examples + test_examples- test_examples = list(val_examples) # test = val (same data)- train_remaining = []- # Steal half of val for train- for i in range(0, len(val_examples), 2):- if i + 1 < len(val_examples):- train_remaining.append(val_examples[i])- if train_remaining:- train_examples = train_remaining- val_examples = [ex for ex in val_examples if ex not in train_remaining]- test_examples = list(val_examples)+ if len(train_examples) == 0:+ all_avail = val_examples + test_examples+ random.Random(42).shuffle(all_avail)+ n = len(all_avail)+ n_test = max(1, n // 5)+ n_val = max(1, n // 5)+ n_train = n - n_val - n_test+ if n_train <= 0:+ raise ValueError(f"Not enough data ({n} examples) for train/val/test splits")+ test_examples = all_avail[:n_test]+ val_examples = all_avail[n_test:n_test + n_val]+ train_examples = all_avail[n_test + n_val:]if len(train_examples) == 0:raise ValueError("Not enough data — need at least 3 examples per tool for train/val/test splits")@@ -275,7 +274,6 @@ def finetune_local(args):from datasets import Dataset as _Datasetval_ds = _Dataset.from_list(val_examples)- test_ds = _Dataset.from_list(test_examples)# Base model eval on TEST set (never seen by model)from .run import load_checkpoint@@ -311,10 +309,10 @@ def finetune_local(args):warmup_ratio=0.05, decay_ratio=0.05, wandb=False,dtype=cfg.get("dtype", "bfloat16"),checkpoint_dir=args.checkpoint_dir, seed=42,- eval_every=max(1, approx_steps), max_eval_samples=min(val_kept, 200),+ 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,- activation=cfg.get("activation", "swiglu"),+ activation=cfg.get("activation", "drelu"),mat_factors=[2, 4], dropout=0.0,contrastive_weight=0.1,contrastive_dim=cfg.get("contrastive_dim", 128),@@ -356,4 +354,6 @@ if __name__ == "__main__":p.add_argument("--checkpoint-dir", type=str, default="checkpoints")p.add_argument("--checkpoint", type=str, required=True)p.add_argument("--cache-dir", type=str, default=None)+ p.add_argument("--max-enc-len", type=int, default=None)+ p.add_argument("--max-dec-len", type=int, default=None)finetune_local(p.parse_args())diff --git a/src/ui/README.md b/src/ui/README.mdnew file mode 100644index 0000000..92601ff--- /dev/null+++ b/src/ui/README.md@@ -0,0 +1,77 @@+# 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