Repository navigation
feat(viz): inspect Gemma 4 (basal-omni) text decisions - #75
Merged
Merged
Conversation
Reviewer's GuideAdds Gemma 4 basal-omni text-decision inspection to basal-viz by reusing the text decoder and eager engine’s output-head transformations, while explicitly rejecting media requests and documenting and testing the new behavior. Sequence diagram for Gemma 4 per-layer decision inspectionsequenceDiagram
participant Explainer
participant TextModel as Gemma4TextModel
participant Layer as DecoderLayers
participant Head as OutputEmbeddings
Explainer->>TextModel: forward(input_ids, use_cache=False, output_hidden_states=False)
Layer-->>Explainer: cloned last-position hidden states
Explainer->>TextModel: norm(hidden states)
Explainer->>Head: weight and bias for codes
Head-->>Explainer: output logits
Explainer->>Explainer: apply final_logit_softcapping
Explainer->>Explainer: torch.softmax(logits, -1)
Explainer-->>Explainer: per-layer code distributions
Flow diagram for basal-viz request eligibilityflowchart TD
Start[explain request] --> Media{body.media present?}
Media -->|Yes| Reject[Raise ValueError: text only]
Media -->|No| Architecture{Supported architecture?}
Architecture -->|Gemma 4| GemmaPath[Inspect Gemma 4 text decoder]
Architecture -->|Llama| LlamaPath[Inspect Llama model]
Architecture -->|Other| Unsupported[Raise unsupported architecture error]
GemmaPath --> Explain[Return layer explanations]
LlamaPath --> Explain
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 4 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="basal/viz.py" line_range="102-103" />
<code_context>
- mm, caught = self.model.model, []
- hooks = [layer.register_forward_hook(lambda _m, _i, o: caught.append((o[0] if isinstance(o, tuple) else o)[0, -1]))
+ mm, caught = self.text_model, []
+ hooks = [layer.register_forward_hook(
+ lambda _m, _i, o: caught.append((o[0] if isinstance(o, tuple) else o)[0, -1].clone()))
for layer in mm.layers]
try:
</code_context>
<issue_to_address>
**Concurrent inference corrupts explanations**
When a server-worker inference overlaps `lens()` on the same decoder, the hooks registered by `Explainer.lens` also run during `Gemma4Forward.hidden`, appending unrelated activations to `caught`; `lens` then reports incorrect per-layer probabilities or fails while stacking them. The caller sees an incorrect explanation or an error.
Use the backend inference lock to prevent server-worker forwards from running on the shared decoder while `lens` captures activations.
</issue_to_address>
### Comment 2
<location path="basal/viz.py" line_range="106-107" />
<code_context>
for layer in mm.layers]
try:
- final = mm(input_ids=torch.tensor([ids], device=self.dev), use_cache=False).last_hidden_state[0, -1]
+ final = mm(input_ids=torch.tensor([ids], device=self.dev), use_cache=False,
+ output_hidden_states=False).last_hidden_state[0, -1]
finally:
for h in hooks:
</code_context>
<issue_to_address>
**Long inspections exhaust memory**
When a Gemma 4 prompt is long enough that the full-sequence decoder forward exceeds available memory, the full-sequence forward retains attention work proportional to prompt length squared, so a long but context-valid prompt can exhaust device memory and fail the inspection instead of producing layer probabilities.
Add a chunked, memory-bounded lens path for long prompts, or reject lengths that the full-sequence forward cannot safely handle.
</issue_to_address>
### Comment 3
<location path="tests/test_viz_gemma4.py" line_range="41-47" />
<code_context>
+ layers, _ = ex.lens(ids, codes)
+
+ assert len(layers) == model.config.num_hidden_layers
+ assert all(sum(p) == pytest.approx(1.0, abs=1e-6) for p in layers)
+ eager = object.__new__(EagerBackend)
+ eager.head = model.get_output_embeddings()
+ eager.softcap = model.config.final_logit_softcapping
+ hidden = Gemma4Forward(model).hidden([[ids]])[0][0]
+ served = eager._codes(hidden[None].float(), [codes])[0]
+ assert layers[-1] == pytest.approx(served, abs=1e-6)
+
+
</code_context>
<issue_to_address>
**Incorrect intermediate layers pass**
When an intermediate decoder layer produces an incorrect code distribution while the final layer remains correct, `test_gemma4_lens_matches_eager_served_probabilities_at_every_layer` checks only normalization at line 41 and compares eager parity only for `layers[-1]` at line 47, so incorrect or uniform distributions at earlier layers still pass.
Compare each intermediate distribution against a reference computed from that layer’s activation.
</issue_to_address>
### Comment 4
<location path="tests/test_viz_gemma4.py" line_range="75-76" />
<code_context>
+ monkeypatch.setattr(ex.text_model, "forward", check_forward)
+ layers, _ = ex.lens([i % 55 + 1 for i in range(512)], [1, 2, 3, 4])
+
+ assert seen["output_hidden_states"] is False
+ assert len(layers) == model.config.num_hidden_layers
+
+
</code_context>
<issue_to_address>
**Full-sequence retention goes undetected**
When the hook captures a view into each layer’s full-sequence output rather than a cloned last-position tensor, `test_gemma4_lens_does_not_retain_full_sequence_hidden_states` checks only `output_hidden_states=False` at line 75 and the layer count at line 76, so it still passes if hooks retain views of full-sequence layer outputs instead of cloning the last position.
Assert that the captured hook tensors do not retain full-sequence storage, rather than checking only the forward argument.
</issue_to_address>
pawelkiszczak
added a commit
to pawelkiszczak/basal-ui
that referenced
this pull request
Oct 28, 2026
… /api/models reports inspect_reason Ported from the fork's feat/viz-gemma4-text (UI half); the engine half is rkinas/basal#75.
14 tasks
Owner
|
Thank you, Paweł! Planned for basal 2.5: we are merging it into the 2.5 release branch now, after our checks (full CPU suite, your tests, serving code unchanged). The PR will close when 2.5 is published on main. |
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 #74
What
basal/viz.pyExplainer: accepts Gemma 4 models (basal.gemma4.is_gemma4) besides Llama; the lens runs overbasal.gemma4.text_model(model)with the output embeddings as head, adds the head bias when there is one and appliesfinal_logit_softcapping, as the eager engine reads the codes. The layer hooks clone the last position (no full-sequence hidden states kept).info["layers"]counts the text decoder's layers.explain()refuses a request withmedia:basal-viz reads text only: remove the media to inspect this request.tests/test_viz_gemma4.py(usestests/test_gemma4.py::tiny): the last lens layer equalsEagerBackend._codeson the same hidden state for 2/4/5/12 options; the softcap changes the distribution; nooutput_hidden_states; the Explainer reports the layer count and still refuses other architectures; media requests are refused.docs/SERVING.md("See how a decision is made") anddocs/WHATS_NEW.md(# Unreleased).Why
basal-omni's text decisions could not be inspected at all; the eager engine already reads them from the Gemma 4 text decoder, so basal-viz can show the same per-layer picture it shows for basal-1.x/2.0.
Compatibility
Llama models take the same path as before (
self.model.model,lm_head, no bias, no softcap). Text requests are unchanged; requests withmedianow get an explicit error instead of an explanation of the text alone. The refusal message for other architectures also names Gemma 4 basal-omni.Tests run
uv run --no-sync pytest -q tests/test_viz_gemma4.py— 8 passed.uv run --no-sync pytest -q -x— 769 passed, 53 skipped, 1 warning.Remek/basal-omni-1.0-maxloaded byExplainerreports 48 layers; a 3-optionchoiceexplained withserved_max_diff0.0 againstServer.decideon the same model (through basal-ui's Inspect, which embeds basal-viz).uvx [email protected] check --select E9,F63,F7,F82 --target-version py310 .— only the existingF821 Undefined name kposin untouchedbasal/gemma4.py:471.Summary by Sourcery
Extend basal-viz to inspect Gemma 4 basal-omni text decisions with eager-engine-compatible per-layer probabilities.
New Features:
Bug Fixes:
Enhancements:
Documentation:
Tests: