Skip to content

[Proposal] Natural Language Autoencoders demo: explain and reconstruct a Qwen activation with TransformerBridge #1884

Closed

Description

@janmenjayap

Proposal

Add one demo notebook, demos/Natural_Language_Autoencoders_Demo.ipynb, that runs the released Natural Language Autoencoder (NLA) round trip for Qwen2.5-7B-Instruct at block 20 through TransformerBridge, with no model server.

The notebook shows how to:

  1. extract one raw residual-stream activation from the target model;
  2. turn it into a natural-language explanation with the Activation Verbalizer (AV);
  3. turn that explanation back into a vector with the Activation Reconstructor (AR);
  4. measure how closely the reconstruction matches the original direction.

The notebook only uses existing Bridge features: run_with_cache, bridge.hooks(...) on hook_embed around generate, and boot_transformers. It does not change transformer_lens/, tests/, pyproject.toml, or uv.lock. This follows the demo-first pattern set by #1907.

The notebook has two parts:

  • Mechanics section (runs in CI). Runs on the cached tiny Qwen2 test model and asserts that the injection, generation, read-out, and parsing steps match plain HF.
  • Released section (run locally). The real 7B round trip in bf16, with # NBVAL_SKIP cells and committed outputs.

Motivation

Natural Language Autoencoders Produce Unsupervised Explanations of LLM Activations releases trained AV and AR models that map an activation to text and back. The authors' AV client injects the activation through SGLang embedding injection. Their AR uses a truncated backbone with a separately released linear value head.

A Bridge-based demo lets researchers inspect individual activations in an ordinary notebook, without running a server. It also shows how the AV and AR line up with TL's hook names and residual basis. TL already has every primitive this needs; what is missing is a worked, checked example that puts them together.

This work uses the released inference artifacts only. It does not reproduce the authors' RL/GRPO training. Reconstruction fidelity shows that a vector is preserved; it does not show that the explanation is faithful to a human reading.

Related work, which this does not duplicate:


Pitch

Scope

Target Qwen/Qwen2.5-7B-Instruct, raw Bridge (no compatibility mode)
AV kitft/nla-qwen2.5-7b-L20-av
AR kitft/nla-qwen2.5-7b-L20-ar + value_head.safetensors
Layer zero-based block 20 (blocks.20.hook_out = HF hidden_states[21]), d_model = 3584
Revisions Immutable commit SHAs pinned in the notebook, never main
Input One unpadded prompt and one selected token position per call
Precision Released section in bf16, as in the authors' reference; mechanics section in CPU fp32
Loading Stock HF architectures, trust_remote_code=False, eager attention, one model loaded at a time

Non-goals

  • Explanation-edit steering, causal validation, or a corpus benchmark / dataset FVE. These are possible follow-ups, outlined in the suggested roadmap comment. Per the maintainer's decision, they will be assessed after this demo merges.
  • Gemma or Llama NLA pairs, other layers, or cross-model transfer.
  • Training, SGLang serving, multimodal inputs, or quantization.
  • Any new package API, registry, or test-suite code.

Notebook outline

  1. Introduction. Colab badge, the AV and AR roles, links to the paper and the reference code, and how this differs from Patchscopes.

  2. Requirements box. Disk, memory, and time measured for the released section, and the opt-in switch TL_RUN_RELEASED_NLA=1.

  3. Setup (# NBVAL_IGNORE_OUTPUT).

  4. Helpers. Each helper is short, defined in the notebook, and used in the cell after it:

    • extract(bridge, prompt, layer, position): calls run_with_cache with names_filter set to blocks.{L}.hook_out only. Returns a detached CPU vector and the resolved position. Rejects empty input and out-of-range positions.
    • inject_hook(vector, position, norm): rescales the vector in fp32 to the sidecar injection norm, casts it to the hook tensor's dtype, and overwrites only the placeholder position at hook_embed. With the KV cache it applies on prefill only. Without the cache it re-applies at the original position on every recomputed prefix.
    • verbalize(av_bridge, av_tokenizer, vector, ...): renders the AV chat template once (add_generation_prompt=True), then runs generate inside av_bridge.hooks(...) with explicit, bounded sampling settings.
    • parse_explanation(text): returns the stripped inner text of exactly one complete <explanation>...</explanation> region. Otherwise it returns None and one of these statuses: missing, multiple, nested, incomplete, or empty. A failed parse never falls back to the raw text.
    • reconstruct(ar_bridge, ar_tokenizer, value_head, text): formats the raw AR template once (it is not a chat prompt), reads the final-token output of block 20, and applies the bias-free value head. It never uses the AR's uninitialized final norm or LM head. It rejects text that still contains explanation tags.
    • score(original, reconstructed): computed in float64. Returns the cosine and the direction-normalized MSE, and asserts nmse == 2 * (1 - cos). Both are directional measures, not raw MSE or FVE.
  5. Mechanics on tiny Qwen2 (runs in CI). Uses trl-internal-testing/tiny-Qwen2ForCausalLM-2.5, a synthetic sidecar that follows the real schema, and a placeholder asserted to be a single non-UNK token. Asserts:

    • (a) Bridge prefill logits with the overwrite equal HF logits from inputs_embeds with the same row replaced.
    • (b) Cached and uncached greedy generation produce the same tokens, and only the placeholder position changes.
    • (c) The truncated AR read-out equals HF hidden_states[L+1][:, -1].
    • (d) All six parse outcomes behave as described above.
    • (e) No hooks remain on any model afterwards, including after an exception inside the hook context.

    Each check uses exact equality, or a measured tolerance with a stated reason.

  6. Released Qwen2.5-7B round trip in bf16 (# NBVAL_SKIP, committed outputs):

    1. Load the sidecars at the pinned revisions with yaml.safe_load and assert: injection norm 150, exactly one placeholder, the AR template, mse_scale approximately equal to sqrt(3584) in direction-normalized mode, and a [3584, 3584] value head with no bias.
    2. Target: run extract at blocks.20.hook_out on 3 fixed prompts, keep the vectors on CPU, then unload the model.
    3. AV: run a prefill-logit parity cell against plain HF inputs_embeds in bf16 with the same tokens and the same scaled vector. Run verbalize on each vector, then unload the model.
    4. AR: assert that the only missing keys are the final norm and the LM head. Run a parity cell against plain HF in bf16, run reconstruct, then unload.
    5. Results table with every prompt, including parse failures: parse status, explanation, cosine, and normalized MSE.
    6. Measured resources: peak RAM/VRAM, wall time per stage, and the parity error statistics (max absolute error). These values also go into the requirements box.
  7. Interpreting the results. A checklist: what a high or low cosine does and does not tell you, why sampled explanations vary from run to run, what parse failures mean, and the faithfulness caveat.

Precision and parity

  • The released section runs in bf16, following the authors' reference. Peak memory is roughly half of fp32 (about 34 GiB in fp32). The notebook reports the measured numbers rather than estimates.
  • Parity compares Bridge against plain HF at the same dtype, device, tokens, and attention implementation. This measures what the Bridge adds, not the gap between
    bf16 and fp32. The earlier fp32 spike found exact parity. Any nonzero bf16 error is reported and its cause investigated, not labelled "fp noise".
  • Sampled explanation text and the round-trip cosine are reported as results, not used as pass/fail thresholds.

CI and docs

  • notebook-checks executes the mechanics section only. The released cells carry # NBVAL_SKIP and their outputs come from a local run. The docs build uses nbsphinx_execute = "never", so those outputs still render on the docs site.
  • Register the notebook in docs/make_docs.py, docs/source/index.md, the analysis-tools pointer in docs/source/content/analysis_tools.md, and the notebook-checks matrix in .github/workflows/checks.yml, following Analysis Tools Review & Re-contextualization #1907.

Delivery

One PR from docs/nla-qwen-demo into dev, in three commits:

# Commit
1 docs(demos): add Natural Language Autoencoders demo with tiny Qwen2 mechanics checks
2 docs(demos): add released Qwen2.5-7B NLA round trip in bf16 with HF parity
3 docs: register NLA demo in docs build and notebook checks

Definition of done

  • The notebook is merged, and its mechanics section passes pytest --nbval-sanitize-with demos/doc_sanitize.cfg demos/Natural_Language_Autoencoders_Demo.ipynb.
  • The released section's committed outputs come from a single local bf16 run at the pinned revisions, with measured memory, time, and parity errors.
  • The notebook is registered in the docs build and in notebook-checks, and uv run build-docs passes.
  • make check-format passes; no package, test, or dependency files change.
  • The notebook states the requirements, parse failures, and faithfulness caveats.

Alternatives


Additional context


Checklist

  • I have checked that there is no similar issue in the repo (required)

Activity

  1. added
    TransformerBridge
    Community Feedback Requested
    seen_by_maintainers
    on Oct 12, 2026
  2. jlarson4 commented on Oct 12, 2026

    @jlarson4
    Collaborator

    Hello TransformerLens community! If you would find this feature useful, please react to the initial Proposal with a 👍 . If I see a significant volume of reactions, I will green light the proposal.

    Thank you for your interest in contributing to TransformerLens!

  3. jlarson4 commented on Oct 22, 2026

    @jlarson4
    Collaborator

    @janmenjayap if you would like to restructure this issue into a focused Demo notebook only proposal, rather than a full tools/analysis module, that would be an excellent solution for getting this idea integrated in a valuable & maintainable way.

    Let me know if you're interested in this reframe, and I will assign you + adjust the labels to match the new focus.

  4. janmenjayap commented on Oct 25, 2026

    @janmenjayap
    ContributorAuthor

    Hi @jlarson4, thank you for taking the time to review this and for suggesting the reframe. I would be glad to restructure it as a demo notebook, and after reading #1907 I agree it is the better fit for the library.

    Below are the changes I would like to suggest for this proposal, my proposed plan for delivering it, and a suggested roadmap for the complete NLA work as demos. Please let me know if you would like anything adjusted. I am happy to follow your preference on any of these points.

    Suggested changes to this proposal

    Title

    • Current: [Proposal] Natural Language Autoencoders: explain and reconstruct Qwen activations through TransformerBridge
    • Suggested: [Proposal] Natural Language Autoencoders demo: explain and reconstruct a Qwen activation with TransformerBridge

    Body

    Section Current Suggested
    Proposal A server-free NLA tool in transformer_lens.tools.analysis One notebook, demos/Natural_Language_Autoencoders_Demo.ipynb, with no package code
    Proposed API A NaturalLanguageAutoencoder class with from_pretrained / extract / verbalize / reconstruct / score / unload A notebook outline: about six short helpers defined in the notebook, built only on existing Bridge features (run_with_cache, hooks() around generate on hook_embed, boot_transformers(hf_model=...))
    Correctness contracts Registry, provenance attestation, lifecycle/ownership, and concurrency guarantees Checks the notebook asserts: parity with plain HF, the explanation-parse outcomes, sidecar values, and hook cleanup
    Validation Unit and integration test suites, a wheel-resource test, and slow artifact tests A CI-executed section on the cached tiny Qwen2 test model, plus the released 7B round trip run locally
    Definition of done Public API, registry in the wheel, docs page, test tiers Notebook merged, registered in the docs build and notebook-checks, build-docs passing
    Module-specific items nla_registry.json, the allow_unverified_target attestation, the PyYAML / safetensors dependency additions, content/natural_language_autoencoders.md, and the "maintainer agreement on a tools/analysis integration" checkbox Removed
    Motivation, paper and reference links, non-goals, faithfulness caveats, resource requirements As currently written Kept as is

    Proposed plan for this issue

    My suggestion is one issue (this one), one PR, and three commits. The PR would go from docs/nla-qwen-demo into dev and close #1884. It would not change anything in transformer_lens/, tests/, pyproject.toml, or uv.lock.

    # Proposed commit What it would contain
    1 docs(demos): add Natural Language Autoencoders demo with tiny Qwen2 mechanics checks The new notebook: background on the activation verbalizer (AV, activation to text) and activation reconstructor (AR, text to activation); inline helpers extract, inject_hook, verbalize, parse_explanation, reconstruct, score; and a section on the cached tiny-Qwen2ForCausalLM-2.5 that asserts: (a) logits with the embedding overwritten through the Bridge equal HF inputs_embeds with the same row replaced, (b) cached and uncached generation agree and only the placeholder position changes, (c) the truncated AR read-out equals HF hidden_states[L+1], (d) all explanation-parse outcomes, (e) no hooks remain afterwards. It would end with an interpretation checklist.
    2 docs(demos): add released Qwen2.5-7B NLA round trip with HF parity The released round trip at pinned revisions: Qwen/Qwen2.5-7B-Instruct, AV kitft/nla-qwen2.5-7b-L20-av, and AR kitft/nla-qwen2.5-7b-L20-ar with its value_head.safetensors, all at block 20. It would check the sidecar values (injection norm, placeholder, AR template, mse_scale, head shape) and show AV and AR parity against plain HF in the notebook. Models would load one at a time. Every prompt would be reported, including parse failures, along with measured time and memory.
    3 docs: register NLA demo in docs build and notebook checks Additions to docs/make_docs.py, docs/source/index.md, the demo pointer in docs/source/content/analysis_tools.md, and the notebook-checks matrix in checks.yml, following how #1907 registered the Backward Lens and SVD Circuits demos.

    A question on CI for the 7B section

    The released target, AV, and AR are three 7B checkpoints: about 38 GiB of weights, and about 34 GiB RAM on CPU fp32. Since they cannot run in notebook-checks, only the tiny-model section would be executed there. For commit 2, I can see two options:

    1. Mark the released cells # NBVAL_SKIP and commit their outputs from a local run. The docs build uses nbsphinx_execute = "never", so those outputs would still render on the docs site. This would be my slight preference, since all the code stays visible in one file.
    2. Follow the causal-swap benchmark pattern: a scripts/ file writes a frozen JSON to demos/data/, and the notebook reads and renders it.

    I am happy to go with whichever you think fits the repository better, or with another approach if you have one in mind.

    Suggested roadmap for the complete NLA work

    Looking beyond this issue, here is how I would suggest delivering NLA end to end as demos. This is only a suggestion from my side. Each follow-up would be its own issue, so you can decide on each one separately, and I would only file them with your agreement after this demo is merged. If you feel this issue alone is enough, I am completely fine with stopping there.

    Issue Scope PR Commits Depends on
    1. This issue (#1884) NLA round-trip demo, as described above docs/nla-qwen-demo 3 Your approval
    2. Suggested follow-up Explanation-edit steering, as a new section of the same notebook docs/nla-edit-steering-demo 2 Issue 1 merged
    3. Suggested follow-up Reconstruction benchmark demo over a small fixed prompt set docs/nla-reconstruction-benchmark 3 Issue 1 merged (independent of Issue 2)

    In total, this would be 3 issues, 3 PRs, and 8 commits, with no changes to the package code in any of them.

    Issue 2: explanation-edit steering (suggested follow-up)

    The edited and original explanations are each reconstructed by the AR, and their difference AR(edited) - AR(original) is added as a steering direction at the selected prompt token on blocks.20.hook_out. The generations are compared against two controls: no steering, and a random direction of the same size.

    # Proposed commit What it would contain
    1 docs(demos): add NLA explanation-edit steering mechanics on tiny Qwen2 Inline helpers for the edit direction, the steering hook, and running the three conditions, with separate seeds for the control direction and for sampling. CI-executed checks on the tiny model: alpha = 0 leaves logits unchanged, only the selected position changes, the added norm is as expected, cached and uncached generation agree, the random control has the same norm, and no hooks remain.
    2 docs(demos): add released Qwen explanation-edit example with controls One edited explanation on the released Qwen pair, with a small number of samples per condition. The outcome measure is declared before running, and every sample is reported. It is clearly described as a single example, not a validation.

    Issue 3: reconstruction benchmark (suggested follow-up)

    This would follow the causal-swap benchmark pattern from #1907, so the notebook can run in CI without downloading any model.

    # Proposed commit What it would contain
    1 scripts: add NLA reconstruction benchmark for the released Qwen pair A self-contained script that runs the round trip over a small fixed prompt set (for example 64 prompts) at pinned revisions, one model at a time. It caches each phase so an interrupted run can continue, and refuses to reuse a cache made with different settings. It keeps parse failures in the results, and reports coverage, the cosine distribution, and a clearly defined normalized FVE. It also has a small mode on the tiny Qwen2 model for quick checks.
    2 docs(demos): add frozen NLA reconstruction benchmark artifact The JSON result written to demos/data/: revisions, settings, per-prompt results including failures, and summary values. No tensors, to keep it small.
    3 docs(demos): add NLA reconstruction benchmark demo and register it A notebook that reads the JSON and shows coverage, the cosine histogram, the FVE with its definition, a per-prompt table, and caveats. It would be registered in the docs build and notebook-checks in the same way as the other demos.

    I would check the FVE definition against the reference repository before describing it as equivalent to the paper's metric. If I cannot confirm it, I would label it clearly as a TransformerLens normalized FVE.

    What I would not suggest

    I would not suggest support for the larger released pairs (Gemma-3 12B and 27B, Llama-3.3-70B), offloading support, dataset-level edit studies, or an SGLang backend. These would either need far more memory than a demo can reasonably ask for, or would bring library features or a server dependency back in, which goes against the direction of #1907.

    Separate small bug

    While working on this, I also found that get_tokenizer_with_bos raises KeyError: 'name_or_path' for tokenizers built in memory. It is not related to NLA, and none of these demos depend on it. If you think it would be useful, I can file it as a separate bug report with a small fix and a regression test.

    Next steps

    Once you approve this direction, I will update the proposal's title and body as described above and start working on the PR for this issue. I will bring up the suggested follow-ups again only after it is merged, and only file the ones you are happy with. Thank you again for the guidance!

  5. jlarson4 commented on Oct 26, 2026

    @jlarson4
    Collaborator

    This is an excellent re-frame of this issue, thank you for understanding and taking the time to adjust the approach. Consider this approved as reframed with a couple adjustments/responses from me below, I will assign you and drop the Feedback label.

    1. run the released 7B section in bf16, as the authors' reference does. fp32 at 34 GiB is out of reach for most readers, and bf16 roughly halves it. Make sure to report the measured memory.
    2. For the CI question, go with option 1, skipped cells with committed outputs.
    3. Let's scope this to issue 1 for now. Once this PR is in, I'll assess from there and determine next steps.

    Please file the get_tokenizer_with_bos KeyError as its own bug with a small fix, and feel free to work on that in parallel with this Proposal if you'd like, tag me in the initial Issue Report and I will make sure you are assigned.

  6. added
    enhancement
    complexity-moderate
    and removed
    Community Feedback Requested
    seen_by_maintainers
    on Oct 26, 2026
  7. changed the title [-][Proposal] Natural Language Autoencoders: explain and reconstruct Qwen activations through TransformerBridge[/-] [+][Proposal] Natural Language Autoencoders demo: explain and reconstruct a Qwen activation with TransformerBridge[/+] on Nov 1, 2026
  8. janmenjayap commented on Nov 1, 2026

    @janmenjayap
    ContributorAuthor

    Hi @jlarson4, thank you again for approving the reframed proposal. I've opened the demo PR: #1963.

    I followed your guidance on all three points:

    The released 7B section runs in bf16, and the notebook reports the measured memory: about 13.8 GiB peak RSS and 3.2 minutes on CPU, not counting downloads.
    The released cells are marked # NBVAL_SKIP and keep the outputs from my local run, so notebook-checks only runs the tiny-Qwen2 mechanics section.
    The scope is limited to this demo.
    TransformerBridge matched plain Hugging Face exactly (max absolute difference 0.0) for the target extraction, the verbalizer prefill, and the reconstructor read-out.

    I also made three small edits to the proposal body so it matches what was delivered: it now says 3 fixed prompts, reports the max absolute error only, and links #1961 and #1962 for the tokenizer bug.

    Whenever you have time to take a look, I'd be grateful for any feedback, and I'm happy to make whatever changes you'd like. Thank you!

  9. janmenjayap commented on Nov 4, 2026

    @janmenjayap
    ContributorAuthor

    Hi @jlarson4, thank you for reviewing and merging #1963, and for the guidance throughout!

    You mentioned you would assess next steps once it was in. When you have a moment, I would be glad to hear whether either of the follow-ups from my earlier roadmap comment would be useful:

    • Explanation-edit steering: reconstruct an edited explanation and steer generation with AR(edited) - AR(original), compared against an unsteered baseline and a norm-matched random direction. The round-trip notebook already has about 49 cells, so I would suggest a separate notebook for this, but I am happy to add it as a section of the existing one if you prefer

    • Reconstruction benchmark: a scripts/ file that writes a frozen JSON to demos/data/, plus a small notebook that renders coverage, the cosine distribution, and a clearly defined normalized FVE, following the causal-swap benchmark pattern.

    Both would follow the same conventions as #1963: bf16 with measured memory, pinned revisions, # NBVAL_SKIP cells with committed outputs, and no package code. I would file each as its own issue only if you think it's worthwhile, and I am equally happy to stop here if you feel the demo is enough

    Thank you

  10. jlarson4 commented on Nov 4, 2026

    @jlarson4
    Collaborator

    Hi @janmenjayap! I'm going to hold here for now. The round-trip notebook covers the TransformerLens-specific mechanics (injection through cached generation, the truncated read-out, the faithfulness caveat). Both follow-ups are mostly about the NLA artifacts themselves.

    If people start using the demo and we see issue or traction around it growing in the repo, I'll reopen the question then. I will reach out if anything changes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Research ReproductionTransformerBridgecomplexity-moderateenhancement

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions