Repository navigation
feat(viz): --mode mlx / mlx-q8, the logit lens on the MLX engine - #78
Merged
Merged
Conversation
…nas#77) basal-viz read the layers of the PyTorch model only (--mode mps / eager), so the MLX ports a Mac serves (-MLX-8bit, -MLX-fp4, mlx-q8) could not be inspected. With --mode mlx / mlx-q8 the page runs basal-serve's MLXBackend and the lens runs on its MLX thread: each decoder layer's output at the answer position (the layers wrapped for one forward, then restored) through the final norm, the codes read by MLXBackend._letters as served (fp32 code rows, or the quantised head). The PyTorch lens moves unchanged into torch_lens. Llama-architecture models only, as before. Tests (tiny Llama, fp32 / q8 / q8 with a quantised head): every layer equals the PyTorch lens, the last layer equals MLXBackend.run, the layers are restored. Apple M5 Max, 49 bundled requests, basal-2.0-mini and 4.5B, -MLX-8bit and mlx-q8: page vs served at most 1.7e-6 for single-question requests; multi-question requests up to 0.02, as in mps.
Reviewer's GuideAdds Sequence diagram for the MLX logit lens requestsequenceDiagram
participant Client
participant Explainer
participant MLXBackend
participant Worker as be.pool worker
participant Model as MLX decoder
Client->>Explainer: lens(ids, codes)
Explainer->>MLXBackend: mlx_lens(be, ids, codes)
MLXBackend->>Worker: submit(run)
Worker->>Model: wrap decoder layers with _Catch
Worker->>Model: forward ids
Model-->>Worker: layer outputs at answer position
Worker->>Model: restore decoder layers
Worker->>MLXBackend: _letters(layer states, codes)
Worker->>MLXBackend: _head(final state)
MLXBackend-->>Explainer: per-layer probabilities and top tokens
Explainer-->>Client: decoded lens results
File-Level Changes
Assessment against linked issues
Possibly linked issues
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
There was a problem hiding this comment.
Hey - I've found 3 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="basal/viz.py" line_range="111" />
<code_context>
+ layers = mm.layers
+ mm.layers = [_Catch(layer, caught) for layer in layers]
+ try:
+ final = mm(mx.array([ids]))[0, -1]
+ finally:
+ mm.layers = layers
</code_context>
<issue_to_address>
**Oversized prompts exhaust MLX memory**
When an unauthenticated remote client can reach the visualizer because it is bound to a network interface and submits a request whose rendered prompt is large enough to exhaust memory, `mlx_lens` tokenizes and forwards the prompt before `Server.decide` checks the model context limit; a sufficiently long prompt consumes MLX unified memory and can take down the visualizer process.
Validate prompt length and request size before running the per-layer lens, rejecting or truncating inputs that exceed configured limits.
</issue_to_address>
### Comment 2
<location path="docs/SERVING.md" line_range="211" />
<code_context>
for exploring, not serving: every question runs one extra forward per option order to record all layers.
+`--mode mlx` (the `-MLX-8bit` / `-MLX-fp4` exports or bf16 weights) and `--mode mlx-q8` read the layers of the MLX
+engine that `basal-serve` runs on a Mac, so the page shows where a quantised model's decision forms or moves. The
+codes are read as that engine reads them (fp32 code rows, or the quantised head itself). On the page's 49 bundled
+requests (the 44 items with gold answers and 5 requests with several questions; Apple M5 Max, basal-2.0-mini and 4.5B,
</code_context>
<issue_to_address>
**MLX mode description conflicts**
When a reader uses the serving guide to determine which mode basal-viz runs, the preceding paragraph still says the visualiser runs `--mode mps` on Apple Silicon and `--mode eager` elsewhere, without limiting that claim to the default. Readers therefore get conflicting instructions about the newly documented `--mode mlx` and `--mode mlx-q8` behavior.
Qualify the mps/eager statement as the default behavior and distinguish it from the explicitly selected MLX modes.
</issue_to_address>
### Comment 3
<location path="tests/test_mlx.py" line_range="128-134" />
<code_context>
+ layers = list(be.lm.model.layers)
+ tol = 0.05 if quant else 2e-4
+ served = be.run(TOKS, LIDS)
+ for ids, codes, s in zip(TOKS, LIDS, served):
+ ref, ref_top = torch_lens(m, "cpu", ids, codes)
+ got, top = mlx_lens(be, ids, codes)
+ assert len(got) == len(ref) == 2
+ for r, g in zip(ref, got):
+ assert max(abs(x - y) for x, y in zip(r, g)) < tol
+ assert max(abs(x - y) for x, y in zip(got[-1], s)) < 2e-4 # the page's last layer is the served readout
+ assert top[0][0] == ref_top[0][0] and abs(sum(p for _, p in top) - sum(p for _, p in ref_top)) < tol
+ assert list(be.lm.model.layers) == layers
</code_context>
<issue_to_address>
**Incomplete layer readouts pass**
When the backend returns fewer served rows, or the lens returns fewer code probabilities than expected, `test_viz_mlx_lens` uses `zip(TOKS, LIDS, served)` at line 128 and then `zip(ref, g)` and `zip(got[-1], s)` at lines 132–134 without checking lengths; missing served rows or truncated code vectors therefore skip comparisons, so the test passes with incomplete readouts.
Assert the served-row and probability-vector lengths before comparing their values.
</issue_to_address>…test lengths (Sourcery review on rkinas#78) - explain_branch refuses a prompt longer than the server's context limit (the model's, or the engine's own: Server.context) with a RequestError (HTTP 422) before any forward, in every mode: the lens runs the whole prompt without truncation, where basal-serve would truncate the state. Live, basal-2.0-mini-MLX-8bit (8,192 tokens): a 20,095-token prompt is refused in 0.68 s. - SERVING.md: mps / eager is the default; --mode mlx / mlx-q8 runs the MLX engine instead. - test_viz_mlx_lens checks the lengths of the served rows, the code vectors and the top tokens before comparing them.
rkinas
added a commit
that referenced
this pull request
Nov 2, 2026
rkinas
added a commit
that referenced
this pull request
Nov 2, 2026
… version CONTRIBUTING.md credits the 2.5 pull requests as the release notes' community line lists them (Paweł Kiszczak #52, #62, #64, #66, #68, #71, #73, #75; Marcin Brzeżański #56; Grzegorz Brzezinka #76, #78) and adds Dariusz Koryto (#53, #58, #59, #60 and #55); the README's list names him too. docs/changes/README.md and the changelog.py help use 2.5.1, the next release, as the example.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #77.
Problem
basal-viz reads the layers of the PyTorch model only:
--mode mpson Apple Silicon,eagerelsewhere (basal/viz.py). The MLX ports a Mac serves by default (-MLX-8bit,-MLX-fp4,mlx-q8) cannot be inspected, although they are where quantisation moves decisions (basal-2.0 4.5B-MLX-8bitagrees with bf16 on 0.955 of the bench examples, M5 Max,docs/HARDWARE.md).Change
basal-viz --mode mlx | mlx-q8: the page runs basal-serve'sMLXBackend, asbasal-serve --mode mlxdoes. The default is unchanged (mps/eager).--devicewith an MLX mode is refused with a message.mlx_lens: no parallel path. It runs on the backend's own MLX thread (be.pool, the same single worker as the server's forwards):MLXBackend._letters, as served (fp32 code rows, or the quantised head itself for the-MLX-8bitexports);_head(with the softcap).torch_lens: the existing PyTorch lens, moved out ofExplainerunchanged (it now returns token ids;Explainer.lensdecodes them for both modes)./api/infoshows the MLX weights:8-bit,4-bit nvfp4for an-MLX-fp4export, or the bf16 dtype.Server.context: the model's, or the engine's own) is refused with HTTP 422 before any forward, in every mode: the lens runs the whole prompt, where basal-serve would truncate the state (Sourcery review).docs/SERVING.md: the mode and the measurement below.Verification
Tests (
tests/test_mlx.py::test_viz_mlx_lens, a tiny Llama with fp32 weights,q8, andq8with a quantised head):MLXBackend.run(2e-4);tests/test_server.py::test_viz_refuses_a_prompt_over_the_context: refused with 422, no forward.Full
pyteston an Apple M5 Max: 764 passed, 53 skipped, 1 failed. The failure istest_mlx_gemma4_equals_torch, the M5 TF32 issue fixed by #76, which is not on this branch.Real models: the page's
/api/explainandServer.decideon the 49 bundled requests (44 items with gold answers, 5 requests with several questions), Apple M5 Max, mlx 0.32.4, mlx-lm 0.32.2:mps(before, for reference)mlxmlx-q8mps(before, for reference)mlxmlx-q8"Lens vs engine" is the page's existing
packed_max_diff; "page vs served" is itsserved_max_diff.One deviation from the acceptance check in #77, which asked for at most 1e-3 overall. It holds for single-question requests (at most 1.7e-6). Requests with several questions differ by up to 0.02 in every mode, including the existing
mps: the server packs the questions that share a state into one row, while the page runs each question separately.docs/SERVING.mdalready describes this for bf16. This PR does not change it.Also checked by hand:
--mlx-packed(PositionRoPE-wrapped layers) and a fully quantised head, where the lens's last layer equalsMLXBackend.runexactly; and a livebasal-viz --model Remek/basal-2.0-mini-MLX-8bit --mode mlx, whose/api/infoand/api/explainserve the page.Note on merging
The branch is based on v2.4.1, and the change is planned for 2.5.1. #75 also changes
Explainer.__init__inbasal/viz.py, so I will rebase onto 2.5 (and #75) when they land on main.