Skip to content

feat(viz): inspect Gemma 4 (basal-omni) text decisions - #75

Merged
rkinas merged 2 commits into
rkinas:mainfrom
pawelkiszczak:pr/viz-gemma4-text
Nov 2, 2026
Merged

rkinas merged 2 commits into
rkinas:mainfrom
pawelkiszczak:pr/viz-gemma4-text

Conversation

@pawelkiszczak

@pawelkiszczak pawelkiszczak commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Closes #74

What

  • basal/viz.py Explainer: accepts Gemma 4 models (basal.gemma4.is_gemma4) besides Llama; the lens runs over basal.gemma4.text_model(model) with the output embeddings as head, adds the head bias when there is one and applies final_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 with media: basal-viz reads text only: remove the media to inspect this request.
  • tests/test_viz_gemma4.py (uses tests/test_gemma4.py::tiny): the last lens layer equals EagerBackend._codes on the same hidden state for 2/4/5/12 options; the softcap changes the distribution; no output_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") and docs/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 with media now 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.
  • Real model, Apple M-series (MPS, bf16): Remek/basal-omni-1.0-max loaded by Explainer reports 48 layers; a 3-option choice explained with served_max_diff 0.0 against Server.decide on 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 existing F821 Undefined name kpos in untouched basal/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:

  • Enable basal-viz to inspect Gemma 4 basal-omni text decisions alongside existing Llama models.
  • Reject media-bearing inspection requests with an explicit text-only error.

Bug Fixes:

  • Ensure Gemma 4 layer probabilities match eager-engine served code distributions, including output-head bias and final logit softcapping.
  • Prevent overlapping inspection and served-comparison requests from sharing model execution unsafely.

Enhancements:

  • Limit Gemma 4 inspections to 2,048 rendered prompt tokens and report the text decoder layer count.
  • Capture only final-position layer activations while preserving existing Llama behavior.

Documentation:

  • Document Gemma 4 text inspection, media limitations, prompt limits, and serialized request handling.
  • Add an unreleased changelog entry for Gemma 4 basal-viz support.

Tests:

  • Add coverage for Gemma 4 per-layer lens parity, softcapping, memory behavior, validation, architecture support, media rejection, and concurrent HTTP requests.

@sourcery-ai

sourcery-ai Bot commented Oct 28, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Adds 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 inspection

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

Flow diagram for basal-viz request eligibility

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

File-Level Changes

Change Details Files
Extend the visualization logit lens to Gemma 4 basal-omni text decoding while preserving the existing Llama path.
  • Detect Gemma 4 and select its text decoder, output embedding head, layer count, and configuration.
  • Capture cloned final-position activations per decoder layer without requesting full-sequence hidden states.
  • Apply output-head bias and final logit softcapping before producing code probabilities and vocabulary predictions.
  • Keep Llama behavior unchanged and update unsupported-architecture messaging.
basal/viz.py
Explicitly limit basal-viz explanations to text-only requests.
  • Reject requests containing media with a clear ValueError before explanation processing.
  • Document Gemma 4 support and the media limitation in serving guidance and release notes.
basal/viz.py
docs/SERVING.md
docs/WHATS_NEW.md
Add focused coverage for Gemma 4 lens correctness, memory behavior, and request/model validation.
  • Verify final-layer probabilities match EagerBackend code probabilities across multiple option counts.
  • Verify softcapping changes results, hidden states are not retained, layer counts are reported, unsupported models are rejected, and media is refused.
tests/test_viz_gemma4.py

Assessment against linked issues

Issue Objective Addressed Explanation
#74 Enable basal-viz to inspect Gemma 4 basal-omni text decisions layer by layer, using the text decoder and output head and matching eager-served code probabilities, including the final logit softcap. ✅
#74 Refuse requests containing media with a clear error rather than explaining them using text alone. ✅
#74 Preserve Llama behavior and continue refusing unsupported non-Llama, non-Gemma-4 architectures. ✅

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

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

Comment thread basal/viz.py Resolved
Comment thread basal/viz.py Resolved
Comment thread tests/test_viz_gemma4.py Resolved
Comment thread tests/test_viz_gemma4.py Resolved
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.
@rkinas

rkinas commented Oct 29, 2026

Copy link
Copy Markdown
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
rkinas merged commit 3553bbe 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.
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 cannot read basal-omni (Gemma 4) text decisions

2 participants