Skip to content

feat(viz): --mode mlx / mlx-q8, the logit lens on the MLX engine - #78

Merged
rkinas merged 2 commits into
rkinas:mainfrom
agentGreg:feat/viz-mlx
Nov 2, 2026
Merged

rkinas merged 2 commits into
rkinas:mainfrom
agentGreg:feat/viz-mlx

Conversation

@agentGreg

@agentGreg agentGreg commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Closes #77.

Problem

basal-viz reads the layers of the PyTorch model only: --mode mps on Apple Silicon, eager elsewhere (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-8bit agrees 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's MLXBackend, as basal-serve --mode mlx does. The default is unchanged (mps / eager). --device with 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):
    • each decoder layer is wrapped for one forward to keep its output at the answer position, and the layers are restored afterwards;
    • the outputs go through the final norm, and the codes are read by MLXBackend._letters, as served (fp32 code rows, or the quantised head itself for the -MLX-8bit exports);
    • the top tokens come from _head (with the softcap).
  • torch_lens: the existing PyTorch lens, moved out of Explainer unchanged (it now returns token ids; Explainer.lens decodes them for both modes).
  • /api/info shows the MLX weights: 8-bit, 4-bit nvfp4 for an -MLX-fp4 export, or the bf16 dtype.
  • A prompt over the server's context limit (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).
  • Llama-architecture models only, as before. Gemma 4 / basal-omni stays with feat(viz): inspect Gemma 4 (basal-omni) text decisions #75.
  • 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, and q8 with a quantised head):

  • every layer of the MLX lens equals the PyTorch lens (2e-4; 8-bit: 0.05);
  • the last layer equals MLXBackend.run (2e-4);
  • the decoder layers are restored.

tests/test_server.py::test_viz_refuses_a_prompt_over_the_context: refused with 422, no forward.

Full pytest on an Apple M5 Max: 764 passed, 53 skipped, 1 failed. The failure is test_mlx_gemma4_equals_torch, the M5 TF32 issue fixed by #76, which is not on this branch.

Real models: the page's /api/explain and Server.decide on 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:

model mode lens vs engine (max) page vs served, 1 question (max) page vs served, several questions (max) explain p50
basal-2.0-mini mps (before, for reference) 3.0e-7 1.8e-7 9.0e-3 64 ms
basal-2.0-mini-MLX-8bit mlx 1.2e-6 7.2e-7 1.1e-2 58 ms
basal-2.0-mini mlx-q8 1.0e-6 7.2e-7 2.0e-2 59 ms
basal-2.0-4.5B mps (before, for reference) 5.4e-7 4.8e-7 1.9e-2 137 ms
basal-2.0-4.5B-MLX-8bit mlx 2.1e-6 1.7e-6 1.7e-2 141 ms
basal-2.0-4.5B mlx-q8 3.3e-6 1.3e-6 2.0e-2 143 ms

"Lens vs engine" is the page's existing packed_max_diff; "page vs served" is its served_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.md already 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 equals MLXBackend.run exactly; and a live basal-viz --model Remek/basal-2.0-mini-MLX-8bit --mode mlx, whose /api/info and /api/explain serve 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__ in basal/viz.py, so I will rebase onto 2.5 (and #75) when they land on main.

…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.
@sourcery-ai

sourcery-ai Bot commented Oct 29, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Adds basal-viz --mode mlx and mlx-q8 by running the serving MLX backend on its own worker thread, capturing decoder-layer outputs with native MLX readouts, while preserving the existing PyTorch lens and CLI behavior. Documentation and tests cover model metadata, quantization variants, numerical parity, served-output agreement, and restoration safety.

Sequence diagram for the MLX logit lens request

sequenceDiagram
    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
Loading

File-Level Changes

Change Details Files
Add MLX-backed visualization modes while preserving the existing PyTorch path.
  • Accept mlx and mlx-q8 modes and construct basal-serve’s MLX backend in-process.
  • Reject --device for MLX modes while retaining existing device and dtype behavior for PyTorch modes.
  • Expose MLX weight precision, architecture, layer count, and execution mode through /api/info.
  • Keep Llama-only validation and share the existing server configuration for orders and calibration.
basal/viz.py
Implement logit-lens extraction against each engine’s native model execution and output decoding.
  • Move the existing PyTorch lens into torch_lens, returning token IDs before display decoding.
  • Wrap MLX decoder layers for a single backend-thread forward, restore the original layers in a finally block, and apply the final norm.
  • Read MLX code probabilities through _letters and full-vocabulary predictions through _head, including softcap handling.
  • Decode top-token IDs uniformly in Explainer.lens for both backends.
basal/viz.py
Document MLX visualization usage, supported exports, and observed numerical behavior.
  • Add an MLX basal-viz invocation and explain support for MLX-8bit, MLX-fp4, mlx-q8, and bf16 weights.
  • Document that MLX lens outputs follow the serving engine’s code/head readout and note multi-question packing differences.
docs/SERVING.md
Verify MLX lens parity, served-output consistency, quantized-head handling, and layer restoration.
  • Compare per-layer MLX and PyTorch lens results across fp32, q8, and quantized-head configurations.
  • Check the final lens layer against MLXBackend.run and verify decoder layers are restored after inspection.
  • Cover quantized-head code-row fallback behavior.
tests/test_mlx.py

Assessment against linked issues

Issue Objective Addressed Explanation
#77 Add basal-viz --mode mlx and mlx-q8 so the visualizer runs and inspects the same MLX backend used by basal-serve, without changing the existing default PyTorch modes. ✅
#77 Implement an MLX logit lens for Llama models that records each layer’s output, reads code distributions using the backend’s MLX readout behavior, and shows top full-vocabulary tokens from the final layer. ✅
#77 Verify that the lens matches the served MLX decisions and document the results, while preserving existing mps/eager behavior. ✅

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread basal/viz.py Resolved
Comment thread docs/SERVING.md Resolved
Comment thread tests/test_mlx.py Resolved
…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
rkinas merged commit 1448f5b into rkinas:main Nov 2, 2026
1 check passed
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.
@agentGreg
agentGreg deleted the feat/viz-mlx branch November 16, 2026 19:55
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.

basal-viz: tryb MLX (--mode mlx / mlx-q8), żeby obejrzeć decyzje portów -MLX-8bit i -MLX-fp4

2 participants