Skip to content

Release 5.4.0 - #66

Merged
a9lim merged 293 commits into
mainfrom
six
Oct 31, 2026
Merged

a9lim merged 293 commits into
mainfrom
six

Conversation

@a9lim

@a9lim a9lim commented Oct 31, 2026

Copy link
Copy Markdown
Collaborator

Drowse 5.4.0: a full restructure of the library, plus lens format v7, typed request errors, faster steering and a tidier dashboard. 6.0 stays reserved for the S-lens/mid-lens work and the Ledger redesign.

What changed

  • Layered packages. drowse.core and drowse.io are now 17 packages in a fixed layer order (base, geometry, model, store, steering, readout, lens, sae, generation, fit, loom, session, and the CLI, server, web and notebook fronts). tests/invariants/test_layering.py enforces the order, type-only imports included.
  • The session is a facade. drowse/core/session.py (11,015 lines) became drowse/session/session.py (1,754 lines) over collaborators that own their state: engine, batch, registry, neutral baseline, read plane, one token replay for geometry, lens and SAE. Nothing outside drowse/session/ reads a session private.
  • Lens format v7. Lenses live under models/<id>/lens/ as local/r and local/j, keyed by kind (J/R/K/S) and site (out/mid). The active-lens file has an output side and an input side. Pre-5.4 homes need python scripts/migrate_lens_v7.py --home DIR once; it relinks the same shard bytes and refits nothing.
  • Typed request errors. Client input raises RequestError (400, text verbatim) or a subclass; a bare ValueError is a broken invariant and answers a scrubbed 500.
  • Faster. Against 5.3 on SmolLM2-360M (MPS), with the 17 default probes attached: unsteered decode +1%, affine steering +6% to +19%, probe-gated +53%, curved % steering +35%, session load −9%, months fit −15%. Resident manifolds and probes now upload as one packed device buffer each (geometry/packing.py).
  • Tests and docs. The suite runs on a real tiny CPU session instead of stubs and is organized by package (4,938 tests). Every package has its own AGENTS.md, and ARCHITECTURE and README were rewritten.
  • Dashboard. Svelte 5.57.2 (5.55.8 can freeze its update scheduler under rapid interaction), lazy drawer loading, the Neurons header link removed, and fixes for the token drilldown's remembered tab and first-open drawer focus. The built dist dropped from 11 MB to 5.2 MB.

Breaking changes

  • Module paths under drowse.core and drowse.io are gone. from drowse import X is unchanged.
  • Removed DrowseSession forwarders: diff_nodes, rewind, clear_history, remove_cast_member, ensure_manifold_loaded, ensure_profile_registered. Use session.tree, session.registry or drowse.loom.diff.node_diff. New: session.joint_logprobs(a, b).
  • Lens artifacts must be format v7 (see above). Manifolds, fits, neutral caches, templates, loom trees, transcripts, archives and SAE artifacts keep their formats and load as-is.
  • Server: an unexpected ValueError is now a 500. CLI: template format and ambiguity errors exit 2 instead of 1.
  • drowse lens fit --standard is now --kind j; lens use takes local:r / local:j.

Verification

Full suite with MPS: 4,928 passed, 8 skipped. Perf gates 2/2. svelte-check 0 errors, 0 warnings. Doc references checked against the code: 0 broken of 6,606. Browser goldens byte-identical. drowse.ai's port (branch six-prep) passes its node, Python and build suites; its remaining e2e failures reproduce on drowse.ai main.

a9lim added 30 commits October 30, 2026 11:38
tree_routes routes every session-lock site through one lock-or-503 helper,
so a lock timeout on joint-logprobs is a 503 instead of running model
forwards beside the generation that holds the lock. The edge-label and
diff routes read LoomNode.steering_expr instead of two inconsistent
hand-rolled fallbacks, and stale route docs are corrected.

Graft is a no-op when it has nothing to add. LoomTree.descendants,
attach_events and messages_for(include_system=) had no non-test caller
and are removed.
The drawer dialog, command palette, loom dialogs, and bottom sheet each
hand-rolled a Tab trap with a slightly different focusable selector and
wrap rule. lib/focusTrap.ts defines a tab stop once (tabIndex >= 0, enabled,
rendered, not inert) and wraps at either end.
PrefixCacheEntry arms rollback on the one cache it owns instead of an
import-time patch of transformers' linear-attention layers (which no longer
matched transformers 5.x's per-state dicts): upstream past recording rewinds
sliding windows and conv states, a snapshot restores recurrent states, and a
static entry rewinds its write counters, so static prefixes survive reuse
instead of being dropped after one generation.
LoomTree.load re-implemented LoomNode.from_dict's token-list checks while
merging the gzip sidecar; it now merges the validated keys and leaves the
type checks to the one node reader, and rejects a malformed nodes list
with a LoomTreeError instead of a TypeError.
A gate naming a probe no family attached left the gate callback with no
monitor keys, so it fell through to scoring the whole roster every token
for a gate that can never fire.  The callback now returns nothing for
those keys and only ever scores planned gate keys or reuses the capture
sink's row.

With that fallthrough gone, nothing shares a geometry reading between
the gate callback and the token tap except the sink row itself, so the
geometry run's step-keyed observe memo and prime_observation are dead:
delete them (and prime_observation from the run protocol), and read the
sink row directly in the token payload.
The unsteered and inverted regen modes compose steering "" (the tiers'
explicit unsteered marker that stops a cast default filling the slot), and
so does a caller's steering=""; the grammar rejects the empty expression,
so every such generation failed with SteeringExprError on a real session,
including the dashboard's default A/B comparison. _generate_core now maps a
blank composed expression to None before preparing the call.
Monitor.history was appended at finalize and cleared on rewind, clear
and restore, but nothing ever read it.  Remove it with the accumulate
flag threaded through score_per_token, score_stack, the session's
incremental/aggregate finalizers and the public score_hidden, and fold
measure_from_hidden into score_single_token.
The installed steering is now a function of the steering stack.  The composer
composes the flattened head into a fresh SteeringPlan (cached by its frozen
entries while the registry objects it read are unchanged) and the
SteeringManager installs it as a unit: compiled offset buffers for a static
pure-push plan, transient hooks otherwise.  clear_all zeroes the offsets.

Fixes:
- An exited steering scope left the compiled offsets live, steering the next
  unsteered generation on the compiled route.
- The generation teardown zeroed the offsets after the scope pop had
  re-installed the outer scope, so later generations ran unsteered.
- A push that failed to compose had already cleared the manager, leaving the
  outer scope's entries on the stack with nothing installed.
- A negative along/onto on a curved % term silently clamped to a no-op; it
  now raises SteeringCompositionError.

Every affine injection (single group, multi-group, compiled offsets) runs one
AffineOp: a rank-1 ablation is a dot plus an in-place addcmul_ (6 aten ops
and 1 full-width temporary per fire, down from 12 and 3).  The three
hand-maintained affine paths, the unreachable subspace_inject fallback and the
tuple-indexed group records are gone; Trigger.BOTH is interned at
registration so equal-but-distinct triggers keep the static path.

Resolution runs once per scope in SteeringComposer.resolve (variant
concretization, artifact loads, projections), replacing resolve_pole_aliases
and the speculative preloads; unknown names raise there instead of being
deferred.  A repeated push/pop of the same expression no longer recomposes:
339 ms -> 0.15 ms on MPS for a 3-term expression over 30 layers at D=2048.

