A computer, compiled into the weights of a language model. An exact CPU inside Qwen3.5-4B, with Gated DeltaNet state as RAM.
Sync q35-int 496d591 (fraction printing, release checks); running.md cleaned for publication
Divyansh Agrawal652ef65967a8
diff --git a/README.md b/README.mdindex b15d831..14a5e1d 100644--- a/README.md+++ b/README.md@@ -67,9 +67,10 @@ lookup tables, and every value stays exact in bf16.tool-call tags. When a calculation is complete they run it and print the answer as normal text.Qwen's state is frozen while the computer runs.-**What it can do.** The computer is about 0.7M nonzero weights covering add, subtract, multiply, exact division,-signed and decimal numbers, mod, gcd, and whole expressions with brackets. Stock checkpoints give-every layer the same width, so the merged model is 14 GB vs 9.3 GB for base Qwen. The extra is+**What it can do.** The computer is about 0.7M nonzero weights covering add, subtract, multiply, exact division+(reduced fractions when it doesn't terminate), signed numbers, mod, gcd, and whole expressions with+brackets, powers and decimals. Stock checkpoints give+every layer the same width, so the merged model is 14.65 GB vs 9.3 GB for base Qwen. The extra isalmost all zeros, so the download is about the same size.### Gated DeltaNet as RAMdiff --git a/chipformer/q35/evals.py b/chipformer/q35/evals.pyindex e80dac0..3511f4d 100644--- a/chipformer/q35/evals.py+++ b/chipformer/q35/evals.py@@ -207,7 +207,7 @@ def expr_value(s: str):s = re.sub(r"\d+(?:\.\d*)?", lambda m: f"Fraction('{m[0]}')", s).strip()try:return eval(s, {"Fraction": Fraction}) # noqa: S307 (digits and operators only)- except (ZeroDivisionError, SyntaxError, TypeError, ValueError, OverflowError):+ except (ZeroDivisionError, SyntaxError, TypeError, ValueError, OverflowError, AttributeError):return None@@ -754,7 +754,8 @@ def inline_fires(text: str, pred) -> list[dict]:if ex and not single and (re.search(r"[()^{}]|\d\.\d", ex[1]) or len(re.findall(r"[+\-*/×÷−]|\\times|\\cdot|\\div", ex[1])) >= 2) and (- v := expr_value(ex[1])) is not None:+ v := expr_value(re.sub(r"^\s*\n\s*[-−](?=\s)", "", ex[1]))) is not None:+ # (a list's "- " is one token with the newline: no sign)t = value_text(v)exact = shown.startswith(t)machine = t if exact else shown@@ -1054,7 +1055,8 @@ def run(args) -> None:torch._inductor.config.shape_padding = False # its padded weight copies don't fit 24 GB- max_len = args.max_len or (max(map(len, prompts)) + budget + (3072 if chip else 1024 if think else 512))+ # (chip room: a fraction or a whole expression runs 1-15k trace tokens)+ max_len = args.max_len or (max(map(len, prompts)) + budget + (8192 if chip else 1024 if think else 512))max_len = -(-max_len // 1024) * 1024if args.fast and chip: # exact: chip layers read only their nonzero blocks, and steps onfrom chipformer.q35 import fast # chip-token inputs skip Qwen's (no-op) layersdiff --git a/chipformer/q35/merge.py b/chipformer/q35/merge.pyindex a3fa5ce..bb28a63 100644--- a/chipformer/q35/merge.py+++ b/chipformer/q35/merge.py@@ -23,6 +23,7 @@ OUT_ROWS = re.compile(r"(out_proj|o_proj|down_proj)\.weight$|visual\.merger\.linWIDE_NORMS = re.compile(r"(input_layernorm|post_attention_layernorm)\.weight$|language_model\.norm\.weight$")IM_START = 248045 # <|im_start|> in Qwen3.5's tokenizer+ENDOFTEXT = 248044 # <|endoftext|>def load(path):@@ -189,6 +190,19 @@ def store_row_features(c, lay, v0: int) -> dict[int, torch.Tensor]:return out+def bios_meta() -> dict:+ """The BIOS the weights expect (its entries are compiled in): the boot record is+ trace.boot_tokens(Chip8(bcd.ROM, bcd.QUIRKS).cells), offset by chip_token_offset."""+ import hashlib++ from chipformer.q35.lib import bcd++ image = bytes(bcd.ROM) + b"".join(d for _, d in bcd.ROM.segments)+ return {"sha1": hashlib.sha1(image).hexdigest()[:10], "rom_bytes": len(bcd.ROM),+ "segments": [[a, len(d)] for a, d in bcd.ROM.segments], "ops": bcd.OPS,+ "quirks": list(bcd.QUIRKS)}++def build_merged(src, dst, hidden: int | None = None, m: int | None = None,mute_qwen: bool = True, overlay: bool = True, store: bool = False):"""Write Qwen3.5 + the CHIP-8 circuit as one checkpoint ("v2" layout); returns (circuit,@@ -340,14 +354,16 @@ def build_merged(src, dst, hidden: int | None = None, m: int | None = None,# After the circuit prints a tool response inside the assistant turn, Qwen sometimes opens a# new turn (<|im_start|>user ...) instead of going on. Qwen never writes <|im_start|> in its# own output, so the merged model bans it; the circuit never predicts it either.- gen["bad_words_ids"] = [[IM_START]]+ # (and <|endoftext|>: after a printed tool response Qwen sometimes ends with it instead of+ # answering; it ends its turns with <|im_end|>, which stays the EOS)+ gen["bad_words_ids"] = [[IM_START], [ENDOFTEXT]]gen_path.write_text(json.dumps(gen, indent=2))meta = {"layout": "v2", "chip_token_offset": v0, "chip_vocab": spec.VOCAB_SIZE,"chip_layers": n_chip, "qwen_layers_from": n_chip, "hidden": hidden,"chip_dims_offset": d0, "ballast_dims": m, "circuit": c.stats(),"slots": alloc.n_slots, "overlay_slots": len(alloc.final_over),"overlay": plan.summary() if plan else None, "muted": mute_qwen,- "text_ids": {str(k): v for k, v in text_ids.items()}}+ "text_ids": {str(k): v for k, v in text_ids.items()}, "bios": bios_meta()}if store:from chipformer.q35 import store_q35diff --git a/docs/benchmarks.png b/docs/benchmarks.pngnew file mode 100644index 0000000..1b3457fBinary files /dev/null and b/docs/benchmarks.png differdiff --git a/docs/figures/benchmarks.py b/docs/figures/benchmarks.pynew file mode 100644index 0000000..4f21363--- /dev/null+++ b/docs/figures/benchmarks.py@@ -0,0 +1,40 @@+"""Benchmark bar chart: base Qwen3.5-4B vs Qwenputer vs base + Python tool.++python docs/figures/benchmarks.py -> docs/benchmarks.png+"""++from pathlib import Path++import matplotlib.pyplot as plt+import numpy as np++plt.rcParams.update({"font.family": "sans-serif", "font.sans-serif": ["Helvetica", "Arial", "DejaVu Sans"]})++sets = ["NUPA\n(3-20 digits)", "DeepMind\ndiv_big", "DeepMind\nmul_big", "DeepMind\n6 sets pooled",+ "DeepMind clean\nadd / mul"]+base = [48.6, 77, 66, 80.8, 69.5]+qp = [100.0, 97, 93, 92.3, 99.0]+tool = [100.0, 85, 91, 94.2, 98.5]++x = np.arange(len(sets))+w = 0.26+fig, ax = plt.subplots(figsize=(11, 4.6))+cols = {"base": "#b9b9b9", "qp": "#7b6cf0", "tool": "#e3a76f"}+b1 = ax.bar(x - w, base, w, color=cols["base"], label="Qwen3.5-4B")+b2 = ax.bar(x, qp, w, color=cols["qp"], label="Qwenputer (computer in the weights)")+b3 = ax.bar(x + w, tool, w, color=cols["tool"], label="Qwen3.5-4B + Python tool")+for bars in (b1, b2, b3):+ for r in bars:+ ax.text(r.get_x() + r.get_width() / 2, r.get_height() + 1.2, f"{r.get_height():g}",+ ha="center", va="bottom", fontsize=10.5, color="#333")+ax.set_xticks(x, sets, fontsize=11.5)+ax.set_ylabel("accuracy (%)", fontsize=12.5)+ax.set_ylim(0, 112)+ax.set_yticks([0, 25, 50, 75, 100])+for s in ("top", "right"):+ ax.spines[s].set_visible(False)+ax.legend(frameon=False, fontsize=11, loc="upper center", ncol=3, bbox_to_anchor=(0.5, 1.13))+ax.tick_params(axis="y", labelsize=11)+out = Path(__file__).resolve().parents[1] / "benchmarks.png"+fig.savefig(out, dpi=200, bbox_inches="tight", facecolor="white")+print(out)diff --git a/docs/running.md b/docs/running.mdindex a04178b..af7fd7b 100644--- a/docs/running.md+++ b/docs/running.md@@ -106,6 +106,60 @@ end.| `text_ids` | The text classes the circuit reads and prints, by Qwen token id || `bios` | The BIOS the weights expect: sha1, size, segments, entry points |-## Measured (q35-inline, A10G)+## Release checks (A10G 24 GB, 2026-10-19)-Filled in by the release check (see below).+**The checkpoint.** [divagr1925/Qwen3.5-4B-Qwenputer](https://huggingface.co/divagr1925/Qwen3.5-4B-Qwenputer).+- Size: 14.65 GB in 7 shards.+- Contents: config, tokenizer, `chat_template.jinja`, `generation_config.json`, `chipformer.json`,+ LICENSE, preprocessor configs.+- A text-only variant (13.98 GB, `Qwen3_5ForCausalLM`) can be exported with `python -m chipformer.q35.textonly`.+- Built from `q35-int` (see the commit below) with `python -m chipformer.q35.merge <Qwen3.5-4B>+ --out q4-int` (overlay on), then `python -m chipformer.q35.textonly`.++**Shape.**+- Hidden 3200, ballast 50.+- 12 chip layers + 32 Qwen layers.+- Circuit: 3222 dims, 84 heads, 28,259 MLP units.+- 516 slots of its own, 1129 overlaid on Qwen's dims.+- BIOS sha1 `5e885286e8` (3072 B at 0x200, plus 174 B at 0x0E0).++**Selftest: 17 tool calls, 0 wrong.** Calls cover add, sub, mul and signed mul, div (decimal,+fraction, signed), mod, gcd and calc, including a negative calc.++**Results** (fp + tc, BatchDecoder `--fast`, greedy):++| Run | Correct | Computer results exact |+|---|---|---|+| Tool mode (`merged_nb_ne_fp_tc`), synthetic arith n=20 | 20/20 | 33/33 tool calls, 7/7 inline fires |+| Inline (`merged_inline_nudge_fp_tc`), arith n=20 | 15/20 (4 stopped at the cache length) | 72/72 fires |+| Tool mode, DM mul_big n=10 | 7/10 (4 cache stops) | 6/6 calls, 22/22 fires |+| Inline + `nudge3`, DM mul_div_multiple_longer n=10 | 3/10 (7 cache stops at 16k) | see the IR replay |+| Whole expressions (`nudge4`), DM mul_div_multiple_longer n=10 | 4/10 (2 cache stops at 24k) | 45/45 scored fires |++**IR replay** (the circuit's IR == the reference BIOS, on every computer-owned position of the+DM records above): 30 records, 177,816 positions, 0 mismatches, 0 stray chip tokens.++**Notes:**+- The DM division sets are short: these runs are 10 problems each.+- Most losses there are cache-length stops. A non-terminating division now runs gcd to print+ `p/q`, which costs 1-9k trace tokens (median 3.6k) instead of about 600.+ - With tc, Qwen doesn't see those tokens, but the static cache still holds them.+ - Use `--max-len 32768` or more on these sets, on a GPU with room: an A10G ran out of memory+ at 32k with the `--fast` CUDA graphs, and `--chip-per-full 0` turns those off.+- On a few multi-operation windows (markdown lists, `1.` list numbers), the scorer's+ attribution of an inline fire to an expression is heuristic. The IR replay is the exactness+ check.+- Not run for this release: text KL vs base, GSM8K and MMLU.++**Tests** (CPU, one file at a time):+- The q35 suite passes: ir, ir_vheads, mute, numerics, macros 19, expr 47, v2, chip8, inline 113.+- `test_q35_overlay` passes 5/5 (noisy-IR leak checks). The merged-checkpoint overlay test was+ run on the GPU and passes.+- `test_q35_store`: 10/11. One store-only failure, `test_circuit_with_arithmetic`: with+ `--store`, the store's tool response lacks the tool-response thinking tail (owner bits at its+ end). The store is optional and not in this checkpoint.++**Not in this release:**+- v17 (decimal operands for the single-op path). Its BIOS (≈550 B) doesn't fit the 4 KB next to+ v18's evaluator. Decimals work through the expression evaluator instead.+- The maths library (pow, sqrt, logs, …).diff --git a/tests/test_q35_expr.py b/tests/test_q35_expr.pyindex d4b43f8..ffc804a 100644--- a/tests/test_q35_expr.py+++ b/tests/test_q35_expr.py@@ -120,7 +120,8 @@ def test_eval_random():assert v == got, (text, v, body)assert n > 250 and errors < n // 4, (n, errors)lengths.sort()- assert lengths[len(lengths) // 2] < 8000, lengths[len(lengths) // 2]+ # (a quotient that does not end runs gcd for its reduced fraction)+ assert lengths[len(lengths) // 2] < 12000, lengths[len(lengths) // 2]def scan(tokens):