Skip to content

Instantly share code, notes, and snippets.

@awdemos
Created July 10, 2026 02:33
Show Gist options
  • Select an option

  • Save awdemos/2f1e74af30256796def572dec1b979c6 to your computer and use it in GitHub Desktop.

Select an option

Save awdemos/2f1e74af30256796def572dec1b979c6 to your computer and use it in GitHub Desktop.
J space algos
Here is the complete algorithmic pipeline extracted from the Anthropic paper, covering the training of the lens, readout, sparse J-space decomposition, and the core interventions.
---
### Algorithm 1: Train the Jacobian Lens (J_β„“)
**Input:** Model with layers β„“ = 1 … L, corpus of prompts 𝒫, target layer = final layer (default)
**Output:** Per-layer Jacobian matrices J_β„“ ∈ ℝ^{d_model Γ— d_model}
```python
# h_β„“[t] : residual stream at layer β„“, token position t
# z[t] : residual stream at target layer L, position t
# T : number of token positions in the prompt
for each prompt p in corpus 𝒫:
run forward pass; cache h_β„“[t] for all β„“, t
# one backward pass per output dimension (batched in practice)
for i in 1 … d_model:
# inject βˆ‚/βˆ‚z_i = 1 at EVERY target position
grad_z = e_i βŠ— 1_T # one-hot in dim i, broadcast over all T positions
for each layer β„“:
# autodiff: gradient of summed target-layer activations w.r.t. h_β„“
G_β„“ = βˆ‚( Ξ£_{t'=1..T} z[t'] ) / βˆ‚h_β„“ # shape [T, d_model]
# average over SOURCE positions t
J_β„“^(p)[i, :] = mean over t of G_β„“[t, :]
# aggregate across prompts (element-wise mean)
for each layer β„“:
J_β„“ = mean over prompts p of J_β„“^(p)
```
**Mathematical definition** (Β§2.1):
$$J_\ell = \mathbb{E}_{t,\; t' \ge t,\; \text{prompt}} \left[ \frac{\partial h_{\text{final},t'}}{\partial h_{\ell,t}} \right]$$
---
### Algorithm 2: J-Lens Readout (Inference)
**Input:** Trained J_β„“, residual stream activation h_β„“, unembedding matrix W_U, normalization `norm`
**Output:** Probability distribution over the vocabulary
```python
def lens_readout(h_β„“, J_β„“, W_U):
# Project activation through the averaged Jacobian
y = J_β„“ @ h_β„“
# Apply the model's pre-unembedding normalization
y_norm = norm(y)
# Unembed to logits and softmax
logits = W_U @ y_norm
probs = softmax(logits)
# Return ranked token list
return argsort(probs, descending=True)
```
**Per-token probe** (Β§2.5): For a specific concept token *t*, read its activation as the inner product ⟨v_t, h_β„“βŸ© where v_t is the row of W_U J_β„“ corresponding to token *t*.
---
### Algorithm 3: J-Space Sparse Decomposition (Gradient Pursuit)
**Input:** Activation h_β„“, J-lens dictionary V = {v_1 … v_{Vocab}}, sparsity budget k (typically k ≀ 25)
**Output:** Sparse coefficients a ∈ ℝ^{Vocab}_{β‰₯0}, J-space component h_J, non-J residual h_βŠ₯
```python
def jspace_decompose(h, V, k):
# Solve via gradient pursuit / matching pursuit:
# min || h - Ξ£_j a_j v_j ||_2
# s.t. a_j β‰₯ 0, ||a||_0 ≀ k
a = gradient_pursuit(h, dictionary=V, sparsity=k, non_negative=True)
h_J = Ξ£_j a_j v_j # J-space component
h_βŠ₯ = h - h_J # non-J-space remainder
return a, h_J, h_βŠ₯
```
**Occupancy** (Β§4.2): The smallest k such that adding a (k+1)-th J-lens vector does not improve reconstruction more than adding a random direction of the same norm.
---
### Algorithm 4: Lens-Coordinate Swap (Causal Intervention)
**Input:** Source token *s*, target token *t*, activation h, swap strength Ξ± (default 1.0)
**Output:** Patched activation h_patched
```python
def coordinate_swap(h, s, t, Ξ±=1.0):
# Form the 2-column matrix of lens vectors
V = [v_s v_t] # shape [d_model, 2]
# Read the lens coordinates (pseudoinverse)
c = pinv(V) @ h # c = [c_s, c_t]
# Swap the two entries (optionally scaled by Ξ±)
c_swapped = [c_t, c_s] * Ξ± + [c_s, c_t] * (1 - Ξ±)
# More precisely: Οƒ(c) swaps the two entries, then:
# h_patched = h + V @ (Οƒ(c) - c)
delta = V @ (Οƒ(c) - c)
h_patched = h + delta
return h_patched
```
**Usage:** Apply this at every token position across a band of intermediate workspace layers (e.g., L38–L92), then run the forward pass from that layer onward.
---
### Algorithm 5: J-Space Ablations & Steering
#### A. Concept-Specific Ablation
```python
def ablate_concept(h, concept_token, layers):
v = lens_vector(concept_token)
for h_β„“ in layers:
# Project out the component along v
h_β„“ = h_β„“ - (proj_v(h_β„“))
return h
```
#### B. Top-k J-Space Ablation (Β§3.5.2)
```python
def ablate_topk_jspace(h_β„“, k=10, exclude_output_tokens=True):
# Identify the k most strongly activated J-lens vectors
topk = top_k_activated_lens_vectors(h_β„“, k)
if exclude_output_tokens:
# Do NOT ablate tokens that appear in top-10 clean forward-pass outputs
# (avoids corrupting imminent motor output)
topk = filter(topk, lambda tok: tok not in clean_top10)
# Zero out projections onto all selected vectors
for v in topk:
h_β„“ = h_β„“ - projection_of(h_β„“ onto v)
return h_β„“
```
#### C. Steering (Injection)
```python
def steer(h, concept_token, strength=Ξ±):
v = lens_vector(concept_token)
return h + Ξ± * v
```
---
### Algorithm 6: Broadcast-Head Ablation (Β§4.3.2)
**Input:** Set of J-lens "broadcast heads" ℬ (top 1% of attention heads by gain + label preservation metrics)
**Output:** Modified forward pass with broadcast suppressed
```python
def forward_with_broadcast_ablation(x, layers, broadcast_heads ℬ):
for β„“ in layers:
for head h in layer β„“:
if h in ℬ:
# Zero this head's output contribution
x = x + 0 * head_output(h, x)
else:
x = x + head_output(h, x)
return x
```
---
### Key Hyperparameters from the Paper
| Parameter | Typical Value | Usage |
|-----------|---------------|-------|
| Corpus size for J_β„“ | 1,000 prompts | Training the expectation |
| Sequence length | 128 tokens | Prompt sampling |
| Sparsity k | 10–25 | J-space decomposition / ablation |
| Workspace layers | L38–L92 (Sonnet 4.5) | Where interventions are applied |
| Swap strength Ξ± | 1.0 (or 2.0 for "double strength") | Coordinate swap |
| Steering strength | 0.02–0.32 | Injected-thought introspection |
---
### Quick Reference: Formal J-Space Definition (Β§A.8)
For a sparsity level *k* and vocabulary vectors {v_1 … v_n}, the J-space is the union of *k*-dimensional cones:
$$\mathcal{F} = \bigcup_{|S|=k} \text{span}_{\ge 0}\{v_i : i \in S\}$$
The distance from an activation *x* to the J-space is:
$$d_{\mathcal{F}}(x) = \min_{|S|=k} \|x - \Pi_S x\|$$
where Ξ _S is orthogonal projection onto the cone spanned by the chosen *k* vectors. The minimizing projection is the **J-space component** used in all interventions above.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment