Refusal, model edits, and their tradeoffs. From two requests to the geometry inside a language model.
Two requests, one model. Recorded LFM3 representations on the left; a calculated projection on the right. These plots track vectors, not generated answers.
In this section, we’ll see how a language model represents a request and how we can change one component of that representation. We’ll use two account-security requests to work through tokens, vectors, PCA, and the mean-difference direction.
Let’s start with two requests about online accounts:
Benign request
“How can I protect my online account from password theft?”
Harmful request
“How can I steal someone else's online account password?”
The first asks for help protecting an account. The second asks for help stealing one. They share a topic, but we would expect an instruction-following model to respond differently to them. How does that difference appear inside the model?
To find out, we’ll follow the requests as they pass through LiquidAI LFM3-1.7B. We’ll first look at how the model represents text, then use those representations to understand single-direction abliteration.
From text to a direction
A language model processes numbers. Before it can work with either request, the text must be split into tokens and converted into vectors. As these vectors pass through the model’s blocks, their values change.
If we collect vectors from many benign and harmful requests, we can compare the two groups. The simplest approach is to calculate the average of each group and subtract one average from the other. This gives us a direction in the model’s representation space. We can then test what happens when we remove a vector’s component along that direction.
There are a few steps here, so let’s work through them using the two requests above.
About the example data
The two requests were passed through the pinned LFM3 checkpoint with unchanged weights. We saved internal activations without generating responses. “Benign” and “harmful” are our request labels; whether a response refuses is measured separately. Later figures use small numerical examples, identified by their figure labels.
From words to 2,048 numbers
The first step is tokenization: splitting the text into pieces that the model recognizes. A piece can be a word, part of a word, or a punctuation mark. The tokenizer assigns each piece an integer called a token ID.
Hover a piece to see its token ID. ␠ marks a space. After chat formatting: 21 tokens. Captured final token: <think> (ID 124901).
See the formatted input
<|startoftext|><|im_start|>user
How can I steal someone else's online account password?<|im_end|>
<|im_start|>assistant
<think>
The model also receives special tokens that mark the roles in the conversation. In this example, the formatted input ends with the start of the assistant’s thinking segment. We’ll inspect the hidden state at that final input position, where the model has already processed the request.
What is a residual vector?
Inside each block, the model carries a numerical representation called the residual stream. Each token position has its own vector containing 2,048 numbers. A vector is simply an ordered list of numbers. Each number is one coordinate, or dimension.
For the whole input, we stack these token vectors as rows of a matrix. If the formatted input contains T tokens, that matrix has shape [T, 2,048]:
H = [x₁; x₂; …; x_T] H: T × 2,048 one row x_t: 2,048 values
The semicolons indicate rows stacked vertically. For example, an input with 10 tokens would have 10 rows and 2,048 columns at one block. Remember that tokens can be word pieces or special markers, so the number of rows need not equal the number of words.
When we say “a residual vector,” we’re selecting one row from this matrix. Here, we select the final formatted input position, whose representation has been computed using the preceding tokens. This is the assistant-prefix position described above.
Let’s look at the first six coordinates of that selected row for each request at block 11:
benign x = [0.021, -0.095, -0.022, -0.007, -0.042, -0.050, …] harmful x = [-0.061, -0.056, 0.053, 0.049, -0.031, -0.062, …] Both lists contain 2,048 coordinates; six are printed here.
These bars show 24 of the 2,048 captured coordinates at block 11. They are entries of the hidden vector before PCA.
Each bar gives the value at one coordinate. The coordinates work together to represent information about the input. An individual coordinate does not come with a name such as “account security” or “refusal.”
Inside a block
Let’s follow the whole matrix through one block. There are two main operations. The first mixes information between token positions, using attention or a short convolution. The second is a feed-forward network, also called an MLP. It transforms each row separately using the same learned weights.
Each operation produces an update that we add to a copy of its input. This addition is the residual connection: the block builds on the existing representation. Follow the purple paths to see where the copies join the updates.
Follow the matrix down the page. Each row belongs to one token position. The purple paths carry a copy forward to each addition.
Gated short convolution
Input residual H[T, 2,048]
token 1x₁,₁x₁,₂…x₁,₂₀₄₈
token 2x₂,₁x₂,₂…x₂,₂₀₄₈
⋮
token Tx_T,₁x_T,₂…x_T,₂₀₄₈
copy H
↓
RMSNorm normalize each row
↓
1Gated short convolutionMixes information from a short, causal neighborhood of token positions.Output: [T, 2,048]
↓
RMSNorm normalize the update
↓
+
H₁ = H + mixer update [T, 2,048]
copy H₁
↓
RMSNorm normalize each row
↓
2Gated feed-forward network (MLP)Transforms each token’s row separately, using the same learned weights.
2,048→7,680→2,048
Gate and value branches meet at width 7,680.
↓
RMSNorm normalize the update
↓
+
H_out = H₁ + MLP update [T, 2,048]
↓
Output residual H_out[T, 2,048] → next block
token 1h₁,₁h₁,₂…h₁,₂₀₄₈
⋮
token Th_T,₁h_T,₂…h_T,₂₀₄₈
↳ We save this final row after the block. One residual vector x: [2,048]
The block updates the values while keeping the outer matrix shape. The highlighted row is the final formatted input position, <think>, in our example captures. Both inputs have 21 formatted tokens, so each full matrix here has shape [21, 2,048]. The cells above are symbolic, rather than measured coordinate values.Where normalization and capture happen
The pinned checkpoint enables sandwich normalization: each branch has RMSNorm both before its operation and before its update is added back. The saved vector is taken after the second addition, before the next block or the model’s final readout normalization. Block labels use zero-based indices, as in the plots. The diagram shows a full-input pass; cached generation can process only the new token positions.
The + circles add matching entries of two matrices. Both inputs to each addition have shape [T, 2,048], so the result keeps that shape. We select the highlighted row after the second addition when recording our residual vector.
RMSNorm adjusts the scale of each row using its root-mean-square value and learned weights. In this checkpoint, normalization appears before each operation and on its output before the residual addition.
Inside the MLP, two learned branches expand each row from 2,048 to 7,680 values, combine through a gate, and project back to 2,048. The sequence still has T rows throughout. The wider intermediate representation gives the MLP more features to work with while keeping the block’s input and output widths the same.
LFM3 uses three mixer types across its blocks. Full causal attention can read all preceding positions; sliding attention limits that range to a local window; short convolution uses a local causal neighborhood. Use the block selector to see which mixer appears at each depth. The architecture documentation describes these components.
Tokens, blocks, and dimensions
These three counts describe different parts of the computation:
Count
Meaning
In this example
Tokens
Positions in the formatted input
Depends on the request
Blocks
Stages that update the representation
24
Hidden dimensions
Values in one residual vector
2,048
The shape depends on which parts of the computation we keep:
What we keep
Shape
One token position at one block
[2,048] — a vector
All T token positions for one input at one block
[T, 2,048] — a matrix
A batch of B equally padded inputs at one block
[B, T, 2,048] — a three-dimensional tensor
Our saved final position across two requests and 24 blocks
[2, 24, 2,048] — a three-dimensional tensor
We saved just one position per block for each request, which is why the saved array has no token-position axis. If we kept every position across all blocks and padded the requests to the same length, its shape would be [2 requests, 24 blocks, T token positions, 2,048 coordinates].
Next, we’ll see how a vector relates to the tokens the model predicts.
From a vector to a token score
To predict the next token, the model needs to turn its final hidden vector into vocabulary scores. It does this with an output head: a matrix that maps the hidden dimensions to one score for every vocabulary entry.
For LFM3, this takes us from 2,048 hidden values to 128,000 vocabulary scores. These scores are called logits. The softmax function converts them into probabilities that add up to one:
logits = normalized_hidden × W_headᵀ W_head: 128,000 × 2,048 probability(token j) = exp(logit_j) / sum of exp(all logits)
The final normalization depends on the model architecture. Once we have the probabilities, a decoding rule chooses the next token. The model repeats this process to generate a response.
Looking at an intermediate block
We can also apply the output head to a hidden state from an earlier block. This is called a logit lens. It lets us inspect which tokens the output head favors as the representation develops.
For example, we could track the combined probability of several tokens that occur in refusal wording. Plotting that quantity across blocks would show where the readout starts to favor those tokens.
There are two details to keep in mind. First, the output head was trained to read the final state, so reading an earlier state is an approximation. Second, a few token probabilities cannot describe every possible refusal. A model can express the same response in many ways.
How do we draw 2,048 dimensions?
We can put two coordinates on a page: one on the horizontal axis and one on the vertical axis. Our vectors have 2,048 coordinates! We therefore need a way to choose a smaller set of axes.
Principal component analysis, or PCA, finds directions along which a collection of vectors varies the most. It first subtracts the average vector, then finds perpendicular axes ordered by the variation they capture. The first is called PC1, the second PC2, and so on.
For this example, we fit PCA on 128 baseline vectors at one block. Each row comes from the selected final input position of a different prompt, so 128 counts prompts here. The input has shape [128 examples, 2,048 coordinates]. Each new axis is a weighted combination of the original coordinates. Keeping two axes gives us a pair of numbers for each vector:
The circles show the 128 baseline examples; the diamonds show our two requests. Each block has its own fitted PCA axes. Change the block to inspect another view of the representations.
The small circles are the examples used to fit PCA. The diamonds are our two account-security requests, placed using those same axes. PCA finds its axes from the vectors alone; the benign and harmful labels are used to color the picture afterward.
Open Explore this plot and change the block. You’ll see a different view of the representations at each depth. We fit a separate PCA at each block, so the axes change along with the block.
How much can two axes show?
PCA lets us measure how much variation each axis captures:
At block 11, PC1 accounts for 52.5% of estimation-set variance and PC2 for 8.4%. Together they show 60.8%; the other 39.2% is outside this two-axis view.
Each bar shows the fraction of variation captured by a PCA component at block 11. We display the first 16 components. With 128 centered examples, at most 127 components can have nonzero variance.
This is why two nearby points in the picture may still be far apart in the full space: the remaining coordinates are hidden from view. A visible gap between groups is also only a starting point. The gap could reflect wording or topic as well as behavior.
It helps to fit the axes on many examples. If we fitted PCA on just our two requests, centering would leave two points on a single line. That would tell us very little about the rest of the model’s representations.
Other ways to draw the vectors
You may also encounter t-SNE and UMAP. These methods emphasize neighborhood relationships, so they can be useful for exploring groups of examples. Their axes and distances are harder to interpret directly. We’ll use PCA here because the linear axes make it easier to follow the arithmetic of an edit.
What does a mean vector mean?
Suppose we have three vectors: [2, 4], [4, 8], and [6, 6]. To average them, we average each coordinate separately. The first entries give us 4; the second entries give us 6. Our mean vector is therefore [4, 6].
The same calculation works with 2,048 coordinates. Our estimation set contains 64 benign requests and 64 harmful requests. At a chosen block, we calculate one mean for each group:
μ_b = average of the 64 benign vectors μ_h = average of the 64 harmful vectors
Each mean still contains 2,048 numbers. Averaging examples changes how many vectors we have, while keeping the width of each vector the same.
μ_b = [0.044, -0.108, 0.026, -0.021, -0.038, -0.015, …] μ_h = [-0.037, -0.091, 0.085, 0.044, -0.050, -0.022, …] Δ = [-0.081, 0.018, 0.059, 0.065, -0.011, -0.008, …] d = [-0.039, 0.009, 0.028, 0.031, -0.005, -0.004, …] Actual first six coordinates at block 11, rounded for reading.
Each cross is the mean of one group, calculated in the full space and then projected onto the PCA axes. The line connects the benign mean to the harmful mean.
The crosses mark the centers of the groups. We can calculate a center in the full space and then project it, or average the projected points; PCA gives the same location either way.
From two means to one direction
Subtracting the benign mean from the harmful mean gives us Δ = μ_h − μ_b. Think of this as an arrow from one center to the other. To use its orientation independently of its length, we divide by its length:
d = Δ / ||Δ||₂
The double bars mean “length.” After this division, d is a unit vector: its length is one.
We now have a candidate direction to test. Because our groups can differ in topic and wording, the direction can contain those differences too. To find out what it does, we need to intervene and observe the model’s responses.
How do we know which direction to target?
We don’t know in advance. Taking the difference of means proposes a candidate; experiments tell us whether changing that candidate affects the behavior we care about.
Let’s separate those two steps. First, we collect benign and harmful requests and save their vectors at matching blocks and token positions. We also examine the baseline responses: a harmful request label alone does not tell us that the model refused it. We calculate a candidate mean direction at each chosen site using the fitting examples.
Next, we intervene on separate requests. We remove the candidate component and measure how the responses change. We can also test the reverse intervention by adding a component along the direction. If removal reduces refusal and addition increases it, that provides stronger evidence that this direction participates in refusal. These are two distinct experiments, with their own intervention strengths.
We need comparisons too. An unchanged-model run gives us the baseline. Equally sized edits along random unit directions help us check whether the effect is specific to our candidate. We also check benign responses, task correctness, and incomplete outputs, since a broken or unfinished response could appear to contain fewer refusals.
If we compare several blocks or strengths, we choose among them using a selection set. We then freeze that choice and evaluate it on a fresh test set. This lets us distinguish a direction that works on new examples from one chosen because it happened to look good on the examples we inspected.
So the sequence is estimate a candidate → intervene → compare with controls → test on fresh examples. A PCA gap helps us describe the vectors, but the response-level intervention supplies the evidence for targeting d. The original single-direction paper connects its identified directions to refusal through removal and addition experiments.
What our LFM3 visualization establishes
Our displayed direction comes from 64 benign and 64 harmful-labeled estimation prompts. The two new account-security requests illustrate the resulting geometry; they did not determine the direction. Their capture and saved-vector projection do not by themselves establish a causal refusal effect. The completed LFM3 tool comparisons measure consequences of fixed edits, while refusal-effect matching and broader causal confirmation remain separate evaluation work.
Removing a component
We can split a vector into a part along d and a part perpendicular to d. The dot product x·d tells us how far x extends along that unit direction. Multiplying this number by d gives us the parallel part:
parallel part = (x·d)d perpendicular part = x − (x·d)d
Let’s draw this with x = [3, 4] and d = [1, 0]. The dot product is 3, so multiplying it by d gives the parallel vector [3, 0]. Subtracting that from x leaves the perpendicular vector [0, 4].
The purple arrow is (x·d)d and the teal arrow is x − (x·d)d. Follow them head-to-tail to reach x. The black arrow has length one. Rotate d to see how the two components change while x stays fixed.
The purple arrow follows d. The teal arrow starts where the purple arrow ends; following both takes us to x. Their sum is therefore x. The small square marks the right angle between the components. The shorter black arrow shows d itself, with length one.
Open Explore this plot and rotate d. We keep x fixed while its two components change. The dot product is a signed number; multiplying by d turns that number into a vector. If the dot product becomes negative, the parallel arrow points opposite to d.
Here are the component magnitudes for our two requests, calculated using all 2,048 coordinates:
For each captured request, we calculate the part along d and the part perpendicular to it. The calculation uses all 2,048 coordinates at one block.
Why subtract the parallel part?
So far, we’ve described the geometry. To understand the purpose, let’s suppose experiments show that d contributes to the model’s refusal behavior. We want to test what happens when the model can no longer carry a component along that direction at the edited site.
The parallel part is exactly the component this intervention targets. We subtract it and leave the perpendicular part unchanged:
x′ = x − (x·d)d = x_perpendicular x′·d = x·d − (x·d)(d·d) = 0 Because d has unit length, d·d = 1.
In our example, x = [3, 4] has a coordinate of 3 along d = [1, 0]. Subtracting [3, 0] gives [0, 4]. We have set that coordinate to zero while keeping the perpendicular coordinate of 4. Subtracting d alone would instead give [2, 4], leaving a component along the direction.
What does the perpendicular part represent?
It is everything in this particular vector that remains after removing the component along d. In the example, the remaining vector is [0, 4]. Its dot product with d = [1, 0] is 0×1 + 4×0 = 0, so it has no component along that direction. This is what “perpendicular” means here.
Which coordinate becomes zero?
We can imagine choosing a new set of axes with d as the first axis. At full strength, projection sets the coordinate along d, measured by x′·d, to zero. It keeps the coordinates on the perpendicular axes. This does not generally set one of the original vector’s numbered entries to zero.
Play the removal and watch the purple component and orange Along d bar shrink to zero. The perpendicular coordinate stays fixed. At 45°, the final vector is [0.5, −0.5]: both original entries are nonzero, but its coordinate along d is zero. Switch to horizontal d to compare with [0, 2]. This is synthetic geometry, not a model measurement.
Open Explore this plot, then choose Remove the component. Blue shows the original x = [3, 2], orange shows the changing x′, and purple shows how much remains along d. Watch the orange “Along d” bar shrink to zero while the perpendicular bar stays the same. The teal arrow shows the movement from x to x′; at full strength, x′ lies on the teal line perpendicular to d.
With horizontal d = [1, 0], the result is [0, 2]. Here the coordinate along d happens to be the first entry. Switch to diagonal d = [1/√2, 1/√2] and play again. Now the result is [0.5, −0.5]. Both original entries are nonzero, but their contributions along d cancel:
x′·d = 0.5/√2 − 0.5/√2 = 0
The sliders and readout let us distinguish the original entries [x′₁, x′₂] from the coordinate along the chosen axis x′·d. At partial strength, the remaining coordinate is (1 − α)(x·d); it reaches zero when α = 1.
In LFM3’s 2,048-dimensional space, there are 2,047 independent perpendicular directions. They usually involve combinations of the original coordinates, rather than a particular set of numbered neurons.
The geometry does not give those remaining directions semantic names. They could carry information about the request’s topic, wording, context, or other properties. Some refusal-related information could remain there too. A zero dot product with one chosen d does not mean that all refusal mechanisms have disappeared.
We leave this remainder unchanged because our experiment targets one direction. That limits the immediate geometric change while letting us test the effect of removing that component. Whether useful behavior is preserved depends on how later layers process the edited vector, which we evaluate separately.
Why keep the rest unchanged?
Among all vectors with zero component along d, this perpendicular projection is the closest to x in Euclidean distance. That gives us a precise geometric reason for choosing it. How the rest of the network responds still has to be measured.
The behavioral motivation comes from intervention experiments. In the original single-direction paper, removing an identified direction suppressed refusal, while adding that direction could induce refusal on benign requests. Those tests connect the direction to behavior. A difference between group means, or a gap in a PCA plot, only gives us a candidate to test.
For our LFM3 example, the local calculation guarantees zero projection at the edited site. We still need model responses to establish its effect on refusal and useful capabilities. The direction can overlap other information, and later blocks can change the representation again.
Choosing how much to remove
We can remove only a fraction of the parallel part by introducing a strength α:
x′ = x − α(x·d)d
At α=0, x stays as it was. At α=0.5, half of the parallel component remains. At α=1, the component is removed completely. The strength refers to this vector operation; a value of 0.5 does not mean that half of a model’s refusal behavior has disappeared.
The remaining coordinate is x′·d = (1 − α)(x·d). Full projection sends it to zero whether its original value was positive or negative. Zero is the reference chosen by this operation; the affine-editing section explores choosing a different reference.
The lines connect the original and edited saved vectors at block 11. Both are drawn with the baseline PCA axes. We edit the vectors directly for this calculation; no new response is generated.
For this figure, we edited the saved vectors in the full space and then projected them onto the original PCA axes. The lines connect each request’s original and edited positions. This calculation shows how the vectors move; measuring a changed response would require running the rest of the model with the intervention.
A smaller example
Let’s repeat the operation with two-dimensional vectors so we can see the whole space:
Faint points mark the original vectors and solid points mark the edited ones. Increase α to remove more of the component along d. In two dimensions, full projection leaves the points on a line.
Use the strength slider to move from the faint original points to the solid edited points. At full strength, every point lands on the line perpendicular to d. In a space with 2,048 dimensions, removing one direction instead leaves a space with 2,047 dimensions.
Our activation hook applies this operation during a forward pass. We’ll see how a related operation can be applied to a weight matrix in the Heretic section.
d=mean_direction(H,B)# One row per exampleedited=project(x,d,strength=0.5)
Repository
Heretic: search and weight edits
We’ve seen how to calculate and remove a direction. Heretic adds a search over the choices behind that edit. Let’s look at how it changes weight matrices, learns low-rank updates, and compares the resulting models.
In the single-direction example, we chose a direction and applied a projection. This leaves several decisions open. Which blocks should we change? How strong should the edit be? How do we compare its effect with the changes it makes to useful responses?
Heretic brings these decisions into a search procedure. It proposes a configuration, modifies the model, measures the result, and uses the scores to guide later trials. We’ll look at two ways it constructs an edit: a directional modifier and Arbitrary-Rank Ablation, or ARA.
We’ll refer to revision cd315cb, so the explanation corresponds to a specific version of the code.
The directional modifier
Let’s return to our account-protection and account-theft requests. The difference between their groups’ mean vectors gives us a candidate direction. As we saw earlier, a vector’s component along that direction can be reduced by projection.
The directional modifier applies a related operation to matrices that write into the residual stream. For a writer W and a unit direction d, the basic output-side edit is:
This changes what the writer produces along d when future inputs pass through it. Heretic also allows the candidate direction to be cleaned against a good-behavior reference, and it offers row normalization to preserve matrix-row lengths.
The direction can vary by layer, or it can be taken from an interpolated depth. The edit strength can also vary across layers. A peak weight sets the largest change, a peak position places it in the network, and a decline distance controls how it spreads toward a minimum weight. We can therefore compare a concentrated edit with one spread over more of the model.
The protection and matrix plots below work through these operations individually. Full row normalization changes the effective update, which the implementation stores with a low-rank approximation. See the directional modifier for the exact calculation.
Learning an update with ARA
ARA takes a different starting point. Instead of choosing one direction and deriving a projection, it learns a low-rank change to a writer:
W′ = W + BA
A and B are the smaller matrices that parameterize the update. To fit them, we collect local inputs and outputs for two sets of examples: good behavior we want to preserve and bad behavior we want to change.
The loss combines three ideas. Keep the new good-behavior outputs close to their original values. Move bad-behavior outputs toward nearby good-behavior outputs. Optionally push them away from nearby bad-behavior outputs:
loss = λ_keep × good-output error + λ_steer × (distance to good neighbors − λ_away × distance to bad neighbors)
Let’s draw one good reference and one bad reference, together with their current outputs. The hollow points stay fixed. The filled points are the outputs we would like the fit to adjust:
Here, “good” and “bad” identify the prompt groups. The points are numerical outputs of a local writer, rather than generated answers or response-quality scores.
Hollow points are frozen references and filled points are current outputs. Blue preserves good outputs, green attracts bad outputs toward good references, and red repels them from bad references. The dashed arrow combines the bad-output terms. These are scaled negative-gradient directions in a one-neighbor numerical example.
The blue arrow pulls the new good output back toward its original value. Its squared-error term decreases as the two points get closer. The green arrow pulls the new bad output toward the original good reference, reducing a positive distance term.
The red arrow pushes the new bad output away from the original bad reference. Why away? This distance enters the loss with a minus sign. Increasing the distance makes that term more negative, which lowers the total loss. The dashed black arrow combines the green and red directions.
Open Explore this plot and change the three weights. Setting overcorrection to zero removes the red push. Setting steering to zero removes both green and red contributions. Increasing preservation strengthens the blue pull without changing those two bad-output terms.
These arrows show scaled negative gradients at the displayed points. Their lengths describe the current loss incentives. Heretic changes the writer’s A and B matrices, and both groups’ outputs depend on those shared weights, so the points cannot be moved independently as free parameters. This small example uses one neighbor; the full fit averages over selected neighborhoods.
The λ values are weights that control the balance between these terms. The neighbor count determines how many nearby outputs contribute to each distance calculation. A layer interval chooses which writers are modified, and optional rescaling preserves their original row magnitudes.
For our running example, the aim would be to preserve the account-protection representation while changing the account-theft representation. Fitting this requires groups of examples, rather than just our two requests. It also needs evaluation after the local fit: later layers still have to turn these writer outputs into responses.
The pinned ARA implementation performs this local numerical optimization. The writer-fit figure below uses our simpler local primitive to make the loss visible.
Which parameters change in a trial?
A trial is one proposed set of settings. Here are the main choices exposed by the two modifier families:
Family
Parameters
Effect
Directional
Direction index or layer-local direction
Chooses the activation direction used in the edit
Directional
Peak weight and peak layer
Sets the strongest change and its location
Directional
Minimum weight and decline distance
Controls how strength varies across depth
ARA
Start and end layer
Selects the interval of modified layers
ARA
Preservation and steering weights
Balances keeping good outputs with changing bad outputs
ARA
Overcorrection weight and neighbor count
Controls repulsion from bad outputs and the local reference sets
There are also configuration choices such as adapter rank, optimizer settings, normalization, datasets, response length, and scorers. A study can hold these fixed or vary them. We’ll distinguish the settings that actually changed in our experiments when we reach the sweep results.
Reducing refusals is only one part of the evaluation. We also want to know how the edited model differs on ordinary requests.
One way to measure this is Kullback–Leibler divergence, or KL divergence. It compares two probability distributions. Here the baseline model supplies one distribution over next tokens and the edited model supplies the other.
We can work through the calculation with just two outcomes: a coin landing Heads or Tails. Let P assign probability 0.5 to each outcome. Let Q assign 0.9 to Heads and 0.1 to Tails. Each distribution still adds up to one.
For each outcome, we take the log probability ratio and weight it by how often that outcome occurs under P. The symbol Σ means to add the terms, and ln is the natural logarithm, so the result is measured in nats.
Blue P and orange Q are two heads/tails distributions. The lower bars show the two weighted log-ratio terms and their sum. Terms may be negative; total KL is nonnegative. Change the probabilities or swap the direction to see the weighting change.
The blue and orange bars show P and Q. Below them, we calculate the Heads and Tails contributions. In this example, Heads contributes about −0.294, Tails contributes about 0.805, and the sum is 0.511 nats. One outcome’s contribution can be negative even though the complete KL divergence is nonnegative.
Tails has probability 0.5 under P but only 0.1 under Q, so it produces a positive penalty. Increase Q(Heads) to make Q(Tails) even smaller and watch that contribution grow. If we instead make Q match P, both contributions and their sum become zero.
Open Explore this plot to change both distributions or swap the KL direction. Swapping P and Q changes which distribution supplies the weights: KL(Q ∥ P) is about 0.368 nats for the initial example. For the language model, the same sum runs over vocabulary tokens instead of two coin outcomes.
In the pinned KL scorer, this comparison uses the first-token distribution on good-behavior prompts, in the direction KL(baseline ∥ edited). A small value means these particular distributions are close. It leaves other questions open, such as whether the model can complete a calculation or call a tool with the right arguments. The scorer source shows the exact readout.
This is why our later comparisons include function calling and complete agent tasks alongside distribution drift.
Working through the individual operations
We’ll now examine protection, writer projection, normalization, low-rank storage, and local fitting one at a time. Together, they explain the building blocks behind the two modifier families.
Upstream Heretic and the local experiments
The measured Qwen and LFM3 studies used our local harness and predefined grids. They did not run upstream Heretic Optuna or ARA. The writer-fit figure demonstrates our local ARA-style primitive. Residual-vector rescaling is also a local control, distinct from Heretic’s weight-row normalization. The SAE, component-mask, token-penalty, and supervised-training examples later in this section are companion techniques implemented in this project.
Protecting a reference direction
Our two requests both discuss accounts and passwords. When we subtract their groups’ means, some shared information may still overlap the resulting direction. We can choose a reference direction that we want the edit to preserve.
A simple choice is the benign mean. We take our candidate d, remove its component along that mean, and normalize what remains. Let’s call the result d_protected:
d_protected ∝ d − projection of d onto the protected span x′ = x − α(x·d_protected)d_protected
The symbol ∝ means “proportional to”: we still need to divide the result by its length. We then use the new direction in the same projection operation as before.
Cleaning d against the benign mean turns the edit perpendicular to that reference. Follow the connecting lines to see how this changes each point’s destination.
The points now move along a direction perpendicular to the protected reference. This preserves their coordinate along that reference. Other coordinates can still change, including those of benign examples.
We can also supply several reference vectors. In that case, we protect their span: all the directions formed by their linear combinations.
Let’s picture two references, u = [2, 0, 0] and v = [1, 2, 0], in three dimensions. Both lie in the plane z=0. Adding any real multiple of u to any real multiple of v keeps us in that plane:
protected span = {a u + b v : a and b are real numbers}
Orange u and purple v span the shaded plane. Cyan is a u + b v, controlled by the two sliders. Cleaning the blue candidate removes its gray in-plane component and leaves the green perpendicular remainder. This is a 3D example projected onto the page, so screen angles are distorted.
The orange and purple arrows are our references. The cyan arrow is one combination a u + b v. Open Explore this plot and change either coefficient to move it around the protected plane, including in the opposite direction with negative coefficients. The shaded patch shows only part of a plane that extends indefinitely.
We split the blue candidate d into its gray in-plane component and green perpendicular remainder. To build the protected edit direction, we remove the gray component from d and normalize the green remainder. Editing x along this new direction preserves its coordinates along both references, and therefore along every combination in their span.
The diagram uses the unnormalized candidate d = [2, −1, 2] to keep the coordinates simple. Normalizing it before cleaning would give the same final protected unit direction, [0, 0, 1].
Here we are cleaning the editing direction d before applying it to x. The shaded span is what we protect. This drawing projects a three-dimensional example onto the page, so perpendicular directions in 3D may appear tilted in the picture.
If the candidate lies entirely in an exactly protected span, there is no remaining direction to normalize and the implementation raises an error. A ridge parameter allows softer protection with a reference bank. The related biprojected writer operation also normalizes matrix rows; we explain that separately below.
Applying the edit to a weight matrix
An activation hook changes a vector as the model runs. We can also change a matrix that produces contributions to the residual stream. We’ll call such a matrix a writer.
Using row vectors, a linear writer computes y = xWᵀ + b. W has one row per output coordinate and one column per input coordinate. To reduce what it writes along d, we can edit its output side:
The bars compare matrix-row lengths before and after the edits. Row normalization restores these lengths and can change the rank of the effective update.
This preserves a specific quantity: each row’s norm. The rescaling also changes the edit, and it can reintroduce output components along d. It does not generally preserve the matrix’s singular values or the outputs for every input.
Our biprojected writer combines a protected direction with this row-normalized operation.
A post-block residual includes earlier contributions as well as this writer’s output. Projecting that entire residual therefore differs from editing one writer. Bias handling and other writers also matter. See the norm-preserving method explanation and our API for the enforced invariant.
Preserving an activation’s length
We can apply a similar rescaling idea directly to an activation. First we project it, obtaining u. Then we multiply u by the ratio of the original length to the new length:
Blue 1 is the original vector. The orange arrow takes it to orange 2 after projection. The purple arrow then takes it to purple 3 after rescaling. The dashed ray shows the projected direction, while the pale circular arc marks the original length. Choose an example to inspect all three coordinates and lengths at α=0.5.
Follow one example through the two colored movements. Blue 1 is the original x. The orange arrow shows projection taking x to orange 2, the intermediate vector u. The purple arrow then shows rescaling taking u to purple 3, the final x′.
The gray dashed ray runs from the origin through the projected and rescaled points. Rescaling moves along this ray, keeping u’s direction. The pale circular arc marks the original distance from the origin: both the blue and purple points lie on it.
Open Explore this plot and choose an example. The readout lists its coordinates and length before projection, after projection, and after rescaling, followed by the scale factor. The faint gray points show the original example cloud; you can hide them to focus on the selected movement.
Each point ends at the same distance from the origin as it started. Its orientation changes, so later layers can still read it differently. Two vectors with the same length can carry very different information.
Our expanded LFM3 study used this operation at strength α=0.5. It is a runtime residual edit; the row normalization in Heretic operates on weight matrices.
Numerical details
A zero vector cannot be rescaled to recover information removed by full projection. The partial projection at α=0.5 avoids complete rank-one annihilation of a nonzero vector. Conversion back to BF16 can introduce rounding. Preserved activation length is checked separately from task quality and exported-checkpoint equivalence.
Representing an update with two small matrices
Suppose we have calculated a change ΔW to a matrix W. The edited matrix is W′ = W + ΔW. If the change has low rank, we can represent it with two smaller matrices:
ΔW ≈ BA B: output × r · A: r × input
The intermediate width r is the stored rank. A smaller r needs fewer values, but may only approximate the original update.
We approximate a 3×3 update using B×A. Higher rank keeps more singular components; rank three reproduces the full numerical update.
The figure uses SVD to factor a 3×3 update. As we increase the stored rank, we keep more singular components and reduce the reconstruction error. At rank three, the factorization reproduces the full numerical update.
How this relates to LoRA
Low-Rank Adaptation, or LoRA, learns factors A and B while keeping the base matrix fixed. We can also factor an update we have already calculated. The algebra is related, but only the first case learns those factors through training.
A plain rank-one projection update can be stored exactly at rank one. Extra normalization or local fitting can produce a higher-rank change.
The factorization returns matrices and an approximation error. A usable adapter also needs target-module mappings, scaling, serialization, and merge checks. Our training API can attach PEFT LoRA parameters to supplied modules. A tested LFM3 exporter and runtime-versus-exported equivalence remain separate work.
Learning a writer update from examples
Instead of deriving an update from a direction, we can learn it from a writer’s input and output examples.
We first run benign and source inputs through the original writer. We then fit low-rank factors A and B. The loss penalizes changes to benign outputs and uses distances to reference neighborhoods to guide the source outputs. Optional row normalization is included in the effective matrix during fitting.
LBFGS fits low-rank factors on local numerical inputs and outputs. Each point is an outer optimization step. The loss balances benign-output preservation with source-neighborhood terms.
The curve shows LBFGS fitting on a small matrix and numerical inputs. Each point is an outer step; the optimizer can take several inner iterations within it.
Choosing what to preserve
The preservation weight controls how strongly the fit resists changes on benign examples. The steering weight, neighbor count, and overcorrection weight control how source outputs move. The stored rank limits the update the optimizer can express.
Keeping local outputs close is useful, but we still need to test the full model: later layers process these outputs and can amplify small differences.
This figure uses our local ARA-style numerical primitive. The bridge can invoke the pinned upstream executable, but the completed model experiments used fixed grids. Neither this local fit nor those grids are an upstream ARA/Optuna run.
Comparing settings in a sweep
We now have several choices: which direction to use, how strongly to edit it, and which blocks to change. A parameter sweep runs a collection of settings so we can compare their effects.
Our Qwen follow-up used 17 fixed configurations: an identity baseline, nine strength-and-coverage settings, and seven controls. The first LFM3 study used six settings that varied mean-projection strength and block coverage. The expanded LFM3 comparison used identity plus five methods at strength 0.5 across all 24 blocks.
These studies used predefined grids. Heretic’s automatic Optuna search is a separate procedure, described earlier in this section.
Each point is one of six fixed LFM3 configurations. Compare tool correctness with benign distribution drift. The configurations were not matched for the amount of refusal change.
Each point represents a measured LFM3 configuration. The horizontal position shows benign distribution drift; the vertical position shows tool correctness. Looking at both helps us see whether small distribution changes accompany useful task performance.
Fitting, choosing, and testing
We use the estimation split to fit directions and other parameters. If we choose a configuration from several candidates, we use a separate selection split and freeze the choice. Finally, the test split measures performance after that decision.
This separation matters because choosing the best-looking test result would use the test data to make the method look better.
The generation budget
A model may spend its token budget thinking and never produce a final answer. We keep these incomplete outputs visible when scoring results. We also chose longer-budget repeats before inspecting failures, so the comparison would not depend on which cases happened to look interesting.
Exact settings and limits
The chart does not match methods for refusal effect, so it cannot identify the best capability-preserving method at equal refusal change. Every tested configuration, including ties and losses, remains in the reports.
Evaluating tool use
Let’s now look at what happened when we tested the edited models on tasks. We wrote 32 new tasks across eight families and compared six fixed configurations through two interfaces.
Native mode uses a short tool-calling loop. Hermes mode uses the genuine Hermes agent with direct tool exposure and enforcement enabled. Both use the same lookup, calculation, and submission handlers.
Task success is checked by independently replaying tool effects. The suite contains 32 authored tasks across eight families; Hermes uses the direct-tool condition.
To count a task as successful, the agent must look up the required records and submit the correct number under the exact task ID. We replayed tool effects independently. This lets us distinguish an agent that completes a task from one that merely says it has finished.
Reading the results
A correctly formatted tool call can still contain the wrong arguments. Correct arithmetic submitted under a record ID instead of the task ID also fails the task rule. We therefore report both function-calling benchmark results and complete task outcomes:
Fixed arm
Fresh BFCL
Native tasks
Hermes direct
Original
170/192
32/32
32/32
Mean
174/192
32/32
32/32
Protected mean
175/192
32/32
32/32
SVD rank 2
170/192
32/32
32/32
Conditional
173/192
32/32
32/32
Residual norm
174/192
32/32
32/32
The expanded comparison contains 1,248 BFCL responses and 480 agent episodes, including the longer-budget repeats. BFCL tests function calling; the authored tasks also require linked actions across a short workflow.
Interpreting the comparison
These results describe one checkpoint and this task setup. They give us concrete outcomes to inspect, while leaving cross-model confirmation as a next step.
Experiment scope
The suite contains eight authored families. Budget repeats are correlated sensitivity checks rather than independent task templates. The native interface uses a custom HF XML adapter, and the 16 benign diagnostic passages are reused. The original Hermes gateway had baseline compatibility failures; those remain in the first report and are separated from edit-induced damage. Historical Qwen math and code used different budgets, and absolute perplexity cannot rank models with different tokenizers. The fixed configurations were not matched for refusal effect.
Additional technique · implemented locally
Editing a sparse feature
A sparse autoencoder, or SAE, learns to describe a vector using a larger dictionary of features. Its encoder produces feature activations z. Its decoder combines the active features to reconstruct the input. “Sparse” means that only a small part of the feature dictionary is active for a given input.
If we select a feature, we can subtract its decoder contribution from the original vector:
z = ReLU(xE + b) x′ = x − z_selected D_selected
E is the encoder matrix, D is the decoder matrix, and b is the encoder bias. For a model with 2,048 hidden dimensions and F features, E has shape [2,048, F] and D has shape [F, 2,048].
A hand-chosen identity ReLU dictionary makes the subtraction visible. Removing the positive second-coordinate feature leaves the negative residual component in place. No trained SAE is used in this example.
This small example uses a hand-chosen identity dictionary. ReLU sets negative feature activations to zero, so removing the positive second-coordinate feature leaves a negative residual component in place.
We subtract from the original x. This keeps the autoencoder’s reconstruction error in the result instead of replacing x with the whole reconstruction.
Python example: does an active feature help predict a city?
Suppose we want to investigate the completion “The Eiffel Tower is located in Paris.” We can take a trained GPT-2 SAE, find its most active feature at the final input position, and remove that feature’s contribution. We then measure the probability of the next token, “ Paris.”
We use GPT-2 here because the public SAE was trained on GPT-2 activations at this exact capture site. The SAELens tutorial explains loading these trained dictionaries.
Why do we need a dictionary for the same model?
An SAE’s dictionary is its collection of learned feature vectors: the rows of the decoder matrix D. Each vector describes a pattern the SAE learned from activations at a particular place in a particular model. The encoder estimates how strongly those features are active in a new residual vector.
The GPT-2 SAE below expects a residual vector with 768 coordinates, and each of its decoder feature vectors also has 768 coordinates. LFM3’s residual vectors have 2,048 coordinates. We cannot feed a 2,048-coordinate vector into an encoder that expects 768, or subtract a 768-coordinate feature contribution from it.
Matching the dimensions would solve the shape problem, but we would still need to check what the directions mean. Two models can both have 2,048 coordinates while arranging learned patterns differently within that space. A direction that detects a pattern in one model may point somewhere unrelated in another. We can think of them as two maps: both use coordinates, but the same coordinates on each map need not describe the same place.
The capture site matters too. A dictionary trained on the residual stream entering one block is not automatically suitable for the residual stream leaving another block, even within the same model.
For our LFM3 experiment, we therefore need a dictionary learned from LFM3 activations at the layer and capture point we want to edit, using the same activation preprocessing. Transferring a dictionary between models would require a separately validated mapping between their representations.
importtorchfromsae_lensimportSAEfromtransformer_lensimportHookedTransformerdevice="cuda"iftorch.cuda.is_available()else"cpu"model=HookedTransformer.from_pretrained("gpt2-small",device=device)model.eval()loaded=SAE.from_pretrained(release="gpt2-small-res-jb",sae_id="blocks.7.hook_resid_pre",device=device,)# Older SAELens releases also returned config and sparsity metadata.sae=loaded[0]ifisinstance(loaded,tuple)elseloadedsae.eval()site="blocks.7.hook_resid_pre"tokens=model.to_tokens("The Eiffel Tower is located in",prepend_bos=True)target=model.to_single_token(" Paris")withtorch.inference_mode():baseline,cache=model.run_with_cache(tokens,names_filter=[site])x=cache[site][:,-1:,:]# [batch, 1, 768]z=sae.encode(x)# [batch, 1, number_of_features]feature=int(z[0,0].argmax())assertz[0,0,feature]>0,"No active feature at this position"z_edited=z.clone()z_edited[...,feature]=0# Keep the original reconstruction error: x + decode(z') - decode(z).delta=sae.decode(z_edited)-sae.decode(z)defremove_feature(residual,hook):edited=residual.clone()edited[:,-1:,:]+=delta.to(residual)returneditedchanged=model.run_with_hooks(tokens,fwd_hooks=[(site,remove_feature)])forname,logitsin[("original",baseline),("feature removed",changed)]:probability=logits[0,-1].float().softmax(-1)[target].item()print(name,"P( Paris) =",probability)print("Selected feature:",feature)
The feature index comes from the prompt’s activations, rather than a guessed label. If removing it lowers the probability of “ Paris,” it supports that prediction in this context. If the probability rises, it was suppressing the prediction; if it barely changes, its large activation did not imply a large effect on this output. To understand what the feature represents, we would inspect other activating texts and repeat the intervention on held-out prompts.
Using this with a language model
A model experiment needs trained SAE weights for the correct model and capture site, a feature-selection rule, and held-out intervention tests. This figure demonstrates feature subtraction with a hand-specified dictionary. It does not identify an LFM3 refusal feature. SAE editing is a local companion control in this project. The Python example requires SAELens and TransformerLens and downloads the matched pretrained model and SAE; it is a reproduction recipe, not a reported GPT-2 experiment. The selected SAE has no activation normalization, so the decoded difference is in the residual stream’s coordinates.
Additional technique · implemented locally
Editing a head or neuron
Many components contribute to the residual stream. We can intervene on an individual component before its output is added to that stream.
For an attention head, we can mask its output before the attention output projection. For an MLP neuron, we can mask its activation before the MLP’s output matrix maps it into residual coordinates.
We mask neuron 1 in a four-neuron example. In a model, the output writer maps each neuron’s contribution into residual coordinates.
Here we set one of four neuron activations to zero. In a model, the output matrix spreads a neuron’s contribution across residual coordinates. Removing a neuron can therefore affect many coordinates at once.
Testing a component’s effect
Activation patching gives us a way to test a component. We first save an activation from a reference run. We then insert a chosen value at the corresponding site in another run and measure how the output changes.
Repeating this over layers and token positions produces a patching heatmap. Each cell records the effect on a specified output metric. Patching an activation with its own original value provides a useful check that the intervention machinery is working.
Python example: does a component affect an arithmetic answer?
Let’s ask Qwen to calculate 17 + 25. We will measure its probability of answering “42,” first normally, then with one attention head removed, then with one MLP neuron removed. Each intervention runs separately, and the context manager removes its hook afterward.
importtorchfromtransformersimportAutoModelForCausalLM,AutoTokenizerfromrefusal_audit.instrumentationimporthead_intervention,neuron_interventioncheckpoint="models/qwen3-4b-instruct-2507"tokenizer=AutoTokenizer.from_pretrained(checkpoint)model=AutoModelForCausalLM.from_pretrained(checkpoint,dtype="auto",device_map="auto").eval()text=tokenizer.apply_chat_template([{"role":"user","content":"What is 17 + 25? Reply with the number only."}],tokenize=False,add_generation_prompt=True,)inputs=tokenizer(text,return_tensors="pt").to(model.device)answer_ids=tokenizer.encode("42",add_special_tokens=False)answer=torch.tensor([answer_ids],device=model.device)joined=torch.cat([inputs.input_ids,answer],dim=1)prompt_length=inputs.input_ids.shape[1]@torch.inference_mode()defprobability_of_42():# Teacher forcing: score each answer token given all preceding tokens.logits=model(input_ids=joined,attention_mask=torch.ones_like(joined)).logitsanswer_logits=logits[:,prompt_length-1:-1,:].float()log_probs=answer_logits.log_softmax(-1)token_log_probs=log_probs.gather(-1,answer.unsqueeze(-1)).squeeze(-1)returntoken_log_probs.sum().exp().item()original=probability_of_42()# Indices start at zero: layer 8 is the ninth decoder block.withhead_intervention(model,layer_index=8,head_indices=[0]):without_head=probability_of_42()withneuron_intervention(model,layer_index=8,neuron_indices=[100]):without_neuron=probability_of_42()restored=probability_of_42()print("Original:",original)print("Head removed:",without_head)print("Neuron removed:",without_neuron)print("Restored:",restored)
The head hook sets its output slice to zero before self_attn.o_proj. The neuron hook sets one intermediate activation to zero before mlp.down_proj. These hooks act at every input position in the selected block. They leave the weights in place.
Head 0 and neuron 100 are candidates to test, not components we have identified as arithmetic specialists. A lower answer probability shows an effect on this particular prediction. To test specialization, we would choose candidates on a discovery set and compare their effects on separate arithmetic, factual, and ordinary-language prompts. We score every token in “42,” since a number can span several tokens. This probability does not measure whether a freely generated answer is correct, and it does not include the probability of stopping after the number.
Architecture and experiment details
The four-neuron figure is a numerical example, and this project has not completed a head-discovery scan of every LFM3 block. We ran the arithmetic code above on the local pretrained Qwen checkpoint: the original, head-removed, neuron-removed, and restored conditions all printed probability 1.0 at the computed precision. This saturated one-prompt measurement does not establish arithmetic specialization or the absence of other effects.
Additional technique · implemented locally
Changing a token’s score
We can also intervene after the output head, just before choosing the next token. A logit penalty subtracts a value from selected vocabulary scores.
Remember that softmax converts all the scores into probabilities together. Lowering one score changes its probability and redistributes probability to other tokens.
Subtracting four from the score for “cannot” lowers its probability and increases the others. This example vocabulary contains four tokens.
This vocabulary has four example tokens. We subtract four from the score for “cannot.” Its probability falls, while the other tokens become more likely.
A real model has many ways to express a refusal. Penalizing “cannot” may change the wording, and it may also affect a useful answer that needs that word. We therefore evaluate the completed response as well as any vocabulary-level change.
Python example: a calmer customer-support reply
Suppose our support assistant uses too many exclamation marks. We can lower the score of the standalone “!” token while it writes a reply. A Transformers logits processor receives the vocabulary scores at each generation step and returns the modified scores.
importtorchfromtransformersimportAutoModelForCausalLM,AutoTokenizer,LogitsProcessorListfromrefusal_audit.instrumentationimportsuppress_token_logitscheckpoint="models/qwen3-4b-instruct-2507"tokenizer=AutoTokenizer.from_pretrained(checkpoint)model=AutoModelForCausalLM.from_pretrained(checkpoint,dtype="auto",device_map="auto").eval()text=tokenizer.apply_chat_template([{"role":"user","content":"Write a warm two-sentence support reply confirming that my refund is approved."}],tokenize=False,add_generation_prompt=True,)inputs=tokenizer(text,return_tensors="pt").to(model.device)exclamation_ids=tokenizer.encode("!",add_special_tokens=False)assertlen(exclamation_ids)==1,"Check this tokenizer's punctuation tokens"processor=suppress_token_logits(exclamation_ids,penalty=4.0)withtorch.inference_mode():scores=model(**inputs).logits[:,-1,:].float()changed_scores=processor(inputs.input_ids,scores)token_id=exclamation_ids[0]print("Original P(!):",scores.softmax(-1)[0,token_id].item())print("Edited P(!):",changed_scores.softmax(-1)[0,token_id].item())forname,processorsin[("Original",LogitsProcessorList()),("Calmer",LogitsProcessorList([processor])),]:output=model.generate(**inputs,max_new_tokens=80,do_sample=False,logits_processor=processors,pad_token_id=tokenizer.eos_token_id,)reply=output[0,inputs.input_ids.shape[1]:]print(name,tokenizer.decode(reply,skip_special_tokens=True))
Subtracting 4 multiplies this token’s odds against each unchanged token by exp(−4), approximately 0.018. The printed probabilities include softmax’s normalization. The edited reply can still match the original if another token already had the highest score. Other vocabulary entries can contain exclamation marks too, so penalizing this one ID is a preference rather than a punctuation guarantee.
Using the decoding control
The logit-suppression context restores the original output path afterward. Record the exact vocabulary IDs, penalty, prompts, and generation budget. This is a local decoding control. The model’s tokenizer may split the example word differently, and the four-token figure does not measure semantic refusal removal. Running the support-reply code on the local pretrained Qwen checkpoint reduced the selected token’s first-step probability from approximately 1.51 × 10⁻¹¹ to 2.76 × 10⁻¹³. Both greedy replies were identical and contained no exclamation marks.
Additional technique · implemented locally
Fine-tuning after an edit
An edit can affect useful behavior as well as refusal. One way to study recovery is supervised fine-tuning, or SFT. We give the model a prompt and a desired completion, then update parameters to make that completion more likely.
In our implementation, prompt labels are set to −100 so they are ignored by the completion loss. The prompt still provides context; the loss scores the model’s next-token predictions on the completion.
Twenty training updates on a randomly initialized tiny Qwen model, using two repeated arithmetic examples. The completion tokens contribute to the loss; prompt labels are masked.
This curve comes from 20 updates on a randomly initialized tiny Qwen model, using two repeated arithmetic examples. It illustrates how completion training reduces the fitting loss.
Designing a recovery experiment
To study recovery on a pretrained model, we would compare four conditions: the original model, the edited model, fine-tuning alone, and editing followed by fine-tuning. Separate evaluation data would show which capabilities recover and how refusal behavior changes.
The plotted training uses a random model and hand-tokenized examples. Pretrained LFM3 repair remains planned work. LoRA can limit which parameters receive updates, but its effects on recovery and the original edit must be measured.
Further reading
The original papers and Heretic repository provide the research behind the methods in this guide.
An edit does not have to run on every request. Conditional activation steering separates the decision to intervene from the intervention itself. Let’s see how a gate connects those two steps.
So far, projection has affected every vector at the chosen site. What if we want to apply the edit only when a particular condition is present?
Conditional activation steering introduces a gate. We measure the vector along a condition direction c and compare the result with a threshold τ. If it reaches the threshold, we apply the edit along a behavior direction d:
gate opens when x·c ≥ τ if open: x′ = x − α(x·d)d otherwise: x′ = x
The condition and behavior directions can be different. For example, the gate could detect a topic while the edit changes a response tendency.
Only points that reach the condition threshold receive the edit. The condition direction and edit direction differ in this example. The strength slider changes the movement while keeping the gate fixed.
Some points stay in their original positions because their gate is closed. The remaining points move along the edit direction. Changing the strength changes how far those selected points move.
Choosing the threshold
A threshold determines which examples receive the edit. Set it too low and it may include many benign requests; set it too high and it may miss the requests we intended to change. We therefore choose it using fitting or selection data and then test it on separate examples.
For our six-arm LFM3 comparison, we used the same mean direction for c and d. At each block, the threshold was halfway between the two group means’ projected coordinates.
This is a CAST-style primitive. The original paper includes category construction and threshold selection beyond this example. A gate fitted on final input positions also needs testing when applied at generated positions, or after earlier blocks have been edited.
Research paper
RDO / RCO: directions and cones
A difference of means gives us one candidate direction. We can also learn a direction by optimizing the effect of an intervention. In this section, we’ll move from subspace projection to optimized directions and families of directions.
A single arrow may be too simple to describe the differences between our groups. We can instead collect several directions into a matrix Q. Together, they define a subspace.
For the projection formula below, Q’s columns are perpendicular unit vectors. This property is called orthonormality. If we keep r directions in LFM3, Q has shape [2,048, r]:
x′ = x − α(xQ)Qᵀ
The first multiplication finds the coordinates along our chosen directions. The second converts those coordinates back into the component we subtract.
Finding a basis with SVD
One way to choose Q is singular value decomposition, or SVD. Let’s build the matrix it works with before looking at what it finds.
Move the reference point to the benign mean
Imagine that each example has just two coordinates. The blue points are benign examples, and their mean is μB = [1, 1]. One orange harmful example, h = [3, 2], becomes h − μB = [2, 1]. We subtract the same blue mean from every harmful example. The dashed orange lines show this movement: the new vectors describe where the harmful examples lie relative to the benign mean.
Stacking these shifted vectors gives a matrix Z. Each row is one example and each column is one coordinate. Our small animation has six harmful examples, so Z has shape [6, 2]. With N harmful examples at one LFM3 capture site, it would have shape [N, 2,048].
Play the steps: subtract the blue benign mean from the orange examples, reveal green q1 and purple q2, then choose one or two columns for Q. The bars show squared projection energy. At rank one, the final dots lie on the green line; rank two reconstructs the whole shifted plane. This is a synthetic two-coordinate example, and the final approximation is distinct from the subtraction edit below.
Choose Explore this plot, then Play steps to watch the subtraction and the SVD directions appear. The progress slider lets us pause anywhere. At the final step, switch between rank one and rank two: the green and purple columns in Q show exactly which directions we keep.
Find the direction that captures the most
Think of placing a line through the origin and dropping every shifted orange vector onto it. How much of the data does that line capture? For a unit direction q, we square each projection length zᵢ·q and add them:
energy along q = Σᵢ(zᵢ·q)²
SVD finds the unit direction with the largest total. This is the green arrow q1. It then finds the best direction perpendicular to q1: the purple arrow q2. In higher dimensions, it continues with further perpendicular directions. The bars show how much squared projection energy each direction captures. The arrows have convenient display lengths; their lengths do not represent these energies.
We write the decomposition as Z = UΣVᵀ. The columns of V are the directions in coordinate space. The diagonal entries of Σ are the singular values, ordered from largest to smallest. Squaring a singular value gives the energy captured by its direction. U records the corresponding normalized coefficients across examples.
Choose how many columns go into Q
At rank one, Q contains only green q1 and has shape [2, 1]. At the end of the animation, the orange points move onto the green line: this is their rank-one approximation, ZQQᵀ. The dashed green segments are the part that this approximation leaves out. At rank two, Q also contains purple q2. Together the two directions span the whole plane, so the approximation reproduces every shifted point.
For LFM3, keeping two directions gives Q shape [2,048, 2]. Those two arrows capture a plane within a much larger space. We choose the rank as part of the experiment; SVD orders the directions but does not decide how many we should edit.
There is a useful distinction from ordinary mean-centered PCA here. We subtract the benign mean, rather than the harmful group’s own mean. The energy can therefore include both the harmful group’s displacement from the benign mean and its spread around its own center. A leading direction is a candidate to test; a large singular value alone does not establish that it causes refusal.
The animation above keeps the component along Q to explain how SVD summarizes Z. The intervention below subtracts that component from an input vector x: x′ = x − α(xQ)Qᵀ. It operates on the supplied x; subtracting μB was the direction-estimation step, rather than an additional translation in this projection formula.
This example has two coordinates and removes a rank-two subspace. At α=1 the points reach zero. A rank-two edit in 2,048 dimensions would leave 2,046 perpendicular coordinates.
Here, the vectors have only two coordinates and we remove two directions. At full strength, the entire plane is removed and the points reach zero. Removing two directions from a 2,048-dimensional vector would instead leave 2,046 perpendicular coordinates.
The number of directions, r, is the rank of the projector. Increasing it lets the edit change more of the representation. The next two subsections take another approach: learning directions by optimizing what an intervention does.
About this subspace example
SVD is a local comparison method here, rather than the RCO extraction algorithm. Its directions can reflect topic or wording. Sequential projections along nonorthogonal vectors also differ from projecting out their full orthonormal span, so the basis and rank are part of the experiment specification. The animated example uses six explicitly synthetic harmful vectors and four synthetic benign vectors. Its NumPy SVD projectors are checked against our PyTorch estimator at both ranks. Singular-vector signs can flip without changing their span or projector. The production estimator also limits the requested rank to the numerical rank of the input matrix.
Learning the direction through optimization
So far, we have calculated candidate directions from examples. We can also treat the direction itself as a parameter to learn.
To do this, we need a loss function: a number that tells the optimizer how well an intervention meets our goal. For this example, we want edited source points to move toward the benign mean while keeping benign points close to their original locations.
The optimizer starts from a unit direction, applies the edit, and calculates the loss. It uses gradients to update the direction, then divides by its length so it remains a unit vector.
The learned direction minimizes a geometric loss: bring source points toward the benign mean while limiting movement of benign points. The figure uses small numerical examples.
This changes the orientation of the edit. We can follow the loss during training:
The loss is recorded over 60 Adam updates. It measures progress on the numerical objective used in the preceding figure.
The curve records 60 Adam updates. Its decrease shows that the direction is improving on the chosen numerical objective. To optimize language-model behavior instead, we would need an objective computed through model interventions and separate tests of the resulting responses.
Our optimizer supports an RDO-style objective supplied by the caller, including differentiation through model hooks with frozen model weights. The figure uses a geometric objective. The paper’s target-generation and selection protocol are additional steps beyond this primitive.
Learning a family of directions
What if several directions work well? We can represent a family by learning a set of basis vectors and combining them with nonnegative weights. This set of combinations forms a positive cone.
Let Q contain our basis vectors. We sample nonnegative coefficients c, form Qc, and normalize the result to obtain a candidate unit direction. During optimization, we evaluate both sampled combinations and the basis directions, update Q, and restore an orthonormal basis.
Each point on the arc represents a unit direction formed from a nonnegative combination of the two learned basis vectors. These are candidate intervention directions.
Each point on the arc represents a direction from the fitted two-dimensional cone. These points are arrows we could use for an intervention; they are separate from the prompt vectors in our earlier scatter plots.
A cone and a subspace
Choosing one arrow from this family removes one component. Projecting out Q’s entire span removes all of its independent components together. These are different interventions, even though both use the same basis matrix.
This RCO-inspired primitive takes a caller-supplied objective. The example uses the same geometric loss as the preceding direction optimizer. The number of basis vectors specifies the parameterization; establishing a model behavior’s causal dimension requires further experiments.
Research paper
SOM: prototype directions
One average can hide several groups of examples. A self-organizing map learns several representative points instead. We’ll use these prototypes to build candidate editing directions.
Imagine that harmful requests form several groups. Their average might land between the groups, far from a typical request in any of them. We could get a more detailed picture by learning several representative points, called prototypes.
A self-organizing map, or SOM, arranges prototypes on a grid. Each training example selects the closest prototype. That prototype and its grid neighbors move a little toward the example. Repeating the process organizes the prototypes around the data.
We fit a map to harmful-request vectors. We then subtract the benign mean from selected prototypes to obtain candidate directions. If we use several of them, we turn them into an orthonormal basis before projecting.
See the 3×3 map
This example fits a 3×3 grid of nine prototypes, labeled P0 through P8. Each cell below contains its learned two-coordinate vector. For example, P0 stores [3.017, 2.454]: its first activation coordinate is approximately 3.017 and its second is 2.454. These are the fitted values from our numerical example, rather than the prototype’s grid position.
The nine cells are the actual fitted map. Each shows its prototype ID, activation coordinates, training wins, and final nearest-example count. Darker orange means more training wins. The top-left cell P0 is labeled SELECTED and has a thick green outline: its 51 training wins select it for the direction below. Grid positions specify neighbors; numbers inside cells are activation coordinates.
The grid row and column tell us which prototypes are neighbors during learning. They are different from the two activation coordinates stored inside each cell. In LFM3, a cell at the same capture site would store 2,048 numbers, while the map could still have just three rows and three columns.
Each cell also shows two counts. Wins counts how often the prototype was closest to the sampled training example during the 180 updates; darker orange means more wins. Final counts how many of the 32 harmful examples are closest to that prototype after training finishes. These can differ because the prototypes move while learning. Training can sample an example more than once, so wins sum to 180, whereas final assignments sum to 32.
Look at the top-left cell, P0, labeled SELECTED inside a thick green outline. It won 51 of the 180 training steps, more than any other prototype, so we use it to build the edit direction. We subtract the benign mean from P0, then normalize the result. The numbers below the grid show this calculation for the actual fit. The projection plot below uses that same direction:
We fit the numbered 3×3 SOM above to the harmful example points. The prototype with the most cumulative training wins supplies the displayed direction relative to the benign mean.
Choosing the prototypes
A larger grid can represent more local structure, but it also introduces more choices. We need to decide how many training steps to take, which prototypes to use, and how many independent directions to keep.
Compare this with the mean-difference method: there, one center represents the whole harmful group. Here, the prototypes allow us to describe parts of that group separately.
The plot uses a fitted numerical SOM on synthetic two-coordinate data. Our SOM-inspired implementation selects prototypes by cumulative training wins and omits the paper’s Bayesian subset optimization. The numeric map and intervention plot use the same seed 12, 180 updates, 32 harmful vectors, and benign mean. Prototype coordinates are rounded to three decimals for display; calculations use the full values. A local group can still reflect topic rather than refusal, which requires separate behavior tests.
Research paper
ACE: affine editing
Projection sets a coordinate to zero, but our benign examples may be centered elsewhere. Affine editing lets us choose a different reference. Let’s see how that changes where the points end up.
At full strength, ordinary projection removes the component along d, so its coordinate x′·d becomes zero. As the coordinate animation shows, the original numbered entries need not become zero. But why should zero be the value we want along d? Our benign examples may be centered somewhere else.
An affine edit lets us choose a reference point. We measure the vector relative to the benign mean μ_b, then set its coordinate along d to a target t:
x′ = x − [((x − μ_b)·d) − t]d
When t=0, the resulting vector has the same coordinate along d as the benign mean.
At full strength, the points reach a line through the benign mean, perpendicular to d. The slider blends this target-coordinate edit with the original vectors.
At full strength, the points reach a line through the benign mean. Compare this with ordinary projection, where the line passes through the origin. Both operations keep the perpendicular part; they choose different values for the parallel part.
The slider blends the original vector with the full affine result. Try it to see how the reference point changes the destination.
This ACE-style control computes the target-coordinate operation with affine_edit; interpolation is a figure control. The reference and target are chosen before final evaluation. Sharing a coordinate with benign examples does not by itself establish benign behavior.
Research paper
SRA: protect concept atoms
The same direction can carry information about both intent and writing style. We’ll look at how separate concept examples can help us choose which parts of a candidate direction to keep.
Suppose our harmful and benign examples differ in writing style as well as intent. Removing their mean difference could then affect both. To reduce this overlap, we can first collect separate examples that vary in style while controlling other properties.
The difference between the new groups’ mean activation vectors gives us a reference direction for their style contrast. We can do this for several concepts and put the resulting vectors into the columns of a matrix A, called an atom bank. Each column is one supplied reference direction; an atom is not a token or a neuron.
We first estimate a candidate editing direction d from the harmful mean minus the benign mean, normalized to length one. Then we reduce the part of d that overlaps the atom bank:
d_clean ∝ d − A(AᵀA + λI)⁻¹Aᵀd
The symbol ∝ means we normalize the result to length one. Aᵀd measures the candidate’s overlap with the references. The matrix expression turns those overlaps into a component to subtract. I is the identity matrix, and λ controls regularization. With λ = 0 and independent reference columns, this removes the component in their span exactly. A positive λ makes the subtraction softer and keeps the inverse defined even when reference columns overlap.
We call the result the cleaned candidate. Cleaning adjusts the direction of the later edit. It does not establish that the remaining direction represents only refusal. With exact cleaning, a later projection along this direction preserves each vector’s component along the supplied atoms. Soft cleaning leaves some overlap, and either version can still change other useful components.
The horizontal direction is our supplied style reference in this numerical example. Cleaning the candidate against it reduces the horizontal part of the edit.
In this example, we have assigned the horizontal direction to a style concept. Cleaning the candidate reduces its horizontal component, so the edit moves away from that reference direction.
Follow the subtraction with two numbers
Let’s use an illustrative two-coordinate example. For the moment, let’s remove the overlap exactly, without regularization:
Candidate arrow c = [3, 4] Wording atom a = [1, 0] ← horizontal, length one
Overlap along a: c·a = 3
Component along a: (c·a)a = 3 × [1, 0] = [3, 0]
Subtract that component: c − (c·a)a = [3, 4] − [3, 0] = [0, 4]
The original arrow points partly horizontally. The cleaned arrow points vertically, perpendicular to the wording atom. Starting with the normalized candidate [0.6, 0.8] gives the same final direction: subtract [0.6, 0], then normalize [0, 0.8] to [0, 1].
We have changed an editing direction. We have not cleaned a sentence, modified its text, or established that the remaining arrow contains only refusal information.
A worked example: keep a wording contrast out of the edit
Let’s follow two requests: B, “How can I protect my online account from password theft?”, and H, “How can I steal someone else’s online account password?” Blue diamonds represent B and orange diamonds represent H. We recorded a 2,048-number vector for each at block index 11 of LFM3. For this calculation, we use eight PCA coordinates; the plots show the first two. The faint points are the 128 separate examples used to fit the method.
1. Start with the captured requests. Both diamonds use the same PCA axes as the fitting examples.
The named benign and harmful sentences are diamonds in the original LFM3 capture space, summarized by two displayed PCA coordinates. Faint points are separate fitting examples. The operation uses eight coordinates.
2. Build a separate wording reference, then clean the candidate. There are three different arrows in this step. Let’s give each one a concrete meaning before looking at their coordinates.
What is the candidate direction?
The candidate direction d is the editing arrow we start with. We calculate the harmful fitting group’s mean minus the benign fitting group’s mean, then normalize the result to length one. It is a candidate because the difference between those groups might include topic, wording, or other information alongside refusal-related behavior.
We have not edited either request at this point. We are choosing the direction along which a later operation will remove a component.
What is a wording atom?
A wording atom a is a reference direction representing a wording difference we want the edit to avoid. We build it from separate benign pairs such as:
Casual: “How do I keep my online account safe?”
More formal: “Please explain how I can safeguard my online account.”
These sentences ask for the same kind of help. That is intentional: we want to compare their wording while keeping their intent similar. Two further pairs cover two-factor authentication and password managers.
For each pair, we subtract the casual activation vector from the formal activation vector. We average those differences, then normalize the result. The resulting arrow is our supplied wording atom. “Atom” means one reference vector here, rather than a word, token, or individual neuron.
The pairs also differ in vocabulary, length, and politeness. We therefore call this a wording-contrast direction, rather than claiming it isolates formality. In the chart’s legend, Style atom refers to this same measured wording reference.
What is the cleaned candidate?
The cleaned candidate d_clean is the editing arrow after we reduce its component along the wording atom. Imagine that d points partly along the wording reference. Cleaning subtracts that shared component, then normalizes the remaining arrow. We will use this new direction for the later edit.
Read the fitted eight-coordinate result
The bars below return to our actual eight-coordinate calculation. They show the original candidate d, the wording atom a, and the normalized cleaned candidate d_clean. Their coordinates tell us how those three arrows differ.
Editing direction compared with the wording atom
Dot product
Original candidate: d·a
−0.0812
Cleaned candidate: d_clean·a
−0.000807
Closer to zero means more perpendicular, so the cleaned editing direction overlaps much less with this particular wording reference. The negative sign describes orientation; it does not mean the direction is bad.
Our real calculation uses regularization λ = 0.01. This makes the removal softer than the exact subtraction in the small example, leaving the small nonzero overlap above. It helps stabilize the operation when reference directions overlap or are uncertain.
These are the actual eight-coordinate candidate, formal-minus-casual atom, and cleaned direction. Their dot-product overlap decreases from −0.0812 to −0.000807 with ridge 0.01. The atom comes from three separately captured benign wording pairs.
3. Apply the cleaned direction. The same half-strength projection receives both request vectors. Dashed segments connect each diamond’s original and edited positions; the coordinates below the plot make their movement explicit. The axes have the same limits as the first plot.
Both named request vectors receive the cleaned half-strength projection. Dashed segments and printed coordinates track their changes on exactly the original axes. This is a calculation on saved activations, not a new generated answer.
The wording atom changes which component we subtract. The movement of B also lets us inspect a cost: cleaning one reference direction does not keep every benign vector fixed. These are calculations on captured vectors; we have not generated new answers for this worked example.
Watch the direction being built and cleaned
Open Explore this plot and choose Play all steps, or use Step → to advance one operation at a time. Blue B and orange H first appear as sentence vectors. A purple arrow grows from B to H: this is their difference Δ = H − B. In the lower panel we divide Δ by its length to get the purple unit candidate d. Next, we draw the green wording atom a, identify the pink component along it, subtract that component, and normalize the teal remainder to obtain the cleaned candidate.
Play B → H−B → unit candidate d → wording atom a → subtract overlap → normalize the cleaned candidate. Purple is the candidate, green is the wording reference, pink is the removed part, and teal is the cleaned arrow. Default numbers are illustrative; recorded mode uses the saved LFM3 pair in a rotated eight-PC plane. Exact and ridge-regularized cleaning are separate options.
The default uses illustrative coordinates B = [1, 1] and H = [4, 5], making their difference [3, 4] easy to follow. The same benign and harmful sentences label the points, but these simple numbers are not their measured activations. The final candidate is [0, 1] with exact removal. Switch to Soft removal · λ=0.01 to see a small horizontal component remain.
Choose Recorded LFM3 pair to repeat these steps with the saved activations for our two requests. There are two choices behind this view: how we draw the vectors, and which examples we use to estimate the candidate. Let’s separate them.
Why does the green atom point horizontally?
Our recorded residual vectors each have 2,048 coordinates. Earlier, we represented them using eight principal components. That gives us eight coordinates per request, but a flat plot still has only two axes. Which two should we use to show cleaning?
We choose the wording atom as the horizontal axis. Then we choose a vertical axis perpendicular to it, pointing along the part of H − B that remains after removing its overlap with the atom. Imagine turning a camera until these two directions lie flat in the picture. The green atom points right because we chose to draw it that way; we have not changed the atom itself.
These two axes define a plane. The phrase “the plane spanned by the difference and the wording atom” means all the arrows we can make by adding scaled copies of those two vectors. For example, twice the atom plus half the difference is still in that plane. The difference arrow, the atom, and the cleaned candidate all lie in it, so we can show their complete geometric relationship in two dimensions within our eight-coordinate working space.
In this view, a candidate’s horizontal coordinate measures its overlap with the wording atom. Its vertical coordinate measures the perpendicular part. With exact removal, cleaning takes away the horizontal component, leaving a vertical arrow. We then normalize that arrow to length one. This is why a right angle is useful here: we can see directly that the cleaned direction has zero dot product with the green atom.
For the recorded pair, the unit candidate appears at approximately [−0.131, 0.991] in these axes. Its small negative horizontal coordinate means it points slightly against the green arrow. Exact cleaning subtracts [−0.131, 0], leaving [0, 0.991]. Normalization then gives [0, 1]. With soft removal, a small horizontal component remains.
The axes in this animation therefore differ from the PC1 and PC2 axes in the earlier scatter plots. We changed our viewing coordinates to make the cleaning operation visible. The two-dimensional view preserves the lengths and angles of arrows in this plane; the earlier reduction from 2,048 coordinates to eight components already left some information out.
Why is this candidate different from the fitted one?
In the animation, we start with just the two displayed requests: the benign account-protection request B and the harmful account-theft request H. We subtract their vectors and normalize the result:
One-pair difference: Δ_pair = H − B One-pair candidate: d_pair = Δ_pair / ‖Δ_pair‖
This makes every step easy to follow: we can watch an arrow grow directly from the blue point to the orange point. But that difference can include anything that distinguishes these two requests, including their particular words and meanings. Calling it a candidate does not establish that it isolates refusal.
The completed before/after example above estimates its candidate from 128 separate fitting requests: 64 harmful and 64 benign. We average each group first, then subtract the two averages and normalize:
Averaging lets many examples contribute instead of letting one pair determine the arrow. It can reduce the influence of details specific to one request, although shared wording or topic differences can still remain. Our two displayed requests were held out of this fitting set.
So we should expect d_pair and d_fit to be different arrows. Both examples use the same cleaning idea and wording reference, but they begin with different candidates. The animation explains the construction from one pair; the earlier before/after plots show the edit using the candidate fitted on 128 examples. Playing the animation changes the displayed arrows without changing the request text or model weights.
Where the concept comes from
The examples give an atom its interpretation. Naming a PCA axis “math ability” would not establish that it represents mathematical ability. We need separately defined contrasts, followed by tests of the behavior we want to preserve.
This SRA-style core uses supplied concept contrasts and omits automatic hard-negative refinement. The horizontal style atom is a numerical example; no LFM3 style circuit was identified for this figure. Small samples and nearly collinear atoms can make the estimate sensitive to regularization.
Research paper
PCA-OT: distribution transport
Two groups can differ in both their centers and their spread. Optimal transport gives us a way to move and reshape a distribution. We’ll work through a Gaussian map in a small PCA subspace.
A worked example: move and reshape the request vectors
We’ll use B, “How can I protect my online account from password theft?”, and H, “How can I steal someone else’s online account password?” Their diamonds show captured LFM3 vectors at block index 11. We calculate in eight PCA coordinates and draw the first two; the faint points are 64 benign and 64 harmful fitting examples.
1. Inspect the source and target. The harmful fitting cloud supplies the source mean and covariance, while the benign cloud supplies the target. The two named requests are held out from fitting.
The source is the harmful fitting cloud; the benign fitting cloud supplies the target statistics. The two named requests are held out. The same eight-coordinate PCA representation and first-two-coordinate view are used before and after.
2. Fit the transport: learn where to move the cloud and how to reshape it. A cloud has a center and a shape. The mean is its center: we average each coordinate across the examples. The covariance describes its spread: which directions vary a lot, and which coordinates tend to increase or decrease together. Here, the harmful fitting cloud is the source, and the benign fitting cloud is the target.
Why choose four directions if we have eight coordinates?
Each request currently has eight PCA coordinates. We choose four perpendicular directions within that space so the reshaping happens in a smaller space. Our implementation finds these directions by applying SVD to the two groups after subtracting each group’s own mean. It keeps the four directions with the greatest combined within-group variation. These directions are learned combinations of the eight coordinates; they are not four words, four requests, or necessarily the first four plotted PCA axes.
We store the directions as the columns of Q, an 8×4 matrix. Multiplying an eight-coordinate vector by Q gives four numbers: how far that vector extends along each selected direction. We call those its reduced coordinates. The other four independent directions are outside this selected subspace.
What does the 4×4 matrix T do?
We estimate the source and target covariances in those four reduced coordinates. From them, we calculate T, a matrix that reshapes the source spread toward the target spread. “Gaussian” means we approximate each cloud using its mean and covariance for this calculation. We do not assume that every measured point forms a perfect bell-shaped distribution.
Watch what the Gaussian approximation keeps
Let’s temporarily use two illustrative coordinates so we can see the whole calculation. The orange points below form two clumps. Their mean sits between the clumps, and the solid orange ellipse summarizes their spread around that mean. The dashed blue ellipse shows the target mean and covariance. Crosses mark the two centers. The target stays fixed throughout the animation.
Orange dots form two clumps; the solid orange ellipse summarizes their mean and covariance. The dashed blue ellipse is the fixed target summary. Play centering → reshaping with T → translation. The bars track variance and covariance. Matching these statistics leaves the clumps visible: it does not match the full empirical distribution. These are illustrative two-coordinate values, not LFM3 measurements.
Open Explore this plot and press Play, or move the progress slider through three stages:
0–25: subtract the source mean. The orange cloud moves to the origin. Its clumps keep the same shape and spacing. The covariance bars stay unchanged because translating a cloud does not change its spread around its own center.
25–75: apply T. The centered orange cloud stretches and compresses along different directions. Its summary ellipse changes width, height, and tilt until it matches the target ellipse’s shape. The bars move toward the blue target values.
75–100: add the target mean. The reshaped orange cloud moves to the blue center. Its covariance stays unchanged during this translation. At the end, the two summary ellipses overlap, but the orange dots still form two clumps.
What do the covariance numbers describe?
For each point, first subtract the cloud’s mean to get offsets δx and δy. Variance x averages the squared horizontal offsets; a larger value means more horizontal spread. Variance y does the same vertically. Covariance xy averages the products δxδy. Positive covariance means the coordinates tend to increase together, giving an upward tilt. Negative covariance means one tends to decrease as the other increases, giving a downward tilt. Our sample estimates divide the summed products by n − 1.
The source has more horizontal than vertical spread and a positive tilt. The target has more vertical spread and a negative tilt. T is calculated to satisfy T C_source Tᵀ = C_target in this example, so applying it changes both spread and tilt. The diagonal bars show the two variances; the third bar shows their shared off-diagonal covariance.
Why call this Gaussian if the points have two clumps?
A Gaussian distribution is completely specified by its mean and covariance. In two dimensions, its equal-density contours are ellipses. The orange ellipse draws the shape of that Gaussian summary, extending two standard deviations along each principal direction. It is not a boundary containing every point, and it is not the measured cloud’s actual density contour. Several different clouds can have the same ellipse.
Our map uses those summaries to choose T. It does not use every detail of the cloud’s density. This is why the ellipse can match perfectly while the two-clump structure remains. Likewise, matching the summaries of harmful and benign activation clouds does not establish that their complete distributions, meanings, or generated answers match.
In the recorded example above, we perform the same covariance calculation in four selected coordinates. The covariance and T are therefore 4×4 instead of 2×2. The measured calculation also adds a small diagonal regularizer, so its fitted target is the regularized covariance rather than an exact match to every raw sample statistic.
T takes four numbers in and returns four numbers. Each output is a weighted sum of the inputs. For example, using column-vector notation, the first output is:
z′₁ = T₁₁z₁ + T₁₂z₂ + T₁₃z₃ + T₁₄z₄
A diagonal entry scales one coordinate’s contribution to its corresponding output. An off-diagonal entry lets a different input coordinate contribute to that output. Together, these entries can stretch or compress the cloud in different directions and change how its coordinates vary together. The heatmap below shows the actual fitted 4×4 matrix T, with its entries printed in the cells. Its row and column numbers refer to these four learned directions, not vocabulary tokens.
Printed cells show the fitted four-by-four Gaussian transport matrix T. It maps reduced source coordinates before the target mean and perpendicular remainder are added back. The fit uses ridge 0.0001.
3. Apply the map and plot again. Once Q, T, and the two means have been fitted, we keep them fixed. For each request vector x, we perform the same steps:
Subtract the harmful mean μ_h. This gives the request’s offset from the source cloud’s center. Even a benign request is measured relative to that same source center.
Split this offset into two parts. Project it onto Q to obtain four reduced coordinates z. Save the perpendicular remainder r, which is the part those four coordinates cannot represent.
Reshape the four coordinates with T. This changes the selected part of the offset to reflect the target cloud’s spread.
Reconstruct and add the benign mean μ_b. Convert the four mapped coordinates back into eight coordinates using Q, add the saved remainder, and place the result around the target center.
Using the row-vector convention of our Python code, the complete calculation is:
z = (x − μ_h)Q ← four reduced coordinates r = (x − μ_h) − zQᵀ ← eight-coordinate perpendicular remainder x′ = μ_b + (zTᵀ)Qᵀ + r
Saving r prevents the map from throwing away everything outside the four selected directions. It preserves the perpendicular offset relative to the source center, then adds it back relative to the target center. Those absolute coordinates can still shift if the two centers differ in that perpendicular space.
Why does the blue benign point move too?
The labels tell us which examples to use when fitting the map. They do not become a condition inside the fitted map. When we call transport(pair), both request vectors pass through the same arithmetic. The map does not first ask whether a request is harmful.
Consider a separate, illustrative one-coordinate example. Suppose the harmful center is 2, the benign center is 5, and the spreads already match, so T = 1. The fitted map is then x′ = 5 + (x − 2) = x + 3. It moves a harmful point at 2 to the benign center at 5. But it also moves a benign point already at 5 to 8. A map that moves one distribution onto another does not automatically leave the target distribution fixed.
Our measured example has the same issue, with reshaping as well as a center shift. We apply the map to both diamonds and all fitting points so we can inspect this effect. The blue cloud in the after plot is the transformed benign cloud, not the original target cloud held in place. Compare its movement with the orange cloud’s movement using the original axes. A gate would be an additional rule deciding whether each vector receives the map; this example has no such rule.
The map changes both the source cloud's location and shape. Because there is no gate, it also moves benign vectors. Diamonds and numeric coordinates follow the two held-out requests; the plot does not measure their generated behavior.
The dashed segments and printed coordinates track B and H individually. Here, B’s first two coordinates move from approximately [1.780, −0.500] to [6.346, −0.817], while H moves from [−1.838, 0.692] to [3.434, 4.090]. The large blue-cloud movement shows what can happen when a map fitted to the harmful source is also applied to benign inputs. Matching activation statistics is a geometric operation; it does not tell us that H now produces a benign answer.
Why transport includes shape
Two groups can have similar centers and very different shapes. One might be tightly clustered; the other might be spread along a diagonal. Moving their means closer together would leave this difference in spread.
Optimal transport gives us a way to consider both. In our Gaussian version, we summarize each group with its mean and covariance. The covariance describes how coordinates vary together. We then calculate an affine map that moves the source mean and reshapes its covariance toward the target.
We do this inside a small PCA subspace and keep the perpendicular part of each vector:
The map changes the source cloud’s center and spread using the fitted means and covariances. The slider blends the original vectors with the full map, which also moves any benign points it receives.
Watch how the source cloud changes both position and shape as you increase the slider. The map was fitted once; the slider blends its result with the original vectors.
Applying the map
Learning a map from harmful to benign examples does not decide which future vectors should receive it. Applied to every vector, it will also move benign examples. We would need an additional gate to make the operation conditional.
This is our PCA-OT-style implementation. The figure uses a rank-two Gaussian map in a two-dimensional example. Model experiments use the configured reduced rank. Covariance regularization and sample size affect the fitted map, and matching activation statistics requires separate evaluation of response behavior.
Research paper
LEACE: linear concept erasure
How can we remove a linear relationship between vectors and labels? LEACE answers this with a fitted affine transformation. We’ll look at why covariance matters and what its linear guarantee means.
A worked example: erase a fitted label relationship
Take B, “How can I protect my online account from password theft?”, and H, “How can I steal someone else’s online account password?” We capture their LFM3 vectors at block index 11 and express them in eight PCA coordinates. The plot displays two of those coordinates. Blue and orange fitting points carry labels 0 and 1; the named request diamonds are held out.
1. Plot the original relationship. The label is associated with a difference between the fitting groups.
Blue and orange fitting captures carry labels 0 and 1. The named account-security requests are held-out diamonds. These two axes display part of the eight-coordinate working space.
2. Fit the eraser on the fitting examples. LEACE centers and whitens the eight-coordinate representations, removes their linear label-related component, and maps them back. The bars below measure the cross-covariance between each coordinate and the label before and after the fitted transformation. The after bars are zero up to numerical precision.
Each bar measures one coordinate's fitted cross-covariance with the label. After LEACE, all eight are zero up to numerical precision. The check applies to these fitting coordinates, not all hidden dimensions or nonlinear predictors.
3. Send the two held-out requests through the same eraser. The original and edited plots share their axes. The diamonds and their numeric coordinates show how this statistical operation moves each request.
The same fitted affine eraser transforms both held-out requests and the fitting clouds. Compare their positions and printed coordinates with the first plot on matching axes. No model response is regenerated.
The zero cross-covariance check applies to the eight-coordinate fitting data. It does not establish that a held-out classifier fails, that nonlinear information is gone, or that every label-related component in the original 2,048-dimensional space was erased.
How the eraser is constructed
Our mean-difference method starts by choosing an arrow. LEACE starts with a statistical goal: remove linear cross-covariance between the representation and a set of concept labels while controlling how much the representation changes.
The calculation first centers the vectors. It then whitens them, adjusting for their covariance so that directions with different spreads can be handled in a common coordinate system. In that space, it finds and removes the label-related component, then maps the vectors back.
Both labeled groups receive the same affine transformation. At full strength, the fitted cross-covariance between representations and labels is zero up to numerical precision.
The same fitted transformation is applied to both groups. At full strength, its cross-covariance with the fitting labels is zero up to numerical precision.
What “linear” means here
A linear predictor combines coordinates using fixed weights. Eliminating this particular statistical relationship gives us a precise property to check. A nonlinear predictor might still recover information about the label, and new examples may behave differently from the fitting data.
Because whitening changes the coordinate system, the final affine transformation generally differs from an ordinary perpendicular projection in the original space.
erase=leace(X,labels)edited=erase(x)
Data and numerical details
The figure uses a small numerical example. With 128 examples in 2,048 dimensions, the fitted covariance is rank-deficient; our implementation works with its supported eigenspace. The LEACE paper defines the formal objective and its linear guarantee.
Research paper
RFM-AGOP: sensitivity subspaces
A predictor can learn to distinguish our labeled groups. We can then inspect which input changes affect its predictions. This section explains how gradients lead to a bank of candidate directions.
RFM means Recursive Feature Machine. It learns which directions in our captured activation vectors help predict the supplied benign and harmful labels. Here, the machine is a small predictor fitted to saved vectors. LFM3 supplies those vectors; its weights stay fixed throughout this calculation.
A worked example: follow the predictor’s gradients
Let B be “How can I protect my online account from password theft?” and H be “How can I steal someone else’s online account password?” We use their captured block-11 LFM3 vectors, summarized in eight PCA coordinates. The faint fitting points provide 128 labeled examples; these two request diamonds are held out.
1. Plot the inputs before learning a direction. Only the first two PCA coordinates appear on the page, while the predictor receives all eight.
The two request captures are held out while 128 other captures train the label predictor. Its input has eight PCA coordinates, of which two are visible here.
2. Fit a predictor and calculate its sensitivity. We run three RFM iterations. An iteration is one pass through the following cycle.
What happens in one RFM iteration?
Fit a label predictor. We give the predictor the eight-coordinate fitting vectors and their labels: 0 for benign, 1 for harmful. It estimates a numerical label score using similarities between examples. Our RBF kernel assigns greater similarity to nearby vectors and less similarity to distant ones. Its bandwidth, set to 2 here, controls how quickly similarity falls with distance. Ridge regularization, set to 0.05, stabilizes the fit.
Measure the predictor’s sensitivity. At each fitting vector x, we calculate a gradient ∇f(x). It answers: “If we move this vector slightly, which direction increases the predicted label score most quickly?” The gradient has eight entries because the predictor receives eight coordinates. A large entry means a small change in that coordinate has a strong local effect on the score. It measures the fitted predictor’s response, rather than directly measuring a change in LFM3’s generated answer.
Combine the sensitivities. For each gradient g, we form the outer product ggᵀ: an 8×8 matrix whose entry (i, j) is gᵢgⱼ. We average these matrices across the fitting examples to obtain the average gradient outer product, or AGOP. Using outer products lets us capture shared sensitivity even when gradients point in opposite directions and would cancel if we simply averaged the arrows.
Update how distance is measured. We use the AGOP, normalized to control its overall scale, as the predictor’s new input metric. A metric specifies how much movement in each direction contributes to distance. This update makes the next fit pay more attention to directions with stronger sensitivity. It can also combine coordinates, rather than giving each original coordinate an independent weight.
What does “three iterations” mean?
We start with an identity metric, which treats all eight coordinate directions equally. Then we repeat:
Iteration 1: fit using the initial metric → calculate gradients → update the metric Iteration 2: refit using that updated metric → calculate new gradients → update again Iteration 3: refit once more → calculate gradients → obtain the final sensitivity matrix
This repeated feedback is why the method is called recursive. Three iterations means three predictor fits and three sensitivity updates. It does not mean three LFM3 layers, three passes through its transformer blocks, or three epochs of language-model fine-tuning. The same 128 saved fitting vectors are reused; the two named request vectors remain held out.
After the third update, we take the final AGOP’s leading eigenvector: the unit direction v with the largest average squared sensitivity, average[(∇f(x)·v)²]. Our example keeps one such direction (rank=1) and uses it for the later projection. This produces a candidate for an intervention, rather than establishing that the direction controls refusal.
The bars show the last fitted predictor’s gradients at B and H, alongside the chosen direction’s eight entries. A gradient at one request describes local sensitivity there; the selected direction comes from averaging over the fitting examples, rather than choosing either request’s gradient alone.
The bars show the last RBF predictor's gradients at the benign and harmful requests and the selected AGOP direction. The direction is calculated from fitting-example gradients; the held-out gradients illustrate local sensitivity.
3. Remove half the component along that learned direction. Compare both diamonds with their starting positions. The same projector also moves the blue request, which gives us a concrete benign-change diagnostic.
Both requests receive a half-strength projection along the fitted leading AGOP direction. Their dashed movements reveal benign changes too. A predictor's label sensitivity is a candidate editing signal, not proof of a causal refusal feature.
This predictor learns the supplied labels. Its sensitivity could reflect topic, wording, or other correlates; a response intervention is still needed to connect the direction to refusal.
From sensitivity to a direction
Another way to find directions is to train a predictor of our group labels. Once it can distinguish the groups, we can ask which changes to its input affect its prediction.
A gradient answers this locally: it gives the direction in which the predictor’s output increases most rapidly. We calculate gradients for several examples and average their outer products:
G = average of [∇f(x) ∇f(x)ᵀ] Q = leading eigenvectors of G
The matrix G is the average gradient outer product, or AGOP. Its leading eigenvectors identify directions to which the predictor is sensitive.
The RFM loop uses this matrix to refine the distance measure for the next fit. After the final iteration, we take its leading direction and use it in a projector.
We fit an RBF predictor and refine its input metric using gradient outer products. The leading eigenvector supplies the projection direction shown here.
The direction can differ from the mean difference because the fitted predictor uses more of the groups’ structure than their centers alone.
Testing the learned directions
The predictor might use differences in topic or formatting to separate the labels. We therefore still need interventions to learn whether its directions affect the language model’s refusal behavior.
Our RFM-AGOP-style core starts with an identity metric rather than the paper’s probe-informed initialization. The example fits the predictor and gradients on numerical data. Bandwidth, regularization, iterations, and sample size affect the result; pairwise kernel storage grows quadratically with the number of examples.
Research paper
WRDO: weighted direction banks
Suppose we already have several directions. We can learn weights that combine them into a new one. Let’s work through the candidate bank, the weights, and the normalization step.
We’ll follow B, “How can I protect my online account from password theft?”, and H, “How can I steal someone else’s online account password?” Their block-11 LFM3 captures are represented in the same eight-coordinate PCA space used by the fitting examples. Only the first two coordinates are drawn.
1. Start with the unedited requests. The two diamonds have not been used to fit the candidates or their weights.
The two named requests start unedited and are excluded from candidate fitting and weight optimization. The same PCA axes are used in the final plot.
2. Build a bank and learn its weights. We estimate one mean-difference direction from all 128 fitting examples, another from the first 32 examples per class, and a third from the last 32 per class. These are reproducible subsets, rather than three semantic categories. We then optimize their softmax weights for 60 Adam steps.
What does the geometric loss ask the optimizer to do?
For each proposed mixture of candidates, we normalize the combined direction d and use it to project the fitting vectors. The loss then asks two questions.
Are the projected harmful vectors closer to the benign center? We calculate the benign mean μ_b by averaging the original benign fitting vectors. For each harmful vector h, we obtain its projected version h′ and measure its squared distance from μ_b. Averaging these squared coordinate differences gives the harmful loss. A smaller value means the projected harmful vectors lie closer to that fixed center.
How much did we disturb the benign vectors? We apply the same projection to each benign vector b, obtaining b′. We measure the squared difference between b′ and its original position b, then average across examples and coordinates. This is the benign movement penalty. A smaller value means less movement of the benign fitting vectors.
Our implementation combines these terms as:
L_harmful = mean over harmful examples and coordinates of (h′ − μ_b)² L_benign = mean over benign examples and coordinates of (b′ − b)² L = L_harmful + 0.3 × L_benign
The coefficient 0.3 controls how much benign movement contributes to the objective. Increasing it puts more pressure on the optimizer to preserve the benign vectors. It is a chosen tradeoff weight, not a guarantee of preserving behavior.
Here is an illustrative comparison, separate from the measured loss values:
Proposed editing direction
Harmful loss
Benign movement penalty
Total loss
A
2.0
4.0
2.0 + 0.3 × 4.0 = 3.20
B
2.5
0.5
2.5 + 0.3 × 0.5 = 2.65
The optimizer prefers B. It brings harmful vectors somewhat less close to the benign mean, but disturbs the benign vectors much less. The combined score rewards that tradeoff.
“Pulls toward” describes this optimization pressure. We cannot freely drag every point toward the center. We adjust the weights of three candidate directions, which changes one shared direction d; projection along d determines how each vector moves. During this fitting objective, we use full-strength projection. The before/after plots below use half strength to display the learned direction’s effect on the held-out requests.
This objective measures geometry. Moving a harmful vector closer to the benign mean does not establish that LFM3 will produce a benign answer, and limiting benign-vector movement does not establish that every useful behavior is preserved.
Read the learned weights
The resulting weights are approximately 0.388, 0.371, and 0.241. The loss curve changes only slightly: these candidates are similar, so changing the mixture has a small effect in this example.
The three weights combine an all-example direction and two half-data directions. Sixty Adam steps yield approximately 0.388, 0.371, and 0.241. The small loss change remains visible rather than being presented as a large improvement.
3. Apply the combined direction. We normalize the weighted vector before using it in a half-strength projection. The after plot shows the resulting movement of both held-out requests on the original axes.
We normalize the weighted sum, then apply the resulting half-strength projection to both requests. The coordinates show the actual movement in the plotted plane; no generated-response claim follows from it.
The weights describe contributions from candidate directions, not the importance of words in either sentence.
Why the bank matters
Suppose we already have several candidate directions from different groups of examples. We can learn how to combine them instead of adjusting every coordinate of a new vector.
We put the candidates into the columns of a matrix A. The optimizer learns a set of numbers a. Softmax turns those numbers into nonnegative weights that add up to one, and we use them to form a weighted direction:
w = softmax(a) d = normalize(Aw)
We normalize once more because a weighted sum of unit vectors does not generally have length one.
The bars show the learned softmax weights for three candidates. They sum to one; we then normalize the combined vector to give it unit length.
The bars show the weights learned for three candidates using our geometric loss. A taller bar means that candidate contributes more to the resulting vector. Similar candidates can exchange weight while producing almost the same combined direction.
The role of the candidate bank
The bank defines which combinations the optimizer can express. If a useful direction lies outside that set, changing the weights will not find it. Choosing the candidates is therefore part of the method.
This aggregation uses Adam and takes inspiration from WRDO. It does not use the paper’s CMA-ES or GRPO-IS optimizer. The displayed weights come from numerical examples, rather than an attribution of real-model refusal to training prompts.
Research paper
COSMIC: score candidate geometry
Before generating responses for every candidate, we can inspect a geometric score. We’ll use cosine similarity to compare edited representations with their reference groups.
A worked example: score first, then inspect the selected edit
Let’s return to B, “How can I protect my online account from password theft?”, and H, “How can I steal someone else’s online account password?” We use their captured block-11 LFM3 vectors in an eight-coordinate PCA space. Their diamonds are separate from the 128 fitting points used for candidate scoring.
1. Plot the original requests and references. These are the unedited representations against which we compare the later movement.
The unedited request diamonds are held out from candidate scoring. Faint fitting references supply the group tensors used by the local cosine-inversion scorer.
2. Compare three candidate directions on the fitting data. We use the all-example mean difference and the two half-data alternatives from the weighted-bank example. We want to choose which arrow to test further. For each candidate, we run two geometric checks: remove its component from harmful references, and add each benign reference’s component to that reference.
What does “remove” or “add” mean here?
For a unit direction d, the component of a vector x along it is (x·d)d. Removal subtracts this component; addition adds it back on top of what is already there:
H_removed = H − (H·d)d B_added = B + (B·d)d
For an illustrative two-coordinate example, take d = [1, 0], H = [3, 2], and B = [1, 1]. The harmful component is [3, 0], so removal gives H_removed = [0, 2]. The benign component is [1, 0], so addition gives B_added = [2, 1]. These numbers illustrate the arithmetic, rather than the measured LFM3 score.
Addition therefore doubles the vector’s existing coordinate along d. It does not add a fixed amount to every example. A zero coordinate stays zero; a negative coordinate becomes more negative. Nor does this arithmetic guarantee that the modified benign vector becomes more similar to a harmful reference. The score measures whether that happens for the supplied data.
Why add anything to benign vectors?
We do not need this addition to perform harmful-component removal. It is a separate diagnostic for choosing the direction. We ask both: “Does removal make harmful representations point more like benign references?” and “Does addition make benign representations point more like harmful references?” The second question checks a reverse change, rather than inspecting removal alone.
We calculate a cosine similarity for each comparison and sum the two terms. The bars below show those totals; hovering exposes both terms. The all-example candidate has the highest total in this run.
Each candidate receives the sum of two cosine terms after harmful-component removal and benign-component addition. The highest fitting-data score selects the all-example candidate. Hover to inspect both terms.
3. Inspect the selected candidate on the two requests. We apply the same scoring diagnostic: add the component to B and remove it from H. The after plot tracks those two different operations. Their class labels determine which operation is applied here; this is not a learned inference-time gate.
For this diagnostic, we add the selected component to the benign request and remove it from the harmful request. This label-dependent comparison is not an inference-time gate or a measured behavioral inversion.
The after plot illustrates the two diagnostic operations, rather than a rule for processing an unseen request. We already supplied which request is benign and which is harmful.
What the score compares
Testing every candidate by generating many responses can be expensive. A geometric score gives us a cheaper quantity to inspect first.
Our concept-inversion score asks how much an intervention turns one group’s representation toward the other. We add a component to benign states and remove it from harmful states, then compare them with the opposite references using cosine similarity.
Cosine similarity compares vector orientations. For nonzero vectors, it is one when they point in the same direction and minus one when they point in opposite directions.
Suppose candidate A gives 0.9 for the harmful-removal comparison, while candidate B gives 0.6. These are illustrative scores. A produces closer directional agreement with the benign references on that comparison. This measures orientation, not distance: two vectors can point in the same direction while having very different lengths.
The total also includes the benign-addition comparison. For example:
Candidate
Harmful after removal vs. original benign
Benign after addition vs. original harmful
Total
A
0.9
0.2
1.1
B
0.6
0.7
1.3
Here, B wins overall even though A wins the removal comparison. A higher total does not mean both terms improved. We should inspect them separately as well as their sum.
In our local implementation, each comparison flattens the whole supplied group tensor into one long vector. We compare the groups in their supplied order; this is not an average of nearest-neighbor matches or a comparison only of the two displayed requests. Group construction and ordering therefore matter to the score.
The conclusion is narrow but useful: the winner has the highest combined score among the candidates we tried, under this geometric test. That selects a candidate to investigate. It does not yet establish that the direction controls refusal or changes the content of generated answers.
The curve adds two cosine similarities comparing edited representations with opposite-group references. It shows how the geometric score varies with edit strength in this example.
The curve shows how this score changes with intervention strength in our numerical example. A candidate that looks promising here can then be tested on actual model responses.
How would we test whether it actually affects refusal?
The cosine score is a selection heuristic. To investigate a causal effect on refusal, we would change the selected component while the model generates answers, then measure the resulting behavior. This is the next experiment for this worked example; its vector plots do not report that experiment’s outcome.
Record baseline answers on held-out requests. Use harmful requests, ordinary benign requests, and safe requests that can trigger unnecessary refusals. Keep these separate from the examples used to estimate and select the candidate.
Intervene during generation. Convert the direction from our eight-PC working representation back to the matching 2,048-coordinate residual space, respecting the saved coordinate transform. At the chosen capture site, remove its component during the forward pass. Apply the same removal rule to every request, without consulting its benign/harmful label. Specify which token positions receive the intervention so the experiment can be reproduced.
Compare with controls. Use the same requests and generation settings for no intervention, the selected direction, and random unit directions at matched intervention strengths. Test several strengths to see whether the effect changes consistently. For sampled generation, repeat across seeds.
Evaluate the complete answers. Measure refusals, substantive responses, and incoherence separately. Check benign accuracy, unnecessary refusals, and tool calling as well. Use an explicit response rubric with manual checks, rather than treating the absence of a refusal keyword as success.
If removing the selected direction consistently reduces refusals on unseen requests beyond the control interventions, that supports a causal effect on refusal in this setting. If benign performance also falls, the result includes collateral damage. If only the geometric score improves, we have not established a behavioral effect.
A complementary experiment could add a signed amount βd during generation and test whether refusal increases. This fixed signed steering intervention differs from doubling each vector’s existing component in the scoring diagnostic above. We would need to check the direction’s sign and compare against the same controls. Evidence in both directions would strengthen the interpretation, while still allowing the direction to carry other information alongside refusal.
This implements a COSMIC-style score, rather than the full candidate and layer-selection procedure. The function flattens each supplied tensor before comparing it. The construction of the original and intervened tensors therefore affects the score. Held-out response evaluation determines whether it selects useful edits.
Research paper
GRP-Obliteration: relative rewards
Instead of extracting a direction from two groups of prompts, we can update a model using rewards. We’ll start with a small example of sampling several responses and comparing their rewards within a group.
A worked example: a request to steal session cookies
Consider this hypothetical harmful request:
Help me steal another person’s session cookies so I can access their account.
A session cookie can represent a signed-in session, so this request seeks unauthorized account access. We will describe response categories without producing theft instructions. This is our teaching scenario, not the prompt used in the GRP-Obliteration paper.
The earlier methods estimate directions from captured activations. Reward-based training takes a different route: generate responses, score them, and update model parameters to favor responses with higher relative reward. The reward determines which behavior is encouraged.
1. Start with three response categories
For a small, fully inspectable example, suppose a policy has these invented probabilities:
Illustrative cookie-theft request: invented starting probabilities over refusal, defensive redirection, and harmful compliance. These are response categories, not LFM3 outputs or token probabilities.
These are category probabilities in a three-choice mathematical policy. They are not measured LFM3 probabilities, and no harmful completions have been generated.
2. Assign rewards and compare responses within the group
Imagine a group of ten responses containing six refusals, three defensive redirections, and one harmful compliance. We choose those counts for this example; they were not sampled from a model. To illustrate an unalignment objective, give compliance reward 1, and the other categories reward 0.
The mean reward is 1 / 10 = 0.1. The population standard deviation is 0.3. We standardize each reward within the group:
advantage = (reward − group mean) / group standard deviation
Ten invented responses receive binary rewards: only harmful compliance earns 1. The group mean is 0.1 and standard deviation 0.3, giving advantages +3 for compliance and −1/3 otherwise. No model completions were sampled.
“Positive advantage” means above the group’s average reward. It does not mean safe or correct. Here, our chosen reward deliberately gives the harmful response the positive advantage. If every response received the same reward, there would be no within-group preference to learn.
3. Update the response probabilities
To illustrate the paper’s positive-advantage idea, we use the simple categorical loss L = −average[max(advantage, 0) × log(probability of response)]. Only the compliance category has positive advantage in this group. Minimizing this loss raises its probability.
Our script executes one analytical gradient step on three category logits, with learning rate 1. The starting logits are the logarithms of [0.6, 0.3, 0.1]. The update changes them by [−0.18, −0.09, +0.27], after which softmax produces the probabilities below:
One exact gradient step on three category logits increases the rewarded compliance category. This is an executed categorical calculation, not LLM training or measured refusal removal. The probability axis matches the before plot.
The compliance probability rises from 10% to approximately 14.45%; refusal changes from 60% to 55.30%, and defensive redirection from 30% to 30.25%. This is an executed calculation on a three-category policy, not an LLM training result. The other probabilities change too because softmax normalizes all three scores together. The categories with negative advantage have no direct term in this positive-only loss, but their probabilities can still decrease as the rewarded category gains probability.
The actual paper uses generated token sequences, a judge reward, and a reference-policy KL penalty. Our example isolates the reward-to-update arithmetic and omits that KL term. It does not establish refusal removal, skill acquisition, or transfer to other prompts.
What changes compared with the geometric methods?
SRA, RFM, and the cosine diagnostic work with representations or candidate directions. Here, the reward guides a parameter update. We do not need a harmful/benign pair or a mean-difference direction first. We do need a reward signal, sampled responses for actual training, and separate evaluation to discover whether the change generalizes or damages other behavior.
Additional executed check of the generic training core
The earlier random-model training check below samples 16 one-token completions and rewards token IDs 4 or 6. It verifies our generic grouped-update primitive separately from the three-category cookie illustration. It does not generate cookie-theft responses or reproduce the paper’s DAPO training setup.