Steering.classified/normalized_entries/SteeringEntries collapse into one
Steering.entries() view.
Each verb group now declares its flags next to its runner as a Verb tree
(drowse/cli/verbs/*), dispatched through set_defaults(func=...). The
1.5k-line parsers.py, the seven hand dispatchers, the runners/__init__.py
monkeypatch barrel, and the _pkg indirection are gone, so building the
parser no longer imports torch (drowse --help: 0.54 s -> 0.08 s).

One error boundary in main maps CliError / DrowseError status / missing
files to a single stderr line and exit code; runners raise instead of
printing and exiting. All narration (startup, model info, progress)
goes to stderr, so every -j payload is one JSON document.

Fixes:
- serve no longer pre-extracts referenced concepts (which authored
  duplicate local/ manifolds and crashed on jlens/ and sae/ atoms); -S
  overrides YAML vectors, is parsed before the model load, and is
  preflighted once through session.steering with an extract hint.
- YAML temperature/top_p/thinking now reach the session GenerationConfig.
- serve keeps the persisted lens selection; it only adopts a source when
  none is selected, and clears a failed trial selection.
- reserved readout namespaces are never treated as HF coordinates.
- push and merge sources resolve existing manifolds cross-namespace.
- compare/why fold :from-<src> and :role-<r> variants.
- transcript replay regenerates each assistant turn under its imported
  parent, with history.
- manifold generate --seed (a dead flag) is removed.
- template score, manifold generate and experiment naturalness no longer
  bootstrap the probe roster; fan grids and naturalness options are
  validated before the model load; serve warms up only with --compile.

Also: --kind {r,j} replaces --relp/--standard on lens fit; the band
layer alias, --base-steering, --namespace on extract and --ridge-scale
on compare are removed; rm requires -y on every lifecycle; ConfigFile is
driven by its dataclass fields and one validator table; config validate
dry-runs ensure_vectors_installed. The store.alignment tests move to
tests/test_transfer_alignment.py and the argparse-tautology tests are
replaced by table-driven parser invariants.
Its re-exports served one test; import from the submodules.
Removes endsOnUserNode (written in four places, read only by the unused
predictedQueueEndOnUserNode), latestLayerScores, isBuiltInHighlightTarget,
formatScoreTooltip, progressMessage, TokenReadoutProvenance, the unused
browser-mode parameter of manifoldSelectorOptions, the constant
sentenceBranchAvailable gate, and the 13 drawers' prop declarations whose
only purpose was an effect that read params. The registry type now admits
prop-less drawers instead.
A % term on a bare :role / :sae / :from manifold reached the loader
unconcretized and always failed as an unsupported variant; it now pins the
unique fitted tensor like vector atoms do.
model/chat.py owns the stop-id set, thinking delimiters, the one
enable_thinking sniff, the logits-cap kwarg, a lazy token-text table and a
bounded render cache. The session builds it at init (and adopts its stop
ids as the model's generation default, which also covers models passed to
DrowseSession directly), replacing four module-global weakref caches,
clear_generation_caches, the eager full-vocab token table (241 ms on
SmolLM2's 49k vocab, about 3 us per new id lazily) and the loader's upward
import of the decode loop.
serve checks the bind address before composing config, adopts the live
lens before preflighting default steering (jlens/ atoms resolve against
it); fan and template score parse -S up front; manifold fit parses
--layers before loading. pack show lists without hashing fitted
payloads. histogram.py's only consumer was manifold why, so its bucketing
moves there.
The monitor fallback and the run-less branches were reachable only from
tests: the session always passes the bound geometry run.
_prepare_capture_batch is the single render/tokenize/pool-index front half:
the per-row fallback for scalar-only test tokenizers, the duplicate
_render_and_tokenize_for_capture, the test-only single-pair
_encode_and_capture_all (now a local helper in test_smoke), the unused
role=/system_msg= knobs and the dead _CAPTURE_BATCH constant are gone. Capture
test tokenizers take batches like HF tokenizers do. The module docstring and
folded_directions docstring describe what the code does now.
LoomDialog.svelte owns the ten dialog kinds (state, background inertness,
focus containment, apply logic, markup, styles); the sidebar opens it
through the bound instance and gets focus and search reveal back through
callbacks. The fan-out strength parser and node-id prefix lookup become
pure, tested helpers in loomCommands.ts. Also drops unused imports left in
the sidebar, api.ts, ws, and the steering store.
geometry/manifold.py held eight jobs in 4.1k lines. It is now:

- domains.py: ManifoldDomain and the Box/Sphere/Klein/RP2/Custom domains,
  spec validation (geodesic() deleted: only tests used it; the
  translate_foot-from-origin tests cover the same paths)
- rbf.py: RbfFitPlan as the one RBF factorization (exact, fixed-lambda,
  GCV via Demmler-Reinsch), eval_rbf, eval_rbf_jacobian and a fused
  eval_rbf_jet; fit_rbf_interpolant, fit_rbf_smoothed, _rbf_saddle,
  _rbf_smoother_matrix and _gcv_select_lambda are gone
- subspace.py: LayerSubspace, pca_basis, fit_affine_subspace and
  fit_curved_subspace (was fit_layer_subspace), both returning LayerFit
  instead of tuples and out-dicts; subspace_share needs a whitener
- manifold.py: the Manifold container with an O(1) is_affine property
  (manifold_is_affine, tangent, jacobian_at, nearest_node_label deleted)
- invert.py, inject.py, tube.py, transfer.py: foot solve, composition and
  the steering kernel, the sigma field, cross-model transfer
- fit/node_stats.py: the model-forward capture driver and the row-spool
  covariance pass, so geometry no longer imports the store

Composition (synthesize_subspace) now runs on CPU fp32 with one batched
Woodbury apply per layer and one packed host-to-device transfer, and
SynthesizedSubspace validates with one host read per device. The curved
kernel computes h + delta.B in reduced space (norm cap included), reuses
fused RBF jets, and the 1x1 Gauss-Newton solve is a scalar division.
LayerWhitener gains _require() (uncovered layers raise WhitenerError, not
KeyError), mahalanobis_norms() and a single-apply mahalanobis_cosine; the
unreachable fp32 legacy guard and the WhitenerError re-export are gone.

fit/naturalness.py no longer crashes on discover manifolds: the behavior
manifold uses the per-model fitted layout, both centroids and trajectories
are read chat-rendered over response positions, and evaluate() is the
experiment entry point the CLI runner now calls.
stage_verify_swap built at <ns>/<name>.staging and backed up to
<ns>/<name>.bak; both names match the artifact-name grammar, so a
crash-left stage or backup was discovered as a duplicate manifold.
Staging and backup now live under <root>/.staging/ keyed <ns>~<name>,
and recover_backup / staging_paths replace the hand-rolled .bak
recovery in the HF and local install paths.
One schema, one folder module, one publication path:

- store/manifold_schema.py (new) owns the manifold.json contract
  (parse_manifest / manifest_payload, ManifestSpec) and the fitted
  sidecar (ManifoldSidecar is the single field list; build() is the
  writer's constructor, from_payload/load the reader's).  The four
  hand-written copies of the sidecar schema and the parallel manifest
  validators are gone, as are the v10-predecessor method allowances
  (manifold_monopolar -> authored, folded_vector).
- store/manifold_folder.py keeps the filesystem side: locks, the pair
  scan (manifold_folder_tensor_paths / fitted_pair_files), the one pair
  proof (prove_pair / read_proven_sidecar), read_manifest, and a
  ManifoldFolder whose sidecars load lazily.  Discovery never parses a
  sidecar; one malformed sidecar makes only that fit unavailable.
  Loading no longer emits authoring advisories (authoring_advisories).
- Every whole-folder write (authored, discover, baked, bundled copy)
  builds in staging and swaps into place.  publish_baked_manifold
  replaces create_baked_manifold_folder / save_baked_manifold_tensor
  and both crash-resume engines (authoring and fit.bake).
- store/bundled.py owns bundled materialization for both artifact kinds
  behind one process-scoped guard (archive recovery runs once per home)
  plus reset_bundled_state() for tests; the barrel module is deleted and
  every importer uses the defining module.

Bug fixes, each with a regression test:
- pack refresh default/<x> re-copies the bundle (it was a no-op).
- An interrupted bundled copy (missing manifest or node file) is drift
  and is repaired through stage-and-swap.
- manifold merge --method no longer inherits a foreign mode's
  hyperparameters.
- A sidecar with an invalid domain is a ManifoldFormatError and no
  longer breaks pack ls or bare-label steering; resolve_bare_atom stops
  swallowing arbitrary exceptions.
- update_manifold_folder refuses nodes on non-authored folders.
- Transferred sidecars drop the source fit's capture/checkpoint identity
  and merge provenance.
- refresh no longer holds pair locks across the re-pull (lock-order
  inversion against load_manifold).
- Discovery skips non-name directories and folders not named after
  their manifest.

Also: tensor_filename_for_variant replaces the variant->filename copies
in fit.bake and the steering composer; sidecar_filename, the dead
ActivationRowStore.load/persist, and selectors.parse_args are removed.
The memo was keyed on the manifolds root alone and only in-process
mutators invalidated it, so a running drowse serve never saw a manifold
created, installed, or removed by a separate CLI process until restart
(the dashboard listed it while steering could not resolve its labels).
The memo now carries a fingerprint of the namespace/folder listings plus
each manifold.json inode+mtime and nodes/ mtime: about three stats per
installed manifold, re-walked only when the tree actually changed.
In-process mutators still invalidate for changes inside one timestamp
tick.
The n=2 principal-angle transport builds its pairs from a closed-form 2x2
SVD instead of hopping linalg.svd to the CPU, and the Gauss-Newton step
solves the n<=2 damped normal equations in closed form instead of a
batched linalg.solve (which syncs on MPS). Behind queued GPU work, 34
curved injections now block the CPU for 18-30 ms instead of 150-225 ms.
The persistent-homology triangle loop converts the distance matrix to a
list once instead of indexing a tensor per triangle.
a9lim added 24 commits October 30, 2026 19:32
_whitener, _jlens_toys, _cli_fakes, _generation_stream and _gpu_model become
tests.support.{whitener,jlens_toys,cli,streams,gpu}; TestGenerationStream is
FakeGenerationStream, so it no longer needs __test__ = False.
… they no longer reach

CastMember.from_dict's field checks, the inferred Ollama aliases and the
list-valued eos / kwargs-only forward branches get direct tests.
…remaining server session factories onto it

The multi-node analytics tests run on a tiny session instead of binding
real session methods onto a mock, and the bake tests drive the Extraction
over a plain model handle.
…ining absence tombstones

The traits-stream 404 and missing-attribute checks pin removed surfaces;
the lens and SAE runs keep their rescoring assertions.
# Conflicts:
#	drowse/lens/corpus.py
#	drowse/sae/runtime.py
Wave 3 added EmptyCorpusError on the minors lane as a ValueError and
DrowseError with its own 400 user_message, in parallel with the errors
lane rebasing every request-shaped class onto RequestError. Rebase it
the same way and drop the duplicated user_message; the status, text
and CLI handling are unchanged.
The errors lane retyped the token-readout knob rejections to
RequestError, but the Instrument protocol, geometry and lens docstrings
still promised a bare ValueError, which the server now scrubs to a 500.
# Conflicts:
#	tests/support/lens.py
#	tests/support/read_plane.py
#	tests/support/stubs.py
#	tests/test_boundary_guard.py
#	tests/test_cast.py
#	tests/test_drowse_api.py
#	tests/test_instrument_routes.py
#	tests/test_joint_logprobs.py
#	tests/test_manifold_probe_session.py
#	tests/test_measurements_envelope.py
#	tests/test_server.py
#	tests/test_server_loom.py
#	tests/test_user_message.py
Move the 149 flat test modules into folders that mirror the package each
one targets (base, geometry, model, steering, readout, lens, sae, store,
generation, fit, loom, session, cli, server, web, notebook), plus
browser/ (golden parity), invariants/ (layering, error family, server
import surface, generated dashboard types) and gpu/ (the real-model
tier). conftest.py, support/, fixtures/ and
browser_drowse_archive_bridge.py stay where they are.

Only the __file__-relative repo paths and the tests/<module> references
in docs, comments and scripts change; the collected node set is
identical modulo the folder prefix (4929 tests).
…late error exit codes

A {c.attr} placeholder escaped system_for as a bare AttributeError, which the
server scrubs to a 500; it is now a RequestError like the other malformed
templates. TemplateFormatError and AmbiguousTemplateError became request
errors in wave 3, so the CLI exits 2 on them instead of 1; the error-boundary
test now pins that.
…ken-id probes

The grammar accepted 'jlens/# 12'; the id must now follow '#' directly, and
the shared browser fixture pins both spellings as rejected. Lens probes
attached by vocab id persist under jlens/#<id>, which the tree filter
refused as an identifier; it now accepts jlens/#<id> and slens/#<id>.
session.joint_logprobs had no test past the mock host, so a miswired
replayer dependency would have passed. The new test generates two real
siblings and checks the replay walks each node's own tokens. Also clears
the pyright leftovers in the two test files.
PromptRenderer.resolve_system_prompt is the one resolver; the recipe tests
now go through it. Persistent homology is implemented in-house, so nothing
imports the topology extra's ripser or scipy.
Svelte 5.55.8's update scheduler can wedge for good under rapid interaction:
on neuron-lens.com, which runs the same Svelte, frantic navigation froze the
page in 5 of 6 scripted runs with no error, and 5.57.2 froze in 0 of 12.
svelte-check is clean and the dist is rebuilt.
Unsteered decode with the 17 default probes ran ~15% slower than 5.3 (about
100 vs 119 tok/s on SmolLM2-360M, MPS). Batching the monitor read (222006c)
moved the whitener factors into three large stacks, which left ~6,700 tiny
long-lived tensors (registry manifolds and per-probe attach state) as the
residents of the MPS heap allocator's small pool. Every decode step's KV-cache
cat then paid coalesce_free_blocks around them; per-token ops were unchanged.

Manifold.to onto a device now builds on the host and uploads one buffer per
dtype with views into it (geometry/packing.py), probe attach runs on the host
and uploads the finished probe the same way, and the factor stack is assembled
on the host before its one upload. Live device storages after load drop from
6,749 to 323 and unsteered decode is back to ~119 tok/s.
The drilldown remembered its selection in a $state, which stores a proxy of
the params, so the identity guard never matched and any dependency change
re-picked the tab: adding a probe flipped geometry to lens. The anchor is a
plain variable now.

Since drawers load on first use, App focused the 'Loading…' placeholder one
tick after a first open. DrawerOutlet loads through reactive state and calls
onready once the drawer is in the DOM, and App focuses from there when the
chunk was not loaded yet.
A side tool closes on Escape only while focus is inside it, and its shell is
visible before its chunk loads. Waiting for onready left focus on the trigger
in that gap, so an early Escape did nothing. The container takes focus on the
next tick as before, and onready moves it to the first control if it is still
on the container.
The rework ships as 5.4.0; 6.0 stays reserved for the S-lens/mid-lens work
and the Ledger redesign. Lens homes from before 5.4 need
scripts/migrate_lens_v7.py.
Comment thread tests/support/chat_templates.py Fixed
Comment thread drowse/server/compat/ollama.py Fixed
a9lim added 3 commits October 31, 2026 07:41
CI runs pyright over the whole repo, which the 5.4.0 release PR failed on 57
errors (mostly in tests). Optional fields are narrowed with asserts, untyped
helper parameters and bare dict annotations are filled in, a possibly-unbound
loop variable is bound up front, and the deliberate fakes (SimpleNamespace,
_FakeModel, a stubbed read-only attribute, a Tensor standing in for a
LayerAlignment) go through cast(Any, ...). Two non-test fixes: migrate_lens_v7
asserts __doc__ before splitting it, and gguf._import_gguf returns
types.ModuleType so that on CI, where the optional gguf package is absent and
pyright resolves `import gguf` to the drowse module itself, attribute access
still typechecks. No assertions, production logic or pyright settings changed.
…gged Ollama options

The tokenizer stub rendered chat templates through a bare jinja2 Environment;
it now uses ImmutableSandboxedEnvironment, as transformers does (still without
HTML escaping, since a chat template is not markup). Dropped Ollama option
names come from the client, so line breaks are stripped before they are
logged, with a regression test.
The Demmler-Reinsch check compared two fp32 routes to an ill-conditioned GCV
on random nodes, which drift apart by whole percents and differently on x86
and ARM; it now uses unscrambled Sobol nodes and an fp64 oracle. The Hub
corpus tests imported the optional datasets package only to stub it; they
install a stand-in module (tests.support.lens.fake_datasets) and run without
the hf extra. The prebuilt-base-steering sweep test gets its own home, since
bundled manifolds materialized by an earlier test make a bare 'warm' resolve
to the warm.clinical pole.
@a9lim
a9lim merged commit c249306 into main Oct 31, 2026
12 checks passed
@a9lim
a9lim deleted the six branch October 31, 2026 12:12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants