cactus-needle 2.0.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cactus_needle-2.0.0/LICENSE +21 -0
- cactus_needle-2.0.0/MANIFEST.in +3 -0
- cactus_needle-2.0.0/PKG-INFO +289 -0
- cactus_needle-2.0.0/README.md +267 -0
- cactus_needle-2.0.0/cactus_needle.egg-info/PKG-INFO +289 -0
- cactus_needle-2.0.0/cactus_needle.egg-info/SOURCES.txt +38 -0
- cactus_needle-2.0.0/cactus_needle.egg-info/dependency_links.txt +1 -0
- cactus_needle-2.0.0/cactus_needle.egg-info/entry_points.txt +2 -0
- cactus_needle-2.0.0/cactus_needle.egg-info/requires.txt +14 -0
- cactus_needle-2.0.0/cactus_needle.egg-info/top_level.txt +1 -0
- cactus_needle-2.0.0/llms.txt +200 -0
- cactus_needle-2.0.0/needle/__init__.py +124 -0
- cactus_needle-2.0.0/needle/agent/__init__.py +0 -0
- cactus_needle-2.0.0/needle/agent/fetch.py +54 -0
- cactus_needle-2.0.0/needle/agent/tools.py +159 -0
- cactus_needle-2.0.0/needle/cli.py +175 -0
- cactus_needle-2.0.0/needle/model/__init__.py +0 -0
- cactus_needle-2.0.0/needle/model/architecture.py +622 -0
- cactus_needle-2.0.0/needle/model/decode.py +405 -0
- cactus_needle-2.0.0/needle/model/export.py +526 -0
- cactus_needle-2.0.0/needle/model/finetune.py +379 -0
- cactus_needle-2.0.0/needle/model/quantize.py +366 -0
- cactus_needle-2.0.0/needle/model/run.py +226 -0
- cactus_needle-2.0.0/needle/model/tokenizer.model +0 -0
- cactus_needle-2.0.0/needle/model/tokenizer.py +119 -0
- cactus_needle-2.0.0/needle/model/tokenizer.vocab +8192 -0
- cactus_needle-2.0.0/needle/playground/__init__.py +0 -0
- cactus_needle-2.0.0/needle/playground/app.js +331 -0
- cactus_needle-2.0.0/needle/playground/index.html +111 -0
- cactus_needle-2.0.0/needle/playground/server.py +186 -0
- cactus_needle-2.0.0/needle/playground/style.css +513 -0
- cactus_needle-2.0.0/pyproject.toml +38 -0
- cactus_needle-2.0.0/setup.cfg +4 -0
- cactus_needle-2.0.0/tests/test_build.py +59 -0
- cactus_needle-2.0.0/tests/test_finetune.py +70 -0
- cactus_needle-2.0.0/tests/test_generate.py +90 -0
- cactus_needle-2.0.0/tests/test_inference.py +44 -0
- cactus_needle-2.0.0/tests/test_lora.py +56 -0
- cactus_needle-2.0.0/tests/test_render.py +73 -0
- cactus_needle-2.0.0/tests/test_tools.py +109 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Cactus Compute
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: cactus-needle
|
|
3
|
+
Version: 2.0.0
|
|
4
|
+
Summary: A 14MB foundation tool-calling model for tiny devices: inference, LoRA finetuning, and build.
|
|
5
|
+
License: Apache-2.0
|
|
6
|
+
Requires-Python: >=3.9
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Requires-Dist: huggingface_hub
|
|
10
|
+
Requires-Dist: numpy
|
|
11
|
+
Requires-Dist: jax
|
|
12
|
+
Requires-Dist: jaxlib
|
|
13
|
+
Requires-Dist: flax>=0.12.8
|
|
14
|
+
Requires-Dist: optax
|
|
15
|
+
Requires-Dist: sentencepiece
|
|
16
|
+
Provides-Extra: gpu
|
|
17
|
+
Requires-Dist: jax[cuda12]; extra == "gpu"
|
|
18
|
+
Provides-Extra: test
|
|
19
|
+
Requires-Dist: pytest; extra == "test"
|
|
20
|
+
Requires-Dist: pydantic; extra == "test"
|
|
21
|
+
Dynamic: license-file
|
|
22
|
+
|
|
23
|
+

|
|
24
|
+
|
|
25
|
+
# Needle 2
|
|
26
|
+
|
|
27
|
+
Needle 2 is an open 45M-parameter model for tool calling, device use and structured extraction. The whole model is a single 14MB binary that runs a full session in about 28MB of RAM. It is built on our Simple Attention Network findings, compressed to CQ2-bit with Cactus Quants, and baked into its own engine. On the benchmarks below, Needle 2 trades wins with other small models like FunctionGemma 270M, LFM2.5 230M and Apple FM, at 5x to 70x smaller, and 2 bits against their f16.
|
|
28
|
+
|
|
29
|
+
This repository is the Python package: inference, LoRA fine-tuning, and export. `pip install cactus-needle`, describe your tools, and call them from Python. The inference engine is fetched once from Hugging Face and cached; there is nothing else to build.
|
|
30
|
+
|
|
31
|
+
- **Self-contained**: weights baked into a single 14MB engine; no separate model files to manage, and inference does no network.
|
|
32
|
+
- **Simple contract**: tool calls come back as structured data, text in, JSON out; a byte-level grammar compiled from your schemas constrains every token.
|
|
33
|
+
- **Confidence-gated**: every response carries a calibrated confidence score from a learned head; set a threshold, act above it, escalate below it.
|
|
34
|
+
- **Tool retrieval**: declare a large catalogue and a built-in retrieval head renders only the top five tools per turn, with the grammar constrained to that subset.
|
|
35
|
+
- **Bounded memory**: a 256-token sliding window with the tools pinned as KV sinks, so total memory stays near 28MB no matter how long the conversation runs.
|
|
36
|
+
|
|
37
|
+
Weights: [huggingface.co/Cactus-Compute/needle2](https://huggingface.co/Cactus-Compute/needle2) · source: [github.com/cactus-compute/needle](https://github.com/cactus-compute/needle).
|
|
38
|
+
|
|
39
|
+

|
|
40
|
+
|
|
41
|
+
## Simple Attention Network
|
|
42
|
+
|
|
43
|
+
Needle 2 is a Simple Attention Network, our dense small-model recipe: a Hadamard MLP in place of the FFN, GQA attention, engram key-value memory, and multi-lane hyper-connections. See the paper for the design and ablations: [arXiv:2607.18363](https://arxiv.org/abs/2607.18363).
|
|
44
|
+
|
|
45
|
+

|
|
46
|
+
|
|
47
|
+
Each block carries its update rule. Here x̂ is the RMS-normalised flattening of the four residual streams, H the orthonormal Walsh-Hadamard transform (a fixed matrix, applied in n log n time with no weights to read), (kₜ, vₜ) rows gathered from hashed n-gram tables, and P the doubly-stochastic normalisation of the routing logits A, computed by Sinkhorn iteration; a, b, g and all σ-gates are learned and input-dependent. Both attention and MLP residuals are sandwich-normed and gated, the engram sites fire at two layers, and decoding is constrained by a byte-level grammar compiled from the declared schemas.
|
|
48
|
+
|
|
49
|
+
## Quickstart
|
|
50
|
+
|
|
51
|
+
```sh
|
|
52
|
+
pip install cactus-needle
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Needle reads your tool descriptions to decide what to call and how to fill arguments, so describing them well is the whole game. You can do it three ways, from least to most control.
|
|
56
|
+
|
|
57
|
+
**Simple**: decorate a function. The signature gives the argument types, the docstring is the tool description, and `run()` completes the loop: model picks the call, Needle executes your function, feeds the result back, and returns the model's final answer.
|
|
58
|
+
|
|
59
|
+
```python
|
|
60
|
+
import needle
|
|
61
|
+
|
|
62
|
+
@needle.tool
|
|
63
|
+
def get_weather(city: str):
|
|
64
|
+
"Get the current weather for a city."
|
|
65
|
+
return {"city": city, "temp_c": 27, "sky": "clear"}
|
|
66
|
+
|
|
67
|
+
agent = needle.Needle(tools=[get_weather])
|
|
68
|
+
print(agent.run("what's it like in Lagos right now?")["reasoning"])
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
**Medium**: describe each argument and offer choices. Needle reads a Google-style `Args:` block for per-parameter descriptions; a default makes an argument optional; a `Literal` becomes a fixed set the model must choose from (it cannot emit anything else).
|
|
72
|
+
|
|
73
|
+
```python
|
|
74
|
+
from typing import Literal
|
|
75
|
+
|
|
76
|
+
@needle.tool
|
|
77
|
+
def set_thermostat(temperature: int, mode: Literal["heat", "cool", "auto"] = "auto"):
|
|
78
|
+
"""Set the thermostat.
|
|
79
|
+
|
|
80
|
+
Args:
|
|
81
|
+
temperature: target temperature in Celsius
|
|
82
|
+
mode: heating strategy to use
|
|
83
|
+
"""
|
|
84
|
+
return {"temperature": temperature, "mode": mode}
|
|
85
|
+
|
|
86
|
+
agent = needle.Needle(tools=[set_thermostat])
|
|
87
|
+
agent.run("make it 21 and cool the room")
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
**Advanced**: constrain the values with `needle.Field`, attached inline via `Annotated`. Ranges, patterns, lengths, and item counts are compiled into the decode grammar, so the model can only ever emit values that satisfy them.
|
|
91
|
+
|
|
92
|
+
```python
|
|
93
|
+
from typing import Annotated
|
|
94
|
+
|
|
95
|
+
@needle.tool
|
|
96
|
+
def send_money(
|
|
97
|
+
amount: Annotated[float, needle.Field(gt=0, le=10000, description="USD, up to 10,000")],
|
|
98
|
+
to: Annotated[str, needle.Field(pattern=r"^@[a-z0-9_]+$", description="recipient handle")],
|
|
99
|
+
memo: Annotated[str, needle.Field(max_length=80)] = "",
|
|
100
|
+
):
|
|
101
|
+
"Send money to a handle."
|
|
102
|
+
return {"sent": amount, "to": to}
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
`Field` supports `description`, `enum`, `const`, `ge`/`le`/`gt`/`lt`, `multiple_of`, `min_length`/`max_length`, `pattern`, `format`, `min_items`/`max_items`, and `unique_items`.
|
|
106
|
+
|
|
107
|
+
**Extraction**: to pull structured data out of text, declare the shape and call `extract()`. Pass a Pydantic model and you get a typed object back.
|
|
108
|
+
|
|
109
|
+
```python
|
|
110
|
+
from pydantic import BaseModel
|
|
111
|
+
|
|
112
|
+
class Invoice(BaseModel):
|
|
113
|
+
vendor: str
|
|
114
|
+
total: float
|
|
115
|
+
due_date: str
|
|
116
|
+
|
|
117
|
+
invoice = needle.extract("Invoice from Acme Corp, $1,200.00, due 2026-09-01", Invoice)
|
|
118
|
+
print(invoice.vendor, invoice.total) # -> Acme Corp 1200.0
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
**By hand** - the decorator just builds a JSON schema; you can pass that schema directly, which is exactly what Needle consumes. This is how you set descriptions and constraints without the decorator:
|
|
122
|
+
|
|
123
|
+
```python
|
|
124
|
+
tools = [{
|
|
125
|
+
"name": "set_lights",
|
|
126
|
+
"description": "Turn a room's lights on or off and set brightness",
|
|
127
|
+
"parameters": {
|
|
128
|
+
"type": "object",
|
|
129
|
+
"properties": {
|
|
130
|
+
"room": {"type": "string", "description": "which room to control"},
|
|
131
|
+
"on": {"type": "boolean"},
|
|
132
|
+
"brightness": {"type": "integer", "minimum": 0, "maximum": 100},
|
|
133
|
+
},
|
|
134
|
+
"required": ["room", "on"],
|
|
135
|
+
},
|
|
136
|
+
}]
|
|
137
|
+
agent = needle.Needle(tools=tools)
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
Prefer to drive the loop yourself instead of `run()`? `complete()` returns the raw call and you execute it:
|
|
141
|
+
|
|
142
|
+
```python
|
|
143
|
+
import json
|
|
144
|
+
response = agent.complete("dim the living room to 30")
|
|
145
|
+
if response["type"] == "call":
|
|
146
|
+
result = set_lights(**response["function_calls"][0]["arguments"])
|
|
147
|
+
response = agent.complete(json.dumps(result)) # feed the result back
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
With a large catalogue, persist tool embeddings across runs with `needle.Needle(tools=..., tool_index_path="tools.idx")`. Every turn returns one JSON object:
|
|
151
|
+
|
|
152
|
+
```json
|
|
153
|
+
{
|
|
154
|
+
"type": "call",
|
|
155
|
+
"success": true,
|
|
156
|
+
"error": null,
|
|
157
|
+
"error_code": null,
|
|
158
|
+
"function_calls": [ { "name": "set_lights", "arguments": { "room": "living room", "on": true, "brightness": 30 } } ],
|
|
159
|
+
"reasoning": "'living room' -> room; 'dim' -> on true, brightness 30",
|
|
160
|
+
"confidence": 0.94,
|
|
161
|
+
"prefill_tps": 4300.0,
|
|
162
|
+
"decode_tps": 850.0
|
|
163
|
+
}
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
## Playground
|
|
167
|
+
|
|
168
|
+
Try any model in the browser: pick a preset, edit the tools or prompt, and Run. Follow-up queries continue the same conversation.
|
|
169
|
+
|
|
170
|
+
```sh
|
|
171
|
+
needle playground # base model, http://127.0.0.1:7860
|
|
172
|
+
needle playground --weights my.cact # a tuned model
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
The server downloads and initializes the model before serving, so the first query is instant. The **Finetune on these tools** button runs the fine-tuning pipeline below from the UI and hands back a downloadable `.cact`.
|
|
176
|
+
|
|
177
|
+
## Behaviour
|
|
178
|
+
|
|
179
|
+
Needle solves every problem as a function call. The context declares what may be called; the model answers with calls. Performing an action and extracting structured data are the same operation, the only difference is what you declare.
|
|
180
|
+
|
|
181
|
+
- A request no declared tool can serve is refused with the empty call `[]`. That is the whole contract for off-topic input; there is no free-text fallback.
|
|
182
|
+
- Arguments contain only values evidenced by the input. An optional field with no evidence is omitted, not guessed; omission is the field-level `[]`.
|
|
183
|
+
- `reasoning` is the model's short derivation of each argument from its source span (`'ten minutes' -> minutes 10`). It is generated unconstrained; only the call itself is grammar-constrained, so the JSON cannot be malformed while the derivation stays legible.
|
|
184
|
+
- After you execute a call, pass the result back as the next `complete()`. The model continues from it, and later arguments may depend on earlier results: `search_for_contact` first, then `send_instant_message` with the returned `contact_id`. A final step may answer in plain text from the results: `"type": "respond"` with empty `function_calls`.
|
|
185
|
+
- A session shares one toolset. Later turns are bare queries against the same tools; `reset()` rewinds the conversation and keeps the tools loaded.
|
|
186
|
+
|
|
187
|
+
## Extraction
|
|
188
|
+
|
|
189
|
+
Extraction is not a separate mode - it is tool calling with one tool. Declare the record as the only schema and pass the content where the query goes; the returned call's `arguments` are the extracted fields. With one declared tool the grammar admits exactly one call of that name, so schema conformance is guaranteed rather than requested. Use the `extract()` helper for a typed result (shown in Quickstart), or pass a plain schema and read the call:
|
|
190
|
+
|
|
191
|
+
```python
|
|
192
|
+
receipt = [{
|
|
193
|
+
"name": "receipt",
|
|
194
|
+
"description": "A purchase receipt shared as text",
|
|
195
|
+
"parameters": {
|
|
196
|
+
"type": "object",
|
|
197
|
+
"properties": {
|
|
198
|
+
"merchant": {"type": "string"},
|
|
199
|
+
"total": {"type": "number"},
|
|
200
|
+
"currency": {"type": "string"},
|
|
201
|
+
"line_items": {"type": "array", "items": {"type": "object"}},
|
|
202
|
+
},
|
|
203
|
+
"required": ["merchant", "total"],
|
|
204
|
+
},
|
|
205
|
+
}]
|
|
206
|
+
agent = needle.Needle(tools=receipt)
|
|
207
|
+
print(agent.complete("GreenMart receipt: oat milk 3.50, total 7.75 paid by visa")["function_calls"])
|
|
208
|
+
# -> [{"name": "receipt", "arguments": {"merchant": "GreenMart", "total": 7.75}}]
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
Because it is the same operation, everything else applies unchanged: `confidence` gates the extraction, unsupported input returns the empty call `[]`, and fine-tuning uses the same data format (the record as the tool, the passage as the query).
|
|
212
|
+
|
|
213
|
+
## System facts
|
|
214
|
+
|
|
215
|
+
An optional system turn carries environment state as facts, never instructions:
|
|
216
|
+
|
|
217
|
+
```python
|
|
218
|
+
agent = needle.Needle(tools=tools, system="date: 2026-07-21 Tue 14:30; locale: en-US; device: phone; battery: 62%")
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
Recognized keys are `date`, `locale`, `device`, `battery`, `network`, `location`, `user`, and `assistant`. The model resolves relative language against them: "tomorrow at 7" becomes an absolute time only when a `date:` fact licenses it, otherwise the human phrase passes through verbatim. `assistant:` declares the identity the model binds to. Needle trains with and without the turn, so omitting it is safe; instructions placed there do not steer the model.
|
|
222
|
+
|
|
223
|
+
## Tool retrieval
|
|
224
|
+
|
|
225
|
+
Five or fewer declared tools render directly. Above that, retrieval engages: at init every tool schema is embedded once by a built-in contrastive head, each turn embeds the query, and only the five highest-scoring tools enter the context, with the grammar rebuilt over just that subset. An unselected tool is unreachable, not merely unlikely. `tool_index_path` persists the embeddings on disk, keyed by a fingerprint over the schemas and the model; a matching fingerprint loads instantly, a changed schema re-embeds only what changed.
|
|
226
|
+
|
|
227
|
+
## Confidence
|
|
228
|
+
|
|
229
|
+
The `confidence` field is the minimum of two signals: a calibrated post-hoc head that scores the full prompt plus the call the model just produced, and the decoding probability of the call tokens. A call is accepted only when both agree, so the failure mode is escalation, not wrong execution. The contract: pick a threshold for your product, act at or above it, re-ask or route to a bigger model below it. Off-topic requests return the empty call `[]`.
|
|
230
|
+
|
|
231
|
+
## Fine-tuning
|
|
232
|
+
|
|
233
|
+
Needle fine-tunes with LoRA on the frozen base and merges the adapter at export, so a run is cheap and the tuned model is still a single `.cact` that runs on the same engine. The workflow is: (optionally) synthesize data, LoRA fine-tune, then build a tuned `.cact`.
|
|
234
|
+
|
|
235
|
+
**Data format.** A JSONL file, one example per line. `reasoning` is optional; an off-topic example has `answers: []`.
|
|
236
|
+
|
|
237
|
+
```json
|
|
238
|
+
{"query": "dim the kitchen to 10", "tools": [{"name": "set_lights", "parameters": {"type": "object", "properties": {"room": {"type": "string"}, "brightness": {"type": "integer"}}, "required": ["room"]}}], "answers": [{"name": "set_lights", "arguments": {"room": "kitchen", "brightness": 10}}], "reasoning": "'kitchen' -> room; 'dim to 10' -> brightness 10"}
|
|
239
|
+
```
|
|
240
|
+
|
|
241
|
+
**1. Synthesize data (optional).** Needs `OPENROUTER_API_KEY`. Seed from a tool schema file, or expand an existing set:
|
|
242
|
+
|
|
243
|
+
```sh
|
|
244
|
+
export OPENROUTER_API_KEY=sk-or-...
|
|
245
|
+
needle generate-data --tools my_tools.json --num-samples 500 --output data.jsonl
|
|
246
|
+
needle generate-data --augment data.jsonl --num-samples 500 # expand an existing JSONL
|
|
247
|
+
```
|
|
248
|
+
|
|
249
|
+
**2. LoRA fine-tune.** The base checkpoint auto-downloads from Hugging Face if you do not pass `--checkpoint`. `--generate N` first synthesizes N more examples from the tools in your data (also needs `OPENROUTER_API_KEY`).
|
|
250
|
+
|
|
251
|
+
```sh
|
|
252
|
+
needle finetune data.jsonl --epochs 3
|
|
253
|
+
needle finetune data.jsonl --epochs 3 --generate 300 --lora-rank 16 --lora-alpha 32
|
|
254
|
+
```
|
|
255
|
+
|
|
256
|
+
Key options: `--lora-rank` (default 16), `--lora-alpha` (32), `--lr` (1e-4), `--batch-size` (16), `--max-len` (1024), `--checkpoint <base.pkl>`, `--out <adapter.pkl>`. The adapter is written to `checkpoints/needle_lora.pkl`.
|
|
257
|
+
|
|
258
|
+
**3. Build a tuned `.cact`.** Merge the adapter into the base and quantize. The base auto-downloads if absent.
|
|
259
|
+
|
|
260
|
+
```sh
|
|
261
|
+
needle build checkpoints/needle2.pkl --lora checkpoints/needle_lora.pkl --out my_needle.cact
|
|
262
|
+
```
|
|
263
|
+
|
|
264
|
+
Add `--bits 2` (default 4) for a smaller model, or set `NEEDLE_HF_REPO=<you>/<model>` and pass `--upload` to publish the `.cact`.
|
|
265
|
+
|
|
266
|
+
**4. Run it.** The engine is weights-agnostic, so a tuned `.cact` runs on it directly - no recompilation:
|
|
267
|
+
|
|
268
|
+
```python
|
|
269
|
+
import needle
|
|
270
|
+
agent = needle.Needle(weights="my_needle.cact", tools=[...])
|
|
271
|
+
agent.run("...")
|
|
272
|
+
```
|
|
273
|
+
|
|
274
|
+
## Citation
|
|
275
|
+
|
|
276
|
+
Needle 2 is built by the Cactus Compute team. If you use it in your work, please cite:
|
|
277
|
+
|
|
278
|
+
```bibtex
|
|
279
|
+
@misc{needle2_2026,
|
|
280
|
+
title = {Needle 2: A 45M-Parameter Foundation Tool-Calling Model for Tiny Devices},
|
|
281
|
+
author = {Ndubuaku, Henry and Mosoyan, Karen and Mroz, Jakub and Cylich, Noah and
|
|
282
|
+
Kumar, Satyajit and Sandhu, Parkirat and Shemet, Roman and Lee, Justin H.},
|
|
283
|
+
year = {2026},
|
|
284
|
+
organization = {Cactus Compute, Inc.},
|
|
285
|
+
howpublished = {\url{https://github.com/cactus-compute/needle}}
|
|
286
|
+
}
|
|
287
|
+
```
|
|
288
|
+
|
|
289
|
+
Reach out on founders@cactuscompute.com for partnerships, collaborations, synergies and deploying Needle2 in your product.
|
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+

|
|
2
|
+
|
|
3
|
+
# Needle 2
|
|
4
|
+
|
|
5
|
+
Needle 2 is an open 45M-parameter model for tool calling, device use and structured extraction. The whole model is a single 14MB binary that runs a full session in about 28MB of RAM. It is built on our Simple Attention Network findings, compressed to CQ2-bit with Cactus Quants, and baked into its own engine. On the benchmarks below, Needle 2 trades wins with other small models like FunctionGemma 270M, LFM2.5 230M and Apple FM, at 5x to 70x smaller, and 2 bits against their f16.
|
|
6
|
+
|
|
7
|
+
This repository is the Python package: inference, LoRA fine-tuning, and export. `pip install cactus-needle`, describe your tools, and call them from Python. The inference engine is fetched once from Hugging Face and cached; there is nothing else to build.
|
|
8
|
+
|
|
9
|
+
- **Self-contained**: weights baked into a single 14MB engine; no separate model files to manage, and inference does no network.
|
|
10
|
+
- **Simple contract**: tool calls come back as structured data, text in, JSON out; a byte-level grammar compiled from your schemas constrains every token.
|
|
11
|
+
- **Confidence-gated**: every response carries a calibrated confidence score from a learned head; set a threshold, act above it, escalate below it.
|
|
12
|
+
- **Tool retrieval**: declare a large catalogue and a built-in retrieval head renders only the top five tools per turn, with the grammar constrained to that subset.
|
|
13
|
+
- **Bounded memory**: a 256-token sliding window with the tools pinned as KV sinks, so total memory stays near 28MB no matter how long the conversation runs.
|
|
14
|
+
|
|
15
|
+
Weights: [huggingface.co/Cactus-Compute/needle2](https://huggingface.co/Cactus-Compute/needle2) · source: [github.com/cactus-compute/needle](https://github.com/cactus-compute/needle).
|
|
16
|
+
|
|
17
|
+

|
|
18
|
+
|
|
19
|
+
## Simple Attention Network
|
|
20
|
+
|
|
21
|
+
Needle 2 is a Simple Attention Network, our dense small-model recipe: a Hadamard MLP in place of the FFN, GQA attention, engram key-value memory, and multi-lane hyper-connections. See the paper for the design and ablations: [arXiv:2607.18363](https://arxiv.org/abs/2607.18363).
|
|
22
|
+
|
|
23
|
+

|
|
24
|
+
|
|
25
|
+
Each block carries its update rule. Here x̂ is the RMS-normalised flattening of the four residual streams, H the orthonormal Walsh-Hadamard transform (a fixed matrix, applied in n log n time with no weights to read), (kₜ, vₜ) rows gathered from hashed n-gram tables, and P the doubly-stochastic normalisation of the routing logits A, computed by Sinkhorn iteration; a, b, g and all σ-gates are learned and input-dependent. Both attention and MLP residuals are sandwich-normed and gated, the engram sites fire at two layers, and decoding is constrained by a byte-level grammar compiled from the declared schemas.
|
|
26
|
+
|
|
27
|
+
## Quickstart
|
|
28
|
+
|
|
29
|
+
```sh
|
|
30
|
+
pip install cactus-needle
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
Needle reads your tool descriptions to decide what to call and how to fill arguments, so describing them well is the whole game. You can do it three ways, from least to most control.
|
|
34
|
+
|
|
35
|
+
**Simple**: decorate a function. The signature gives the argument types, the docstring is the tool description, and `run()` completes the loop: model picks the call, Needle executes your function, feeds the result back, and returns the model's final answer.
|
|
36
|
+
|
|
37
|
+
```python
|
|
38
|
+
import needle
|
|
39
|
+
|
|
40
|
+
@needle.tool
|
|
41
|
+
def get_weather(city: str):
|
|
42
|
+
"Get the current weather for a city."
|
|
43
|
+
return {"city": city, "temp_c": 27, "sky": "clear"}
|
|
44
|
+
|
|
45
|
+
agent = needle.Needle(tools=[get_weather])
|
|
46
|
+
print(agent.run("what's it like in Lagos right now?")["reasoning"])
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
**Medium**: describe each argument and offer choices. Needle reads a Google-style `Args:` block for per-parameter descriptions; a default makes an argument optional; a `Literal` becomes a fixed set the model must choose from (it cannot emit anything else).
|
|
50
|
+
|
|
51
|
+
```python
|
|
52
|
+
from typing import Literal
|
|
53
|
+
|
|
54
|
+
@needle.tool
|
|
55
|
+
def set_thermostat(temperature: int, mode: Literal["heat", "cool", "auto"] = "auto"):
|
|
56
|
+
"""Set the thermostat.
|
|
57
|
+
|
|
58
|
+
Args:
|
|
59
|
+
temperature: target temperature in Celsius
|
|
60
|
+
mode: heating strategy to use
|
|
61
|
+
"""
|
|
62
|
+
return {"temperature": temperature, "mode": mode}
|
|
63
|
+
|
|
64
|
+
agent = needle.Needle(tools=[set_thermostat])
|
|
65
|
+
agent.run("make it 21 and cool the room")
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
**Advanced**: constrain the values with `needle.Field`, attached inline via `Annotated`. Ranges, patterns, lengths, and item counts are compiled into the decode grammar, so the model can only ever emit values that satisfy them.
|
|
69
|
+
|
|
70
|
+
```python
|
|
71
|
+
from typing import Annotated
|
|
72
|
+
|
|
73
|
+
@needle.tool
|
|
74
|
+
def send_money(
|
|
75
|
+
amount: Annotated[float, needle.Field(gt=0, le=10000, description="USD, up to 10,000")],
|
|
76
|
+
to: Annotated[str, needle.Field(pattern=r"^@[a-z0-9_]+$", description="recipient handle")],
|
|
77
|
+
memo: Annotated[str, needle.Field(max_length=80)] = "",
|
|
78
|
+
):
|
|
79
|
+
"Send money to a handle."
|
|
80
|
+
return {"sent": amount, "to": to}
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
`Field` supports `description`, `enum`, `const`, `ge`/`le`/`gt`/`lt`, `multiple_of`, `min_length`/`max_length`, `pattern`, `format`, `min_items`/`max_items`, and `unique_items`.
|
|
84
|
+
|
|
85
|
+
**Extraction**: to pull structured data out of text, declare the shape and call `extract()`. Pass a Pydantic model and you get a typed object back.
|
|
86
|
+
|
|
87
|
+
```python
|
|
88
|
+
from pydantic import BaseModel
|
|
89
|
+
|
|
90
|
+
class Invoice(BaseModel):
|
|
91
|
+
vendor: str
|
|
92
|
+
total: float
|
|
93
|
+
due_date: str
|
|
94
|
+
|
|
95
|
+
invoice = needle.extract("Invoice from Acme Corp, $1,200.00, due 2026-09-01", Invoice)
|
|
96
|
+
print(invoice.vendor, invoice.total) # -> Acme Corp 1200.0
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
**By hand** - the decorator just builds a JSON schema; you can pass that schema directly, which is exactly what Needle consumes. This is how you set descriptions and constraints without the decorator:
|
|
100
|
+
|
|
101
|
+
```python
|
|
102
|
+
tools = [{
|
|
103
|
+
"name": "set_lights",
|
|
104
|
+
"description": "Turn a room's lights on or off and set brightness",
|
|
105
|
+
"parameters": {
|
|
106
|
+
"type": "object",
|
|
107
|
+
"properties": {
|
|
108
|
+
"room": {"type": "string", "description": "which room to control"},
|
|
109
|
+
"on": {"type": "boolean"},
|
|
110
|
+
"brightness": {"type": "integer", "minimum": 0, "maximum": 100},
|
|
111
|
+
},
|
|
112
|
+
"required": ["room", "on"],
|
|
113
|
+
},
|
|
114
|
+
}]
|
|
115
|
+
agent = needle.Needle(tools=tools)
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
Prefer to drive the loop yourself instead of `run()`? `complete()` returns the raw call and you execute it:
|
|
119
|
+
|
|
120
|
+
```python
|
|
121
|
+
import json
|
|
122
|
+
response = agent.complete("dim the living room to 30")
|
|
123
|
+
if response["type"] == "call":
|
|
124
|
+
result = set_lights(**response["function_calls"][0]["arguments"])
|
|
125
|
+
response = agent.complete(json.dumps(result)) # feed the result back
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
With a large catalogue, persist tool embeddings across runs with `needle.Needle(tools=..., tool_index_path="tools.idx")`. Every turn returns one JSON object:
|
|
129
|
+
|
|
130
|
+
```json
|
|
131
|
+
{
|
|
132
|
+
"type": "call",
|
|
133
|
+
"success": true,
|
|
134
|
+
"error": null,
|
|
135
|
+
"error_code": null,
|
|
136
|
+
"function_calls": [ { "name": "set_lights", "arguments": { "room": "living room", "on": true, "brightness": 30 } } ],
|
|
137
|
+
"reasoning": "'living room' -> room; 'dim' -> on true, brightness 30",
|
|
138
|
+
"confidence": 0.94,
|
|
139
|
+
"prefill_tps": 4300.0,
|
|
140
|
+
"decode_tps": 850.0
|
|
141
|
+
}
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
## Playground
|
|
145
|
+
|
|
146
|
+
Try any model in the browser: pick a preset, edit the tools or prompt, and Run. Follow-up queries continue the same conversation.
|
|
147
|
+
|
|
148
|
+
```sh
|
|
149
|
+
needle playground # base model, http://127.0.0.1:7860
|
|
150
|
+
needle playground --weights my.cact # a tuned model
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
The server downloads and initializes the model before serving, so the first query is instant. The **Finetune on these tools** button runs the fine-tuning pipeline below from the UI and hands back a downloadable `.cact`.
|
|
154
|
+
|
|
155
|
+
## Behaviour
|
|
156
|
+
|
|
157
|
+
Needle solves every problem as a function call. The context declares what may be called; the model answers with calls. Performing an action and extracting structured data are the same operation, the only difference is what you declare.
|
|
158
|
+
|
|
159
|
+
- A request no declared tool can serve is refused with the empty call `[]`. That is the whole contract for off-topic input; there is no free-text fallback.
|
|
160
|
+
- Arguments contain only values evidenced by the input. An optional field with no evidence is omitted, not guessed; omission is the field-level `[]`.
|
|
161
|
+
- `reasoning` is the model's short derivation of each argument from its source span (`'ten minutes' -> minutes 10`). It is generated unconstrained; only the call itself is grammar-constrained, so the JSON cannot be malformed while the derivation stays legible.
|
|
162
|
+
- After you execute a call, pass the result back as the next `complete()`. The model continues from it, and later arguments may depend on earlier results: `search_for_contact` first, then `send_instant_message` with the returned `contact_id`. A final step may answer in plain text from the results: `"type": "respond"` with empty `function_calls`.
|
|
163
|
+
- A session shares one toolset. Later turns are bare queries against the same tools; `reset()` rewinds the conversation and keeps the tools loaded.
|
|
164
|
+
|
|
165
|
+
## Extraction
|
|
166
|
+
|
|
167
|
+
Extraction is not a separate mode - it is tool calling with one tool. Declare the record as the only schema and pass the content where the query goes; the returned call's `arguments` are the extracted fields. With one declared tool the grammar admits exactly one call of that name, so schema conformance is guaranteed rather than requested. Use the `extract()` helper for a typed result (shown in Quickstart), or pass a plain schema and read the call:
|
|
168
|
+
|
|
169
|
+
```python
|
|
170
|
+
receipt = [{
|
|
171
|
+
"name": "receipt",
|
|
172
|
+
"description": "A purchase receipt shared as text",
|
|
173
|
+
"parameters": {
|
|
174
|
+
"type": "object",
|
|
175
|
+
"properties": {
|
|
176
|
+
"merchant": {"type": "string"},
|
|
177
|
+
"total": {"type": "number"},
|
|
178
|
+
"currency": {"type": "string"},
|
|
179
|
+
"line_items": {"type": "array", "items": {"type": "object"}},
|
|
180
|
+
},
|
|
181
|
+
"required": ["merchant", "total"],
|
|
182
|
+
},
|
|
183
|
+
}]
|
|
184
|
+
agent = needle.Needle(tools=receipt)
|
|
185
|
+
print(agent.complete("GreenMart receipt: oat milk 3.50, total 7.75 paid by visa")["function_calls"])
|
|
186
|
+
# -> [{"name": "receipt", "arguments": {"merchant": "GreenMart", "total": 7.75}}]
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
Because it is the same operation, everything else applies unchanged: `confidence` gates the extraction, unsupported input returns the empty call `[]`, and fine-tuning uses the same data format (the record as the tool, the passage as the query).
|
|
190
|
+
|
|
191
|
+
## System facts
|
|
192
|
+
|
|
193
|
+
An optional system turn carries environment state as facts, never instructions:
|
|
194
|
+
|
|
195
|
+
```python
|
|
196
|
+
agent = needle.Needle(tools=tools, system="date: 2026-07-21 Tue 14:30; locale: en-US; device: phone; battery: 62%")
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
Recognized keys are `date`, `locale`, `device`, `battery`, `network`, `location`, `user`, and `assistant`. The model resolves relative language against them: "tomorrow at 7" becomes an absolute time only when a `date:` fact licenses it, otherwise the human phrase passes through verbatim. `assistant:` declares the identity the model binds to. Needle trains with and without the turn, so omitting it is safe; instructions placed there do not steer the model.
|
|
200
|
+
|
|
201
|
+
## Tool retrieval
|
|
202
|
+
|
|
203
|
+
Five or fewer declared tools render directly. Above that, retrieval engages: at init every tool schema is embedded once by a built-in contrastive head, each turn embeds the query, and only the five highest-scoring tools enter the context, with the grammar rebuilt over just that subset. An unselected tool is unreachable, not merely unlikely. `tool_index_path` persists the embeddings on disk, keyed by a fingerprint over the schemas and the model; a matching fingerprint loads instantly, a changed schema re-embeds only what changed.
|
|
204
|
+
|
|
205
|
+
## Confidence
|
|
206
|
+
|
|
207
|
+
The `confidence` field is the minimum of two signals: a calibrated post-hoc head that scores the full prompt plus the call the model just produced, and the decoding probability of the call tokens. A call is accepted only when both agree, so the failure mode is escalation, not wrong execution. The contract: pick a threshold for your product, act at or above it, re-ask or route to a bigger model below it. Off-topic requests return the empty call `[]`.
|
|
208
|
+
|
|
209
|
+
## Fine-tuning
|
|
210
|
+
|
|
211
|
+
Needle fine-tunes with LoRA on the frozen base and merges the adapter at export, so a run is cheap and the tuned model is still a single `.cact` that runs on the same engine. The workflow is: (optionally) synthesize data, LoRA fine-tune, then build a tuned `.cact`.
|
|
212
|
+
|
|
213
|
+
**Data format.** A JSONL file, one example per line. `reasoning` is optional; an off-topic example has `answers: []`.
|
|
214
|
+
|
|
215
|
+
```json
|
|
216
|
+
{"query": "dim the kitchen to 10", "tools": [{"name": "set_lights", "parameters": {"type": "object", "properties": {"room": {"type": "string"}, "brightness": {"type": "integer"}}, "required": ["room"]}}], "answers": [{"name": "set_lights", "arguments": {"room": "kitchen", "brightness": 10}}], "reasoning": "'kitchen' -> room; 'dim to 10' -> brightness 10"}
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
**1. Synthesize data (optional).** Needs `OPENROUTER_API_KEY`. Seed from a tool schema file, or expand an existing set:
|
|
220
|
+
|
|
221
|
+
```sh
|
|
222
|
+
export OPENROUTER_API_KEY=sk-or-...
|
|
223
|
+
needle generate-data --tools my_tools.json --num-samples 500 --output data.jsonl
|
|
224
|
+
needle generate-data --augment data.jsonl --num-samples 500 # expand an existing JSONL
|
|
225
|
+
```
|
|
226
|
+
|
|
227
|
+
**2. LoRA fine-tune.** The base checkpoint auto-downloads from Hugging Face if you do not pass `--checkpoint`. `--generate N` first synthesizes N more examples from the tools in your data (also needs `OPENROUTER_API_KEY`).
|
|
228
|
+
|
|
229
|
+
```sh
|
|
230
|
+
needle finetune data.jsonl --epochs 3
|
|
231
|
+
needle finetune data.jsonl --epochs 3 --generate 300 --lora-rank 16 --lora-alpha 32
|
|
232
|
+
```
|
|
233
|
+
|
|
234
|
+
Key options: `--lora-rank` (default 16), `--lora-alpha` (32), `--lr` (1e-4), `--batch-size` (16), `--max-len` (1024), `--checkpoint <base.pkl>`, `--out <adapter.pkl>`. The adapter is written to `checkpoints/needle_lora.pkl`.
|
|
235
|
+
|
|
236
|
+
**3. Build a tuned `.cact`.** Merge the adapter into the base and quantize. The base auto-downloads if absent.
|
|
237
|
+
|
|
238
|
+
```sh
|
|
239
|
+
needle build checkpoints/needle2.pkl --lora checkpoints/needle_lora.pkl --out my_needle.cact
|
|
240
|
+
```
|
|
241
|
+
|
|
242
|
+
Add `--bits 2` (default 4) for a smaller model, or set `NEEDLE_HF_REPO=<you>/<model>` and pass `--upload` to publish the `.cact`.
|
|
243
|
+
|
|
244
|
+
**4. Run it.** The engine is weights-agnostic, so a tuned `.cact` runs on it directly - no recompilation:
|
|
245
|
+
|
|
246
|
+
```python
|
|
247
|
+
import needle
|
|
248
|
+
agent = needle.Needle(weights="my_needle.cact", tools=[...])
|
|
249
|
+
agent.run("...")
|
|
250
|
+
```
|
|
251
|
+
|
|
252
|
+
## Citation
|
|
253
|
+
|
|
254
|
+
Needle 2 is built by the Cactus Compute team. If you use it in your work, please cite:
|
|
255
|
+
|
|
256
|
+
```bibtex
|
|
257
|
+
@misc{needle2_2026,
|
|
258
|
+
title = {Needle 2: A 45M-Parameter Foundation Tool-Calling Model for Tiny Devices},
|
|
259
|
+
author = {Ndubuaku, Henry and Mosoyan, Karen and Mroz, Jakub and Cylich, Noah and
|
|
260
|
+
Kumar, Satyajit and Sandhu, Parkirat and Shemet, Roman and Lee, Justin H.},
|
|
261
|
+
year = {2026},
|
|
262
|
+
organization = {Cactus Compute, Inc.},
|
|
263
|
+
howpublished = {\url{https://github.com/cactus-compute/needle}}
|
|
264
|
+
}
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
Reach out on founders@cactuscompute.com for partnerships, collaborations, synergies and deploying Needle2 in your product.
|