Repository navigation
Description
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:
- extract one raw residual-stream activation from the target model;
- turn it into a natural-language explanation with the Activation Verbalizer (AV);
- turn that explanation back into a vector with the Activation Reconstructor (AR);
- 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_SKIPcells 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:
- Patchscopes demo: activation patching into generation, but no trained AV/AR and no reconstruction.
- Jacobian Lens: precedent for artifacts and interventions, but not this activation-to-text-to-activation protocol.
- feat(nla): add Bridge-native Qwen activation verbalization and reconstruction #1889 (closed): the earlier
tools/analysisimplementation. This demo replaces it.
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
-
Introduction. Colab badge, the AV and AR roles, links to the paper and the reference code, and how this differs from Patchscopes.
-
Requirements box. Disk, memory, and time measured for the released section, and the opt-in switch
TL_RUN_RELEASED_NLA=1. -
Setup (
# NBVAL_IGNORE_OUTPUT). -
Helpers. Each helper is short, defined in the notebook, and used in the cell after it:
extract(bridge, prompt, layer, position): callsrun_with_cachewithnames_filterset toblocks.{L}.hook_outonly. 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 athook_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 runsgenerateinsideav_bridge.hooks(...)with explicit, bounded sampling settings.parse_explanation(text): returns the stripped inner text of exactly one complete<explanation>...</explanation>region. Otherwise it returnsNoneand one of these statuses:missing,multiple,nested,incomplete, orempty. 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 assertsnmse == 2 * (1 - cos). Both are directional measures, not raw MSE or FVE.
-
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_embedswith 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.
- (a) Bridge prefill logits with the overwrite equal HF logits from
-
Released Qwen2.5-7B round trip in bf16 (
# NBVAL_SKIP, committed outputs):- Load the sidecars at the pinned revisions with
yaml.safe_loadand assert: injection norm 150, exactly one placeholder, the AR template,mse_scaleapproximately equal tosqrt(3584)in direction-normalized mode, and a[3584, 3584]value head with no bias. - Target: run
extractatblocks.20.hook_outon 3 fixed prompts, keep the vectors on CPU, then unload the model. - AV: run a prefill-logit parity cell against plain HF
inputs_embedsin bf16 with the same tokens and the same scaled vector. Runverbalizeon each vector, then unload the model. - 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. - Results table with every prompt, including parse failures: parse status, explanation, cosine, and normalized MSE.
- 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.
- Load the sidecars at the pinned revisions with
-
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-checksexecutes the mechanics section only. The released cells carry# NBVAL_SKIPand their outputs come from a local run. The docs build usesnbsphinx_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 indocs/source/content/analysis_tools.md, and thenotebook-checksmatrix 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, anduv run build-docspasses. -
make check-formatpasses; no package, test, or dependency files change. - The notebook states the requirements, parse failures, and faithfulness caveats.
Alternatives
- A
tools/analysismodule (the original version of this proposal and feat(nla): add Bridge-native Qwen activation verbalization and reconstruction #1889). Rejected in favor of a demo: a narrow artifact-specific tool is a maintenance burden for the library (see Analysis Tools Review & Re-contextualization #1907). - A frozen-artifact pattern, where a
scripts/file writes JSON todemos/data/and the notebook renders it. Not chosen. Keeping the released code in the notebook with skipped cells keeps everything visible in one file. - fp32 for the released section. Not chosen. About 34 GiB of RAM is out of reach for most readers, and bf16 matches the authors' reference.
Additional context
- Paper: https://transformer-circuits.pub/2026/nla/
- Reference code: https://github.com/kitft/natural_language_autoencoders
- Resources: the target, AV, and AR are three 7B-class checkpoints, about 38 GiB of downloads in total; the AR alone is about 10.9 GB plus a 25.7 MB head. Loading one model at a time lowers peak memory, but not download size or run time.
- Main risks: drift in the injection scale or placeholder, the wrong AR output basis (final norm or LM head applied by mistake), tokenizer/BOS mismatches, and hooks that work in a single forward pass but fail during cached generation. The mechanics checks and parity cells target these directly.
- Found during the earlier spike and filed separately:
get_tokenizer_with_bosraisesKeyError: 'name_or_path'for in-memory tokenizers ([Bug Report]get_tokenizer_with_bosraises KeyError for in-memory tokenizers #1961, fix in fix: handle in-memory tokenizers in get_tokenizer_with_bos #1962).
Checklist
- I have checked that there is no similar issue in the repo (required)
Activity
jlarson4 commentedon Oct 12, 2026
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!
jlarson4 commentedon Oct 22, 2026
@janmenjayap if you would like to restructure this issue into a focused Demo notebook only proposal, rather than a full
tools/analysismodule, 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.
janmenjayap commentedon Oct 25, 2026
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
[Proposal] Natural Language Autoencoders: explain and reconstruct Qwen activations through TransformerBridge[Proposal] Natural Language Autoencoders demo: explain and reconstruct a Qwen activation with TransformerBridgeBody
transformer_lens.tools.analysisdemos/Natural_Language_Autoencoders_Demo.ipynb, with no package codeNaturalLanguageAutoencoderclass withfrom_pretrained/extract/verbalize/reconstruct/score/unloadrun_with_cache,hooks()aroundgenerateonhook_embed,boot_transformers(hf_model=...))notebook-checks,build-docspassingnla_registry.json, theallow_unverified_targetattestation, thePyYAML/safetensorsdependency additions,content/natural_language_autoencoders.md, and the "maintainer agreement on a tools/analysis integration" checkboxProposed plan for this issue
My suggestion is one issue (this one), one PR, and three commits. The PR would go from
docs/nla-qwen-demointodevand close #1884. It would not change anything intransformer_lens/,tests/,pyproject.toml, oruv.lock.docs(demos): add Natural Language Autoencoders demo with tiny Qwen2 mechanics checksextract,inject_hook,verbalize,parse_explanation,reconstruct,score; and a section on the cachedtiny-Qwen2ForCausalLM-2.5that asserts: (a) logits with the embedding overwritten through the Bridge equal HFinputs_embedswith the same row replaced, (b) cached and uncached generation agree and only the placeholder position changes, (c) the truncated AR read-out equals HFhidden_states[L+1], (d) all explanation-parse outcomes, (e) no hooks remain afterwards. It would end with an interpretation checklist.docs(demos): add released Qwen2.5-7B NLA round trip with HF parityQwen/Qwen2.5-7B-Instruct, AVkitft/nla-qwen2.5-7b-L20-av, and ARkitft/nla-qwen2.5-7b-L20-arwith itsvalue_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.docs: register NLA demo in docs build and notebook checksdocs/make_docs.py,docs/source/index.md, the demo pointer indocs/source/content/analysis_tools.md, and thenotebook-checksmatrix inchecks.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:# NBVAL_SKIPand commit their outputs from a local run. The docs build usesnbsphinx_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.scripts/file writes a frozen JSON todemos/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.
docs/nla-qwen-demodocs/nla-edit-steering-demodocs/nla-reconstruction-benchmarkIn 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 onblocks.20.hook_out. The generations are compared against two controls: no steering, and a random direction of the same size.docs(demos): add NLA explanation-edit steering mechanics on tiny Qwen2alpha = 0leaves 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.docs(demos): add released Qwen explanation-edit example with controlsIssue 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.
scripts: add NLA reconstruction benchmark for the released Qwen pairdocs(demos): add frozen NLA reconstruction benchmark artifactdemos/data/: revisions, settings, per-prompt results including failures, and summary values. No tensors, to keep it small.docs(demos): add NLA reconstruction benchmark demo and register itnotebook-checksin 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_bosraisesKeyError: '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!
jlarson4 commentedon Oct 26, 2026
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.
Please file the
get_tokenizer_with_bosKeyError 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.[-][Proposal] Natural Language Autoencoders: explain and reconstruct Qwen activations through TransformerBridge[/-][+][Proposal] Natural Language Autoencoders demo: explain and reconstruct a Qwen activation with TransformerBridge[/+]janmenjayap commentedon Nov 1, 2026
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!
janmenjayap commentedon Nov 4, 2026
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 preferReconstruction 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_SKIPcells 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 enoughThank you
jlarson4 commentedon Nov 4, 2026
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.