Skip to content

v0.1.0

Choose a tag to compare

@MorrisZJ MorrisZJ released this 26 Sep 20:55
· 21 commits to main since this release

Version 3 of the method: a closed-form head at a fixed depth, routing, label-free adaptation, a packaged demo, and a tree that
carries only the shipped code and the result JSON a doc cites (docs/migration_v3.md lists everything removed).

  • L2: closed-form per-question heads on the hidden state, at two thirds of the depth. Decider.fit_head(question, states, labels) (or calibrate(..., level="L2")) runs one forward of the labelled states and solves a shrunk-LDA or ridge head on the last-position hidden state; the block it reads, the head kind and the temperature are chosen by out-of-fold NLL. decide(..., level="L2") then sends one prompt per state through a forward that stops at that block (HFBackend.hidden_states_to, bit-exact against the plain forward in fp32, scripts/exit_parity.py) and returns calibrated probabilities with blocks_executed in the diagnostics; require="L2" is enforced like the other levels. Artifacts round-trip through export_artifacts / load_artifacts / load_artifact (refused on another model or question layout). On LocalLLaMA/typed-decisions with 300 labels per question: Qwen3-1.7B 0.730 at 64% depth, Qwen3-4B 0.786 at 67%, Qwen3-8B 0.771 at 67% (L1: 0.499 / 0.567 / 0.648; Jev published 0.727), pooled ECE 0.03-0.05, at 0.68x the batched time of one plain forward on the 8B; Qwen3-30B-A3B 0.799 at 83%, Qwen3-32B 0.798 at 81% (docs/results_exit.md, from bench/results_exit/2026-09-22/). Needs the transformers backend. docs/method_v3.md, docs/jev_mode.md, docs/levels.md, docs/research_log.md.
  • L2 follows its question across wordings and listing orders. Decider.route(q) serves a question from its exact head, else from the head of the same kind and option texts under another wording, else (heads fit on random listing orders) from the head of the same option set in another order; Decider(adapt="routed") (default) re-estimates a routed head's feature mean and scale from the unlabelled states the question is asked on (30 by default, the current batch included), which on Qwen3-8B takes a reworded question from 0.65-0.70 (head as is) to 0.74-0.75 with 30 unlabelled states (0.74-0.76 with 300) against 0.77 for a labelled refit (bench/results_paraphrase/2026-09-22/Qwen__Qwen3-8B.paraphrase.b24.json; the 4B goes 0.63-0.68 to 0.74-0.75, Qwen__Qwen3-4B.paraphrase.b24.json; research log entry 13); fit_head(listing="auto") fits on random listing orders up to 8 options (flip under reversal 0.07 instead of 0.18, <model>.order.json) and on the canonical order above (random listings cost the 20-way bench heads 6-18 points in the artifact builds, entry 13); level="auto" picks L2 / L1 / L0 per question. Diagnostics: routed_from, reordered, adapted, adapt_n, listing.
  • Closed-form distillation: bench.synth_states writes new cases per workflow from real exemplars (Qwen3-8B, thinking off), bench.distill_heads labels them with a teacher's shipped heads and solves student heads on gold plus teacher-labelled states (hard or soft targets); the 32B's heads lift the Qwen3-1.7B from 0.730 to 0.760 on typed-decisions (95% CI on the gain [+0.015, +0.049]), the 4B and 8B do not move (bench/results_distill/2026-09-22/Qwen__Qwen3-32B.distill_heads.fit.json, entry 14).
  • Shipped heads: scripts/build_heads.py fits and validates a model's heads for the 20 typed questions and the three bench tasks through the user path and writes anyjev-heads/<model>.json (with per-question validation, the agreement with the study caches, and env). The head arrays are stored as base64 float32 (anyjev.heads.encode_array, exact, about ten times smaller than number lists): 1.8-4.4 MB per model, 13.6 MB for the five; LinearHead.from_dict and load_artifacts read the list format too, and scripts/compact_heads.py converts in place after a bit-exact round-trip check.
  • Demo: python -m demo.jev_mode (demo/jev_mode.py; not in the wheel). --backend fake runs in seconds on CPU with no download: raw / L0 / L2 on a synthetic model whose hidden state carries a planted option code, then the same question reworded (routed, then recentred on unlabelled requests) and re-listed, fewer labels, and an artifact export / reload; the default --backend hf runs the shipped heads on LocalLLaMA/typed-decisions (Qwen3-4B on a GPU, Qwen3-1.7B on a CPU) (L2 against L0 on the held-out decisions, the rewording, a head from 50 labels, the round trip) and --json writes every printed number with the environment; --state-file + --question decides one state of yours with a shipped head or, with --labels-file, a head fit on the spot. For the fake walkthrough FakeBackend gains two default-off knobs, logit_noise and wording_shift; Decider._features falls back to a full forward when the backend cannot stop early (older transformers, scaled embeddings) and says so in the diagnostics. Tests on the fake backend in tests/test_demo_jev_mode.py.
  • Online label collection and persistence. Decider.observe(question, state, label, fit_at=30, refit_factor=2.0, **fit_kwargs) records a labelled state and solves the question's L2 head itself once fit_at observations exist (never below max(8, 2K)), re-solving each time the count grows by refit_factor (30, 60, 120, ...); it returns the artifact dict on the call that (re)solved a head, else None, and with level="auto" the question answers at L0 until then and at L2 afterwards; Decider.observations(question) returns the recorded (states, labels). export_artifacts(include_observations=False) now also writes the label-free adaptation statistics of every routed question (adaptation: per question key, sum / sumsq / n, arrays in the compact format) and, on request, the observations; load_artifacts restores both, so a restarted decider answers a reworded question adapted from its first request. python -m demo.jev_mode --backend fake --lifecycle (also --backend hf --questions <workflow.qname>, with --stream and --fit-at) plays this through: day 0 at L0, labels arriving one at a time until the head solves itself at 30 (then 60, 120), a rewording served by the same decider and recentred after 30 requests, then export / restart / load with the statistics and observations restored (on the synthetic model, numbers planted: L0 0.86 on day 0, L2 0.98 at the 30th label, the rewording 0.47 as is and 1.00 recentred, probabilities identical across the restart to floating-point precision, max |dp| under 1e-50). Tests in tests/test_decider_fake.py and tests/test_demo_jev_mode.py.
  • Research code behind L2, all replaying float16 feature caches on CPU: anyjev/heads.py (diff-means / LDA / ridge / RRR solvers, fit_head), bench/pools.py + bench/extract_pools.py (the block-loop feature caches every study replays; the former bench.universal_study --extract-only), bench/exit_study.py (accuracy versus depth, logit lens baseline), bench/labels_study.py (label-efficiency curve), bench/jev_mode_table.py (depth chosen on calibration data only), bench/exit_latency.py (ms per decision by depth), bench/paraphrase_study.py (wording and listing order, adaptation), bench/distill_heads.py. The question-agnostic head, the confidence-gated early-exit cascade and distillation from a 32B teacher's zero-label answers were tried, closed as negative results (research log entries 1 / 3 / 9 / 11, 4 / 10, 7) and their code removed; the JSON of all three is kept: bench/results_universal/, bench/results_heads/, bench/results_distill/, and bench/results_exit/2026-09-22/<model>.cascade.json (the cascade tables are in research log entries 4 and 10). Block-loop feature extraction in HFBackend (_prepare / _run_layers, hidden_states_to with max_layer and a restricted logit lens), option-line spans in anyjev/readout.py, planted hidden states in FakeBackend.
  • Tree: result directories no shipped doc or table generator cites were dropped (bench/results_v01/2026-09-21, results_typed_v01/2026-09-21, results_nanojev/2026-09-21, results_cf, results_distill/labels, handoff/games/superseded), internal drafts under docs/ removed, docs/diag_l0_output.txt regenerated from the directories docs/when_l0_helps.md names, and the offline prior study replayed on the committed dumps (230 units). docs/migration_v3.md has the full list and the renamed commands.
  • Bench (maze, a negative result so far): bench.games.maze + bench.run_maze play a seeded grid maze on raw / L0 / L1 P(open) answers with full trajectories, scripts/make_maze_gif.py replays them; on Qwen3-8B no readout beats blind trying yet. Status and next steps (snake, ViZDoom) in handoff/games/HANDOFF.md.
  • Demo: two games as decision benchmarks with a built-in oracle (demo/games/, python -m demo.games.twenty48, python -m demo.games.minesweeper). 2048 is a 4-way choice under randomness scored by a depth-2 expectimax (oracle agreement, regret, flip under option reversal, ECE of the move probabilities); Minesweeper asks one noul per candidate cell and compares the model's P(safe) with the exact posterior enumerated from the revealed numbers (safest-pick rate, avoidable deaths, |P - exact|). Both play the same seeds under raw, L0 and L1 (temperature fit on oracle- or self-play-labelled decisions, no human labels), draw a live text frame per turn, and run on the synthetic biased backend without a GPU (--backend fake), which is how the tests exercise them.
  • From the second-run reproduction (repro_check, 2026-09-22; ours, from a clean checkout on the same GPU host): L1 artifacts now freeze the prior they were fit with (prior, prior_strength, prior_method, n_calib in the artifact), so calibration is a pure function of its calibration set and L1 decisions no longer depend on decider history; every result JSON records batch_size, dtype, backend, shared-prefix mode, the anyjev version and the git commit; the maze providers compute edge_majority and mean_p_true themselves, pin the NanoJev commit and the episodes file hash, and drop per-cell observations unless --keep-observations.
  • Second pass of the same reproduction, on the fixed code: content-free probes are now scored in their own forward call. Before, the first time a Decider saw a question the probe prompts were batched together with the real states, which shifted every batch boundary and moved bf16 logits at the third decimal; a fresh Decider and a used one therefore scored the same states slightly differently (0.0008 in the fitted temperature), and record_content_free, a bench diagnostics flag, changed the numbers. Now neither does; the test suite checks that the real-state prompts handed to the backend are identical with and without the flag.
  • Bench: the L1 flip rate is now the disagreement of two independently calibrated deployments. bench.run used to load the original artifact onto the reversed-option question ("same temperature, reversed layout"); with the prior frozen inside the artifact that put a prior fit on one option order onto the other, which inflated L1 flip by up to 0.15 on the weakest model without touching accuracy. The reversed layout is now calibrated on the same split (temperature_reversed is recorded), and Decider.load_artifact refuses an artifact whose prior was fit on a different question layout (temperature-only artifacts from 0.0.2 still load anywhere).
  • Bench: reversed_question reverses centers alongside the options for score questions with explicit levels; before, the reversed layout silently rescaled the value (found by the reproduction check; the published tasks have no such question).
  • Bench tables regenerated under the shipped code (bench/results_v01/2026-09-22, results_typed_v01/2026-09-22, results_nanojev/2026-09-22; the 2026-09-21 runs are no longer in the tree). L0 typed cells are unchanged; bench raw and L0 cells move within bf16 batch-composition noise; L1 cells change by design: the L1 prior is now estimated from the calibration set alone rather than from every state the decider had seen, which improves ECE on most cells and costs up to two AURC points on the smallest models at 200 calibration items.
  • Default change: the batch prior is applied at strength 0.75 (Decider(prior_strength=...), an exponent on the prior before dividing). Chosen by replaying every prior rule offline on 230 (model, question) units (bench.prior_study over the --dump-items dumps in bench/results_dump and bench/results_typed_dump): best mean gain, smallest loss on skewed label marginals (docs/when_l0_helps.md). prior_strength=1.0 restores the previous behaviour; the bench tables were regenerated with the new default.
  • Cost: HFBackend.score_shared computes a state's prefix once and scores the K permutation suffixes against the cached KV; the Decider routes to it automatically when the backend has it, a state has at least 3 permutations and the prefix is at least shared_min_prefix_tokens (256) long. Exact to 3e-4 nats against full prompts (fp32 parity script scripts/shared_prefix_parity.py). The backend protocol gains this one optional method.
  • Cost: HFBackend computes logits only at the last position (logits_to_keep=1), which removes the full-vocabulary projection of every earlier position.
  • Cost: Decider(adaptive_shifts=True) (opt-in) reads cyclic shifts one at a time in a spread (van der Corput) order, which keeps accuracy within 0.4 points of the full cycle at 2.6x to 3x fewer prefills where consecutive order lost 3 points (docs/results_adaptive.md), and stops when every shift read so far agrees on the winner after prior correction and the running margin clears adaptive_margin; bench.run --adaptive and bench.adaptive_table measure what it costs in accuracy, ECE and flip rate.
  • Bench: bench.latency measures milliseconds per decision for raw and L0, batch and single-request, on never-seen states, for the transformers backend (shared prefix off and on) and vLLM.
  • Contract: decide(..., require="L1"), Decision.require(level) and DecisionSet.require(level) raise LevelError when a result does not carry the asked level.
  • Bench: bench.run_typed records per-question metrics with gold-label skew; bench.diag_l0 correlates the L0 gain with label-free predictors across every (model, question) point.
  • L2 on vLLM, and depth as a checkpoint. VLLMBackend gains hidden_states: an embed-task server whose pooler is told pooling_type="LAST", normalize=false, softmax=false returns the final block's state at the last position, which is exactly what a closed-form head reads, so an L2 deployment is a pooling server plus a few kilobytes of head and needs no logits at all. Against transformers on Qwen2.5-7B the vectors agree at cosine 0.999935, and all four fit/serve combinations land within half a point on banking20 (fit local serve vLLM 0.830, fit vLLM serve local 0.820, both 0.825-0.830 on their own runtime; same head on both runtimes, 99.0% identical answers, mean |dp| 0.0011), so an artifact fit on a workstation is the artifact the server runs. anyjev/truncate.py writes a model's first n blocks to an ordinary checkpoint -- config, kept tensors, embeddings, final norm, head -- so the depth knob is a smaller model that vLLM, transformers, a quantiser and a GGUF converter all take unchanged, rather than a property of one code path (vLLM's own hf_overrides builds fewer layers but its weight loader still walks every tensor in the checkpoint and dies on the first one it cannot place). python -m anyjev.pipeline <model> runs the whole thing: truncate, serve, fit a head from your labels, measure accuracy, ECE and milliseconds per decision on held-out states, tear the server down, print a table with a row per depth.
  • Measured, on banking20 with Qwen2.5-7B through vLLM (bench/vllm_stack.py, bench/vllm_features.py, both in the tree): truncating to 18 of 28 blocks is two accuracy points better (0.850 against 0.830; the second-run reproduction check reproduced both) and faster -- 1.21x on one question per state and 1.33x on five in our runs, 1.42x and 1.39x in the reproduction's -- because a middle block is a better feature space for a linear head than the final one, where the remaining blocks are converting the answer into token space. Prefix caching is a generate-server effect: an identical 1.6k-4k-token prompt sent again costs 1.86x-2.37x less there (the reproduction measured 1.88x). On the embed server, which is the L2 path, vLLM 0.7.0 does not reuse the cache at all -- 1.01x-1.06x for the same prompt sent again -- so --enable-prefix-caching is not in the L2 serve command in the README, and the claim an earlier version of this entry made of 1.49x on the multi-question L2 shape was a single-pass timing on that path and does not survive repetition; withdrawn. FP8 is not recommended: across our runs and the reproduction's it bought 1.2x-1.5x on one question per state, anywhere from 0.95x to 1.11x on five, and cost those two accuracy points in ours (0.850 to 0.830). The levers do not multiply; the measured best is 1.5x, not the 3x their product predicts, because they compete for the same arithmetic.
  • Fixes from the second-run reproduction check of a59a69e..149e7f7 (Tianze Yang, 2026-09-24), which reproduced the accuracy numbers and the truncation speed-up and caught the rest: the prefix-caching and FP8 claims above are restated to what reproduces; the two bench scripts the entry cited but the tree did not contain now ship; anyjev.pipeline truncates to floor(2/3) of the blocks -- 18 of 28, the depth the numbers were measured at -- where it rounded to 19; and --keep-truncated pointing at a directory that does not exist yet no longer fails on the full-depth pass, which never created it before opening the server log inside it.
  • Fix: HFBackend could not be constructed at all after pip install anyjev[hf]. It passed device_map=device to from_pretrained, and transformers requires accelerate as soon as that argument is present, which the hf extra does not install -- so every device failed, cpu included, with ImportError: Using 'low_cpu_mem_usage=True' or a 'device_map' requires Accelerate. A single device is a placement rather than a sharding plan, so the model is now loaded plain and moved with .to(device); probabilities are bit-identical (max |dp| 0.000e+00 at raw and L0 on Qwen2.5-0.5B-Instruct) and the load time is unchanged (1.06x over alternated runs, i.e. noise). Real sharding stays available as device_map= in the new **model_kwargs, and is then left to transformers. This also removes the Apple Silicon segfault the report opened with: on transformers 5.17 / MPS the device_map weight-materialisation path died with SIGSEGV and no traceback. Reported by @lws2004 in #5, with the working change already identified.
  • Fix: the transformers backend assumed the backbone attribute is called .model, which is true of Llama and Qwen and false of GPT-2 (.transformer), so score_shared raised AttributeError on those families -- and because the Decider routes to the shared-prefix path automatically above 256 prefix tokens, such a model worked on short states and crashed on long ones. The backbone is now resolved through transformers' own base_model_prefix. Testing that on GPT-2 surfaced a second one: those models return the legacy tuple rather than a Cache object, which _repeat_cache could neither repeat nor convert; it now handles both. Also reported by @lws2004 in #5. tests/test_hf_loading.py covers the load path and the backbone without needing torch, and the shared prefix end to end on a tiny GPT-2.
  • Fix: L2 decisions raised on transformers 5. HFBackend._prepare called the mask builders with input_embeds= and cache_position=; transformers 5 renamed the first to inputs_embeds and dropped the second, so every block-loop forward failed with create_causal_mask() got an unexpected keyword argument. The call is now assembled from the builder's own signature, so one code path serves 4.53+ and 5.x. Reported, with the root cause already identified, by @efronh in #4.
  • Fix: anyjev.__version__ reported 0.0.1 in the released 0.0.2 package. The version now comes from the installed package metadata, with a test that fails if it drifts from pyproject.toml.
  • Readout: score questions fall back to letter labels when the tokenizer cannot emit digits as single tokens (Mistral's sentencepiece splits "1" into a space piece plus "1"). resolve_labels picks the label set per tokenizer and the prompt shows the same set.
  • Bench: bench.preflight checks tokenizers and prompts without downloading weights; bench.sweep runs many models across many GPUs; bench.models_table prints one row per model.
  • Bench: seven small open models (1.7B to 8B, six architectures) on all tasks. Results in bench/results_small*/, write-up in docs/results_small_models.md, README section added.
  • Packaging and CI: version 0.1.0; the hf extra requires transformers>=4.53 (the L2 block loop uses transformers.masking_utils); CI lints demo/ and scripts/ as well (ruff check anyjev bench tests demo scripts).
  • Docs: docs/method_v3.md (the method end to end, three flow diagrams), the two diagrams in both READMEs (the fit-then-adapt loop, the deployment lifecycle), ROADMAP.md as a checkbox list with a definition of done per item, docs/migration_v3.md.

pip install "anyjev[hf]"