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.
Enhance finetuning and testing capabilities; add new test cases and update dependencies
HenryNdubuakuda3b96dda063
diff --git a/needle/model/finetune.py b/needle/model/finetune.pyindex 492b51d..65d85ff 100644--- a/needle/model/finetune.py+++ b/needle/model/finetune.py@@ -215,6 +215,7 @@ def finetune_local(args):data_path = augment_jsonl(data_path, args.generate, model=getattr(args, "model", None))params, config = load_checkpoint(base_path)+ params = jax.device_put(params)tokenizer = get_tokenizer(config.vocab_size)seqs, masks = load_jsonl(data_path, tokenizer, args.max_len)if len(seqs) == 0:diff --git a/pyproject.toml b/pyproject.tomlindex 600698a..f55e74f 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -10,13 +10,14 @@ dependencies = ["numpy","jax","jaxlib",- "flax",+ "flax>=0.12.8","optax","sentencepiece",][project.optional-dependencies]gpu = ["jax[cuda12]"]+test = ["pytest", "pydantic"][project.scripts]needle = "needle.cli:main"@@ -31,3 +32,7 @@ include = ["needle*"][build-system]requires = ["setuptools>=68.0"]build-backend = "setuptools.build_meta"++[tool.pytest.ini_options]+testpaths = ["tests"]+markers = ["slow: end-to-end JAX build/finetune tests (init a tiny model)"]diff --git a/tests/conftest.py b/tests/conftest.pynew file mode 100644index 0000000..5fb0b67--- /dev/null+++ b/tests/conftest.py@@ -0,0 +1,45 @@+import os+import pickle++import pytest+++def _engine_available():+ try:+ import needle+ from needle.agent import fetch+ here = os.path.dirname(needle.__file__)+ name = fetch._lib_name()+ cache = os.path.join(os.path.expanduser("~"), ".cache",+ "cactus-needle", needle.__version__, name)+ return os.path.exists(os.path.join(here, name)) or os.path.exists(cache)+ except Exception:+ return False+++requires_engine = pytest.mark.skipif(+ not _engine_available(),+ reason="needle C++ engine not installed (auto-fetched from HF on first real use)")++[email protected](scope="session")+def tiny_checkpoint(tmp_path_factory):+ import numpy as np+ import jax+ import jax.numpy as jnp+ from needle.model.architecture import SimpleAttentionNetwork, TransformerConfig++ config = TransformerConfig(+ vocab_size=8192, d_model=64, num_heads=4, num_kv_heads=2, num_layers=2,+ max_seq_len=128, engram_layers=(1,), engram_slots=64, mhc_lanes=2,+ flash=False,+ )+ model = SimpleAttentionNetwork(config)+ params = model.init(jax.random.PRNGKey(0), jnp.ones((1, 8), jnp.int32))["params"]+ params = jax.tree_util.tree_map(lambda x: np.asarray(x), params)++ path = tmp_path_factory.mktemp("ckpt") / "tiny.pkl"+ with open(path, "wb") as handle:+ pickle.dump({"format_version": 2, "params": params,+ "config": dict(vars(config))}, handle)+ return str(path)diff --git a/tests/test_build.py b/tests/test_build.pynew file mode 100644index 0000000..a1835f8--- /dev/null+++ b/tests/test_build.py@@ -0,0 +1,59 @@+import os+import types++import pytest++pytestmark = pytest.mark.slow+++def _build_args(checkpoint, out, bits="4", lora=None):+ return types.SimpleNamespace(checkpoint=checkpoint, lora=lora, out=out,+ upload=False, bits=bits)+++def test_build_exports_loadable_cact(tiny_checkpoint, tmp_path):+ from needle.model.finetune import build_main+ from needle.model.export import read_export++ out = str(tmp_path / "tiny.cact")+ build_main(_build_args(tiny_checkpoint, out, bits="4"))++ assert os.path.exists(out)+ assert os.path.getsize(out) > 0+ header, tensors = read_export(out)+ assert header["num_tensors"] > 0+ assert len(tensors) == header["num_tensors"]+ assert any(isinstance(t, (bytes, bytearray)) for t in tensors)+++def test_build_at_two_bits(tiny_checkpoint, tmp_path):+ from needle.model.finetune import build_main+ from needle.model.export import read_export++ out = str(tmp_path / "tiny_w2.cact")+ build_main(_build_args(tiny_checkpoint, out, bits="2"))+ header, _ = read_export(out)+ assert header["num_tensors"] > 0+++def test_export_round_trips_a_projection(tiny_checkpoint, tmp_path):+ import pickle+ import numpy as np+ from needle.model.export import write_export, read_export+ from needle.model.architecture import TransformerConfig, effective_kv_window+ from needle.model.tokenizer import get_tokenizer++ with open(tiny_checkpoint, "rb") as handle:+ ckpt = pickle.load(handle)+ params, config = ckpt["params"], TransformerConfig(**ckpt["config"])++ out = str(tmp_path / "rt.cact")+ write_export(params, config, out, bits=4,+ tokenizer=get_tokenizer(config.vocab_size),+ kv_window=effective_kv_window(config))+ header, tensors = read_export(out)++ original = np.asarray(params["stack"]["layers"]["block"]["self_attn"]["q_proj"]["kernel"][0]).T+ dequant = tensors[2]+ assert dequant.shape == original.shape+ assert np.corrcoef(dequant.ravel(), original.ravel())[0, 1] > 0.9diff --git a/tests/test_finetune.py b/tests/test_finetune.pynew file mode 100644index 0000000..71c52e9--- /dev/null+++ b/tests/test_finetune.py@@ -0,0 +1,67 @@+import json+import os+import pickle+import types++import pytest++pytestmark = pytest.mark.slow++TOOLS = [{"name": "send_email", "parameters": {"type": "object", "properties": {+ "to": {"type": "string"}, "subject": {"type": "string"}}, "required": ["to"]}}]+++def _write_data(path):+ rows = [+ {"tools": TOOLS, "query": "email [email protected] about lunch",+ "reasoning": "to from query", "answers": [+ {"name": "send_email", "arguments": {"to": "[email protected]", "subject": "lunch"}}]},+ {"tools": TOOLS, "query": "nothing actionable here",+ "reasoning": "off-topic", "answers": []},+ ]+ with open(path, "w") as handle:+ for row in rows:+ handle.write(json.dumps(row) + "\n")+++def _finetune_args(data, checkpoint, out, ckpt_dir):+ return types.SimpleNamespace(+ jsonl_path=str(data), checkpoint=checkpoint, epochs=1, batch_size=2,+ lr=1e-3, lora_rank=4, lora_alpha=8.0, max_len=64, generate=0,+ model=None, checkpoint_dir=str(ckpt_dir), out=str(out))+++def test_finetune_writes_adapter(tiny_checkpoint, tmp_path):+ from needle.model.finetune import finetune_local++ data = tmp_path / "data.jsonl"+ _write_data(data)+ out = tmp_path / "adapter.pkl"+ finetune_local(_finetune_args(data, tiny_checkpoint, out, tmp_path / "ck"))++ assert out.exists()+ with open(out, "rb") as handle:+ adapter = pickle.load(handle)+ assert adapter["rank"] == 4+ assert abs(adapter["scale"] - 2.0) < 1e-6+ assert adapter["base"] == tiny_checkpoint+ assert adapter["lora"]+ for value in adapter["lora"].values():+ assert "A" in value and "B" in value+++def test_finetune_then_build_merges(tiny_checkpoint, tmp_path):+ from needle.model.finetune import finetune_local, build_main+ from needle.model.export import read_export++ data = tmp_path / "data.jsonl"+ _write_data(data)+ adapter = tmp_path / "adapter.pkl"+ finetune_local(_finetune_args(data, tiny_checkpoint, adapter, tmp_path / "ck"))++ out = str(tmp_path / "merged.cact")+ build_main(types.SimpleNamespace(checkpoint=tiny_checkpoint, lora=str(adapter),+ out=out, upload=False, bits="4"))+ assert os.path.exists(out)+ header, _ = read_export(out)+ assert header["num_tensors"] > 0diff --git a/tests/test_generate.py b/tests/test_generate.pynew file mode 100644index 0000000..c205269--- /dev/null+++ b/tests/test_generate.py@@ -0,0 +1,59 @@+import json++import pytest+++def test_parse_array_variants():+ from needle.model.finetune import _parse_array++ assert len(_parse_array('[{"query":"q","answers":[]}]')) == 1+ assert len(_parse_array('Sure!\n[{"query":"q","answers":[]}]\nDone.')) == 1+ assert _parse_array("no array at all") == []+ assert _parse_array("[not valid json]") == []++ mixed = '[{"query":"q","answers":[]},{"nope":1},{"query":"only"}]'+ assert len(_parse_array(mixed)) == 1+++def test_collect_tools_dedups_by_name():+ from needle.model.finetune import _collect_tools++ examples = [{"tools": [{"name": "a"}, {"name": "b"}]},+ {"tools": [{"name": "a"}, {"name": "c"}]}]+ assert [t["name"] for t in _collect_tools(examples)] == ["a", "b", "c"]+++def test_generate_examples_attaches_tools(monkeypatch):+ from needle.model import finetune++ tools = [{"name": "f", "parameters": {"type": "object", "properties": {}}}]+ monkeypatch.setattr(finetune, "_openrouter",+ lambda *a, **k: '[{"query":"q","reasoning":"r",'+ '"answers":[{"name":"f","arguments":{}}]}]')+ rows = finetune.generate_examples(tools, n=1, api_key="test-key")+ assert len(rows) == 1+ assert rows[0]["tools"] == tools+++def test_generate_examples_requires_api_key(monkeypatch):+ from needle.model import finetune++ monkeypatch.delenv("OPENROUTER_API_KEY", raising=False)+ with pytest.raises(RuntimeError):+ finetune.generate_examples([{"name": "f"}], n=1)+++def test_augment_jsonl_appends_generated(monkeypatch, tmp_path):+ from needle.model import finetune++ tools = [{"name": "f", "parameters": {"type": "object", "properties": {}}}]+ src = tmp_path / "seed.jsonl"+ with open(src, "w") as handle:+ handle.write(json.dumps({"tools": tools, "query": "seed", "answers": []}) + "\n")++ monkeypatch.setattr(finetune, "generate_examples",+ lambda tools, n=1, **k: [{"tools": tools, "query": "gen",+ "answers": []} for _ in range(n)])+ out = finetune.augment_jsonl(str(src), num_samples=3, out_path=str(tmp_path / "out.jsonl"))+ lines = [line for line in open(out) if line.strip()]+ assert len(lines) == 1 + 3diff --git a/tests/test_inference.py b/tests/test_inference.pynew file mode 100644index 0000000..6910e74--- /dev/null+++ b/tests/test_inference.py@@ -0,0 +1,44 @@+from conftest import requires_engine++pytestmark = requires_engine+++def test_tool_call():+ from needle import Needle, tool++ @tool+ def send_email(to: str, subject: str, body: str):+ "Send an email to a recipient."+ return {"ok": True}++ agent = Needle(tools=[send_email])+ response = agent.complete("email [email protected], subject expenses, body coffee $14")+ assert response.get("type") in ("call", "text", "refuse")+ if response.get("type") == "call":+ assert response["function_calls"][0]["name"] == "send_email"+++def test_structured_extraction():+ import pydantic+ from needle import extract++ class Contact(pydantic.BaseModel):+ name: str+ email: str++ result = extract("John Doe can be reached at [email protected]", Contact)+ assert result is None or isinstance(result, Contact)+++def test_run_agentic_loop():+ from needle import Needle, tool++ @tool+ def get_weather(city: str):+ "Get the weather for a city."+ return {"temp_c": 20}++ agent = Needle(tools=[get_weather])+ response = agent.run("what's the weather in Paris?")+ assert isinstance(response, dict)+ assert "type" in responsediff --git a/tests/test_lora.py b/tests/test_lora.pynew file mode 100644index 0000000..91b0f7f--- /dev/null+++ b/tests/test_lora.py@@ -0,0 +1,56 @@+import numpy as np+++def test_lora_target_paths_selects_projection_kernels():+ import jax.numpy as jnp+ from needle.model.finetune import lora_target_paths++ params = {+ "stack": {"layers": {"block": {"self_attn": {+ "q_proj": {"kernel": jnp.ones((2, 8, 8))},+ "gate_proj": {"kernel": jnp.ones((2, 8, 8))},+ "q_norm": {"scale": jnp.ones((2, 8))},+ }}}, "final_norm": {"scale": jnp.ones((8,))}},+ "mtp_combine": {"kernel": jnp.ones((8, 8))},+ }+ paths = lora_target_paths(params)+ assert {p[-2] for p in paths} == {"q_proj", "gate_proj"}+++def test_init_lora_shapes_and_zero_b():+ import jax+ import jax.numpy as jnp+ from needle.model.finetune import init_lora++ params = {"self_attn": {"v_proj": {"kernel": jnp.ones((5, 6, 7))}}}+ paths = [("self_attn", "v_proj", "kernel")]+ lora = init_lora(params, paths, rank=3, key=jax.random.PRNGKey(1))+ adapter = lora[("self_attn", "v_proj", "kernel")]+ assert adapter["A"].shape == (5, 6, 3)+ assert adapter["B"].shape == (5, 3, 7)+ assert np.allclose(np.asarray(adapter["B"]), 0.0)+++def test_merge_lora_is_identity_when_b_zero():+ import jax+ import jax.numpy as jnp+ from needle.model.finetune import init_lora, lora_target_paths, merge_lora++ params = {"self_attn": {"q_proj": {"kernel": jnp.arange(16.0).reshape(1, 4, 4)}}}+ paths = lora_target_paths(params)+ lora = init_lora(params, paths, rank=2, key=jax.random.PRNGKey(0))+ merged = merge_lora(params, lora, scale=8.0)+ np.testing.assert_allclose(+ np.asarray(merged["self_attn"]["q_proj"]["kernel"]),+ np.asarray(params["self_attn"]["q_proj"]["kernel"]), atol=1e-6)+++def test_merge_lora_adds_scaled_delta():+ import jax.numpy as jnp+ from needle.model.finetune import merge_lora++ params = {"w": {"kernel": jnp.zeros((3, 4))}}+ lora = {("w", "kernel"): {"A": jnp.ones((3, 2)), "B": jnp.ones((2, 4))}}+ merged = merge_lora(params, lora, scale=0.5)+ np.testing.assert_allclose(np.asarray(merged["w"]["kernel"]),+ np.ones((3, 4)), atol=1e-6)diff --git a/tests/test_render.py b/tests/test_render.pynew file mode 100644index 0000000..957d596--- /dev/null+++ b/tests/test_render.py@@ -0,0 +1,73 @@+import json++import numpy as np+import pytest++[email protected](scope="module")+def tok():+ from needle.model.tokenizer import get_tokenizer+ return get_tokenizer(8192)+++def test_render_example_markers():+ from needle.model.finetune import render_example+ from needle.model.tokenizer import IM_START, TOOLS_START, TOOL_CALL_START, THINK_START++ example = {"tools": [{"name": "f", "parameters": {"type": "object", "properties": {}}}],+ "query": "do the thing", "reasoning": "because reasons",+ "answers": [{"name": "f", "arguments": {}}]}+ prompt, target = render_example(example)+ assert IM_START in prompt+ assert TOOLS_START in prompt+ assert "do the thing" in prompt+ assert THINK_START in target+ assert "because reasons" in target+ assert TOOL_CALL_START in target+ assert '"name":"f"' in target+++def test_render_example_accepts_function_calls_alias():+ from needle.model.finetune import render_example+ example = {"tools": [], "query": "hi",+ "function_calls": [{"name": "g", "arguments": {"x": 1}}]}+ _, target = render_example(example)+ assert '"name":"g"' in target+++def test_encode_loss_mask_targets_only(tok):+ from needle.model.finetune import _encode, render_example+ from needle.model.tokenizer import BOS_ID++ example = {"tools": [{"name": "f", "parameters": {"type": "object", "properties": {}}}],+ "query": "hello", "answers": [{"name": "f", "arguments": {}}]}+ ids, mask = _encode(tok, example, max_len=128)++ assert len(ids) == 128 and len(mask) == 128+ assert ids[0] == BOS_ID+ assert mask[0] == 0.0+ assert any(m == 1.0 for m in mask)++ _, target = render_example(example)+ assert sum(1 for m in mask if m == 1.0) == len(tok.encode(target)) + 1+++def test_load_jsonl_shapes_and_skips_invalid(tok, tmp_path):+ from needle.model.finetune import load_jsonl++ path = tmp_path / "data.jsonl"+ rows = [+ {"tools": [], "query": "a", "answers": []},+ {"tools": [], "query": "b", "answers": []},+ {"tools": [], "reasoning": "no query here"},+ ]+ with open(path, "w") as handle:+ for row in rows:+ handle.write(json.dumps(row) + "\n")+ handle.write("\n")++ seqs, masks = load_jsonl(str(path), tok, max_len=32)+ assert seqs.shape == (2, 32)+ assert masks.shape == (2, 32)+ assert seqs.dtype == np.int32+ assert masks.dtype == np.float32diff --git a/tests/test_tools.py b/tests/test_tools.pynew file mode 100644index 0000000..82604dc--- /dev/null+++ b/tests/test_tools.py@@ -0,0 +1,109 @@+import typing++from needle import tool, Field+from needle.agent.tools import build_schema, pydantic_schema, _is_pydantic_model+++def test_basic_schema_types_and_required():+ @tool+ def add(a: int, b: int) -> int:+ "Add two numbers."+ return a + b++ schema = add._needle_tool+ assert schema["name"] == "add"+ assert schema["description"] == "Add two numbers."+ assert schema["parameters"]["properties"]["a"] == {"type": "integer"}+ assert set(schema["parameters"]["required"]) == {"a", "b"}+++def test_defaults_are_optional():+ def f(city: str, units: str = "metric"):+ pass++ schema = build_schema(f)+ assert schema["parameters"]["required"] == ["city"]+ assert "units" in schema["parameters"]["properties"]+++def test_literal_list_and_dict_types():+ def f(mode: typing.Literal["fast", "slow"], items: list, meta: dict):+ pass++ props = build_schema(f)["parameters"]["properties"]+ assert props["mode"] == {"type": "string", "enum": ["fast", "slow"]}+ assert props["items"]["type"] == "array"+ assert props["meta"] == {"type": "object"}+++def test_typed_list_items():+ def f(tags: typing.List[int]):+ pass++ props = build_schema(f)["parameters"]["properties"]+ assert props["tags"] == {"type": "array", "items": {"type": "integer"}}+++def test_optional_annotation_not_required():+ def f(a: str, b: typing.Optional[int] = None):+ pass++ schema = build_schema(f)+ assert schema["parameters"]["required"] == ["a"]+++def test_field_constraints_and_docstring_args():+ def f(temp: int = Field(description="temperature", ge=0, le=100),+ name: str = Field(default="x", pattern="^[a-z]+$", min_length=1)):+ """Set the thing.++ Args:+ temp: the temperature in C+ """++ schema = build_schema(f)+ props = schema["parameters"]["properties"]+ assert props["temp"]["minimum"] == 0 and props["temp"]["maximum"] == 100+ assert props["temp"]["description"] == "temperature"+ assert props["name"]["pattern"] == "^[a-z]+$"+ assert props["name"]["minLength"] == 1+ assert "temp" in schema["parameters"]["required"]+ assert "name" not in schema["parameters"].get("required", [])+++def test_docstring_description_falls_back_to_args():+ def f(city: str):+ """Look up weather.++ Args:+ city: the city to look up+ """++ props = build_schema(f)["parameters"]["properties"]+ assert props["city"]["description"] == "the city to look up"+++def test_pydantic_model_schema():+ import pydantic++ class Weather(pydantic.BaseModel):+ "Weather query."+ city: str+ units: str = "metric"++ assert _is_pydantic_model(Weather)+ schema = pydantic_schema(Weather)+ assert schema["name"] == "Weather"+ assert "city" in schema["parameters"]["properties"]+ assert schema["parameters"]["required"] == ["city"]+ assert schema["description"] == "Weather query."+++def test_tool_decorator_preserves_callable():+ @tool+ def greet(name: str) -> str:+ "Greet someone."+ return "hi " + name++ assert greet("bob") == "hi bob"+ assert greet._needle_tool["name"] == "greet"