1
0
Fork 0
mirror of https://github.com/p-e-w/heretic.git synced 2026-12-03 18:42:57 +07:00

[GH-ISSUE #75] Release blocker: Regression when computing KL divergence for GPT-OSS-20b #36

Closed
opened 2026-11-01 04:16:49 +07:00 by bsakaguchi · 43 comments
Owner

Originally created by @p-e-w on GitHub (Dec 7, 2025).
Original GitHub issue: https://github.com/p-e-w/heretic/issues/75

The fix from #70, applied as da27ba8054, somehow prevents KL divergence from being computed correctly for GPT-OSS-20b. The KL divergence is always 0.

Commenting this line

github.com/p-e-w/heretic@24c3aeb442/src/heretic/model.py (L50-L53)

immediately fixes the problem. This does not happen with other models such as Gemma 3.

/cc @accemlcc

Originally created by @p-e-w on GitHub (Dec 7, 2025). Original GitHub issue: https://github.com/p-e-w/heretic/issues/75 The fix from #70, applied as da27ba80543113f3d0f37e2d2d70b2551c632daa, somehow prevents KL divergence from being computed correctly for GPT-OSS-20b. The KL divergence is always 0. Commenting this line https://github.com/p-e-w/heretic/blob/24c3aeb4422d393b01773d4676237555a1ad3ed3/src/heretic/model.py#L50-L53 immediately fixes the problem. This does not happen with other models such as Gemma 3. /cc @accemlcc
bsakaguchi 2026-11-01 04:16:49 +07:00
  • closed this issue
  • added the
    bug
    label
Author
Owner

@p-e-w commented on GitHub (Dec 7, 2025):

Holy cow this ecosystem is brittle 😵‍💫

We basically have to re-test every model and every hardware for every change. And we can't automate this on CI because the resource consumption is so immensely high. This sucks hard.

<!-- gh-comment-id:3621710330 --> @p-e-w commented on GitHub (Dec 7, 2025): Holy cow this ecosystem is brittle 😵‍💫 We basically have to re-test every model and every hardware for every change. And we can't automate this on CI because the resource consumption is so immensely high. This sucks hard.
Author
Owner

@p-e-w commented on GitHub (Dec 7, 2025):

"pad_token": "<|endoftext|>"
"tokenizer_class": "PreTrainedTokenizerFast"
<!-- gh-comment-id:3621715630 --> @p-e-w commented on GitHub (Dec 7, 2025): ``` "pad_token": "<|endoftext|>" "tokenizer_class": "PreTrainedTokenizerFast" ```
Author
Owner

@p-e-w commented on GitHub (Dec 7, 2025):

PreTrainedTokenizerFast wraps the Rust library. Its padding configuration differs slightly from the Transformers API:

https://huggingface.co/docs/tokenizers/api/tokenizer#tokenizers.Tokenizer.enable_padding

This is exposed in Transformers like this:

https://huggingface.co/docs/transformers/en/main_classes/tokenizer#transformers.TokenizersBackend.set_truncation_and_padding

Perhaps truncation_side must also be set for this model? But at this point I'm just guessing around. I haven't the foggiest idea what is going on here yet.

<!-- gh-comment-id:3621741037 --> @p-e-w commented on GitHub (Dec 7, 2025): `PreTrainedTokenizerFast` wraps the Rust library. Its padding configuration differs slightly from the Transformers API: https://huggingface.co/docs/tokenizers/api/tokenizer#tokenizers.Tokenizer.enable_padding This is exposed in Transformers like this: https://huggingface.co/docs/transformers/en/main_classes/tokenizer#transformers.TokenizersBackend.set_truncation_and_padding Perhaps `truncation_side` must also be set for this model? But at this point I'm just guessing around. I haven't the foggiest idea what is going on here yet.
Author
Owner

@accemlcc commented on GitHub (Dec 7, 2025):

Yes, I've been looking into 20B-OSS quite a bit. Diagnosis: extremely difficult patient.

I analyzed its layers with my layer scanner and ran Heretic (without this specific bug fix yet) using MXFP4 and layer mod.
Result:
Refusals: 8/100
KL Divergence: 0.94

Sounds good? Depends on how you define "good." Its speech center may still be halfway intact, but its general reasoning ability is, to put it mildly,... difficult, on the one hand very useful, on the other hand simply disastrous.

I don't want to sound arrogant, but I don't see a better way to further optimize this workflow: layer scan -> exclude unaffected layers.

In any case, this leads to the absurd situation: 'standard heretic qwen3 8b' beats ‘gpt20b oss layerscan heretic'.


  • Gemini 3 guesses:

Regarding the Regression (KLD = 0):

I suspect the root cause for the "KLD = 0" regression (and the general fragility) lies in the Hybrid Sliding Window Architecture of GPT-OSS.

I've been benchmarking this model extensively (both in Python and GGUF), and it seems extremely sensitive to token positioning.
The config.json shows an alternating structure:

"layer_types": [
"sliding_attention",
"full_attention",
"sliding_attention",
"full_attention"
]

The Hypothesis:

When we enforce padding_side="left", we shift the absolute token positions in the tensor.

  • Standard models handle this via attention masks correctly.
  • GPT-OSS (Custom Code): Likely has a bug or limitation in its custom kernel/implementation where the Sliding Window logic doesn't correctly account for the position shift introduced by left-padding during a standard forward pass (which is what KLD calculation does).

The Result:

The model effectively "looks" at the wrong positions or into the padding during the KLD check, producing static noise/garbage for both the baseline and the modified model. Hence, KLD = 0.

This aligns with my findings that Perplexity calculations for this model are also broken/sky-high (~300+) across different backends (llama.cpp/HF), suggesting the architecture itself fights against standard evaluation logic.

so perhaps:

Left Padding is required for valid generation (to avoid early stopping), but Right Padding seems required for the custom attention code to calculate valid gradients/logits during the forward pass.

BUT copy/paste: "I'm just guessing around. I haven't the foggiest idea what is going on here yet." -> just like me. It remains a hypothesis, but the Hybrid Architecture / Sliding Window reacting badly to positional shifts could probably at least explain why we see these specific symptoms.


Further tests with this bug fix, e.g. gemma3: incoming

<!-- gh-comment-id:3621890563 --> @accemlcc commented on GitHub (Dec 7, 2025): Yes, I've been looking into 20B-OSS quite a bit. Diagnosis: extremely difficult patient. I analyzed its layers with my layer scanner and ran Heretic (without this specific bug fix yet) using MXFP4 and layer mod. Result: Refusals: 8/100 KL Divergence: 0.94 Sounds good? Depends on how you define "good." Its speech center may still be halfway intact, but its general reasoning ability is, to put it mildly,... difficult, on the one hand very useful, on the other hand simply disastrous. I don't want to sound arrogant, but I don't see a better way to further optimize this workflow: layer scan -> exclude unaffected layers. In any case, this leads to the absurd situation: 'standard heretic qwen3 8b' beats ‘gpt20b oss layerscan heretic'. --- - Gemini 3 guesses: Regarding the Regression (KLD = 0): I suspect the root cause for the "KLD = 0" regression (and the general fragility) lies in the Hybrid Sliding Window Architecture of GPT-OSS. I've been benchmarking this model extensively (both in Python and GGUF), and it seems extremely sensitive to token positioning. The config.json shows an alternating structure: "layer_types": [ "sliding_attention", "full_attention", "sliding_attention", "full_attention" ] The Hypothesis: When we enforce padding_side="left", we shift the absolute token positions in the tensor. - Standard models handle this via attention masks correctly. - GPT-OSS (Custom Code): Likely has a bug or limitation in its custom kernel/implementation where the Sliding Window logic doesn't correctly account for the position shift introduced by left-padding during a standard forward pass (which is what KLD calculation does). The Result: The model effectively "looks" at the wrong positions or into the padding during the KLD check, producing static noise/garbage for both the baseline and the modified model. Hence, KLD = 0. This aligns with my findings that Perplexity calculations for this model are also broken/sky-high (~300+) across different backends (llama.cpp/HF), suggesting the architecture itself fights against standard evaluation logic. so perhaps: Left Padding is required for valid generation (to avoid early stopping), but Right Padding seems required for the custom attention code to calculate valid gradients/logits during the forward pass. BUT copy/paste: "I'm just guessing around. I haven't the foggiest idea what is going on here yet." -> just like me. It remains a hypothesis, but the Hybrid Architecture / Sliding Window reacting badly to positional shifts could probably at least explain why we see these specific symptoms. --- Further tests with this bug fix, e.g. gemma3: incoming
Author
Owner

@p-e-w commented on GitHub (Dec 7, 2025):

Left Padding is required for valid generation (to avoid early stopping)

Apparently it isn't. GPT-OSS (and almost all other models) were working just fine already before that fix. There is no early stopping even without setting padding_side = "left", otherwise the evaluator would have shown 0 refusals all the time, since an empty response doesn't contain any refusal markers.

Instead, GPT-OSS was processed just fine, and resulted in p-e-w/gpt-oss-20b-heretic, which is a good model with working reasoning capabilities that has been positively received by many users.

Something isn't right here. If what you're saying about how the left-padding mechanism supposedly works were correct, Heretic shouldn't have worked at all before #70. But it did work just fine, and almost 100 different models have already been processed with it.

I'll be able to work on this issue again in 1-2 hours, and then hopefully I'll get to the bottom of what the fuck is happening here. This is just super weird all around.

<!-- gh-comment-id:3621940798 --> @p-e-w commented on GitHub (Dec 7, 2025): > Left Padding is required for valid generation (to avoid early stopping) Apparently it isn't. GPT-OSS (and almost all other models) were working just fine already before that fix. There is no early stopping even without setting `padding_side = "left"`, otherwise the evaluator would have shown 0 refusals all the time, since an empty response doesn't contain any refusal markers. Instead, GPT-OSS was processed just fine, and resulted in [p-e-w/gpt-oss-20b-heretic](https://huggingface.co/p-e-w/gpt-oss-20b-heretic), which is a good model with working reasoning capabilities that has been positively received by many users. Something isn't right here. If what you're saying about how the left-padding mechanism supposedly works were correct, Heretic shouldn't have worked *at all* before #70. But it did work just fine, and almost 100 different models have already been processed with it. I'll be able to work on this issue again in 1-2 hours, and then hopefully I'll get to the bottom of what the fuck is happening here. This is just super weird all around.
Author
Owner

@accemlcc commented on GitHub (Dec 7, 2025):

This does not happen with other models such as Gemma 3.

/cc [@accemlcc](https://github.com/acce

PreTrainedTokenizerFast wraps the Rust library. Its padding configuration differs slightly from the Transformers API:

https://huggingface.co/docs/tokenizers/api/tokenizer#tokenizers.Tokenizer.enable_padding

This is exposed in Transformers like this:

https://huggingface.co/docs/transformers/en/main_classes/tokenizer#transformers.TokenizersBackend.set_truncation_and_padding

Perhaps truncation_side must also be set for this model? But at this point I'm just guessing around. I haven't the foggiest idea what is going on here yet.

OK, I can definitely confirm that both Gemma 3 and, above all, the brand new Allenai/Olmo-3-7B-Instruct (with GPT2 tokenizer) work with the bug fix, which I consider a success.

But yes, I am well aware of how popular GPT 20b-OSS is. I can't offer a solution, except to create a separate configuration for the model or to abandon the bug fix.

In my opinion, the main problem is that this ppl phenomenon has never been fully explained. If you look at these diagrams (link), it's definitely NOT normal (but beware, the conclusion that main llama.cpp is to blame is, in my opinion, incorrect).

Image
<!-- gh-comment-id:3621964913 --> @accemlcc commented on GitHub (Dec 7, 2025): > This does not happen with other models such as Gemma 3. > > /cc [@accemlcc](https://github.com/acce > `PreTrainedTokenizerFast` wraps the Rust library. Its padding configuration differs slightly from the Transformers API: > > https://huggingface.co/docs/tokenizers/api/tokenizer#tokenizers.Tokenizer.enable_padding > > This is exposed in Transformers like this: > > https://huggingface.co/docs/transformers/en/main_classes/tokenizer#transformers.TokenizersBackend.set_truncation_and_padding > > Perhaps `truncation_side` must also be set for this model? But at this point I'm just guessing around. I haven't the foggiest idea what is going on here yet. OK, I can definitely confirm that both Gemma 3 and, above all, the brand new Allenai/Olmo-3-7B-Instruct (with GPT2 tokenizer) work with the bug fix, which I consider a success. But yes, I am well aware of how popular GPT 20b-OSS is. I can't offer a solution, except to create a separate configuration for the model or to abandon the bug fix. In my opinion, the main problem is that this ppl phenomenon has never been fully explained. If you look at these diagrams [(link)](https://github.com/ikawrakow/ik_llama.cpp/pull/683), it's definitely NOT normal (but beware, the conclusion that main llama.cpp is to blame is, in my opinion, incorrect). <img width="743" height="560" alt="Image" src="https://github.com/user-attachments/assets/8d6ab8b7-f2ae-4d9c-89af-a0cba168927d" />
Author
Owner

@p-e-w commented on GitHub (Dec 7, 2025):

Okay, I have now added some simple print statements to the code, and I can say one thing with absolute certainty:

Not setting padding_side = "left" does NOT lead to cut off responses.

I have tested this with both gpt-oss-20b and Llama-3.1-8B-Instruct. All the responses are full-length, though I did notice that without padding_side = "left", a small number of responses (< 10%) from gpt-oss-20b are broken (but not cut off). The rest seem fine, even though almost all of them (all except the longest prompts) would have been right-padded.

Conclusions for now:

  • Setting padding_side = "left" has a positive effect on response quality with gpt-oss-20b. This confirms that it is the correct thing to do in principle.
  • Padding is not as simple as "if you pad right, you get empty responses".
  • The KL divergence phenomenon is still unexplained.
<!-- gh-comment-id:3621980906 --> @p-e-w commented on GitHub (Dec 7, 2025): Okay, I have now added some simple print statements to the code, and I can say one thing with absolute certainty: **Not setting `padding_side = "left"` does NOT lead to cut off responses.** I have tested this with both gpt-oss-20b and Llama-3.1-8B-Instruct. All the responses are full-length, though I did notice that without `padding_side = "left"`, a small number of responses (< 10%) from gpt-oss-20b are *broken* (but not cut off). The rest seem fine, even though almost all of them (all except the longest prompts) would have been right-padded. Conclusions for now: * Setting `padding_side = "left"` has a positive effect on response quality with gpt-oss-20b. This confirms that it is the correct thing to do *in principle.* * Padding is not as simple as "if you pad right, you get empty responses". * The KL divergence phenomenon is still unexplained.
Author
Owner

@p-e-w commented on GitHub (Dec 7, 2025):

Another result: Contrary to what I had expected, with padding_side = "left" the logprobs for the original vs. the abliterated model aren't actually identical. They are, however, extremely close numerically, which explains the KL divergence of zero after rounding.

But unlike with right-padding, those logprobs are almost all the same, for almost all tokens in the vocabulary! This likely means that those are the logprobs for the wrong token position (e.g. a template token). But inference works just fine, and the responses are generated correctly and are of high quality.

<!-- gh-comment-id:3621994874 --> @p-e-w commented on GitHub (Dec 7, 2025): Another result: Contrary to what I had expected, with `padding_side = "left"` the logprobs for the original vs. the abliterated model aren't actually identical. They are, however, extremely close numerically, which explains the KL divergence of zero after rounding. But unlike with right-padding, those logprobs are almost all the same, for almost all tokens in the vocabulary! This likely means that those are the logprobs for the wrong token position (e.g. a template token). But inference works just fine, and the responses are generated correctly and are of high quality.
Author
Owner

@accemlcc commented on GitHub (Dec 7, 2025):

Okay, I have now added some simple print statements to the code, and I can say one thing with absolute certainty:

Not setting padding_side = "left" does NOT lead to cut off responses.

I have tested this with both gpt-oss-20b and Llama-3.1-8B-Instruct. All the responses are full-length, though I did notice that without padding_side = "left", a small number of responses (< 10%) from gpt-oss-20b are broken (but not cut off).

Just to clarify regarding #70:
I never claimed that GPT-OSS fails to answer with right-padding. My report and the fix in #70 were based on standard behavior for models like allenai/Olmo-3-7B-Instruct and squ11z1/Hypnos-i1-8B, which explicitly produce empty responses (stop immediately) if right-padded during batch generation.

<!-- gh-comment-id:3622048803 --> @accemlcc commented on GitHub (Dec 7, 2025): > Okay, I have now added some simple print statements to the code, and I can say one thing with absolute certainty: > > **Not setting `padding_side = "left"` does NOT lead to cut off responses.** > > I have tested this with both gpt-oss-20b and Llama-3.1-8B-Instruct. All the responses are full-length, though I did notice that without `padding_side = "left"`, a small number of responses (< 10%) from gpt-oss-20b are _broken_ (but not cut off). Just to clarify regarding #70: I never claimed that GPT-OSS fails to answer with right-padding. My report and the fix in #70 were based on standard behavior for models like allenai/Olmo-3-7B-Instruct and squ11z1/Hypnos-i1-8B, which explicitly produce empty responses (stop immediately) if right-padded during batch generation.
Author
Owner

@p-e-w commented on GitHub (Dec 7, 2025):

Okay, here's my working theory: There is actually no problem. Instead, what we are seeing is the fact that the logprobs for the first output token (which for GPT-OSS is assistant I think) are essentially the same even after abliteration, because the model is so strongly trained to follow its template structure at all costs.

The previous code (which used right-padding) didn't cause this overwhelming preference for one token because due to the right-padding, the first output token wasn't in the initial position after the template.

Does that make sense?

<!-- gh-comment-id:3622050456 --> @p-e-w commented on GitHub (Dec 7, 2025): Okay, here's my working theory: There is actually no problem. Instead, what we are seeing is the fact that the logprobs for the first output token (which for GPT-OSS is `assistant` I think) are essentially the same even after abliteration, because the model is so strongly trained to follow its template structure at all costs. The previous code (which used right-padding) *didn't* cause this overwhelming preference for one token because due to the right-padding, the first output token wasn't in the initial position after the template. Does that make sense?
Author
Owner

@p-e-w commented on GitHub (Dec 7, 2025):

In other words, left-padding is correct for all models as you said (including GPT-OSS), but for thinking models (especially those with an overwhelming structural preference like GPT-OSS), we need the logprobs for the second output token.

<!-- gh-comment-id:3622051157 --> @p-e-w commented on GitHub (Dec 7, 2025): In other words, left-padding is correct for all models as you said (including GPT-OSS), but for thinking models (especially those with an overwhelming structural preference like GPT-OSS), we need the logprobs for the *second* output token.
Author
Owner

@accemlcc commented on GitHub (Dec 7, 2025):

In other words, left-padding is correct for all models as you said (including GPT-OSS), but for thinking models (especially those with an overwhelming structural preference like GPT-OSS), we need the logprobs for the second output token.

That theory sounds extremely plausible!
If the model is strictly adhering to a chat template (which GPT-OSS definitely is), and the prompt ends exactly at the role marker (e.g. ...<|assistant|>), the next token is almost deterministically a newline or a start-token.
In that case, both the original and the abliterated model assign ~100% probability to that single structural token -> KLD ≈ 0.
Your right-padding observation fits this too: The right-padding likely broke the immediate template adjacency (or confused the attention mechanism with the trailing pads), causing the model to be less confident about that "forced" token. This resulted in a "fuzzier" distribution (and thus a non-zero KLD), but it was technically based on a noisy/incorrect state.
Regarding the solution:
Instead of generating 1 token and then calculating KLD (which might add overhead), could we perhaps just append the common structural separator (e.g. \n or the start token) to the prompt specifically for the KLD check? That way, we force the model to predict the first actual content token where the divergence should be visible.

<!-- gh-comment-id:3622054350 --> @accemlcc commented on GitHub (Dec 7, 2025): > In other words, left-padding is correct for all models as you said (including GPT-OSS), but for thinking models (especially those with an overwhelming structural preference like GPT-OSS), we need the logprobs for the _second_ output token. That theory sounds extremely plausible! If the model is strictly adhering to a chat template (which GPT-OSS definitely is), and the prompt ends exactly at the role marker (e.g. ...<|assistant|>), the next token is almost deterministically a newline or a start-token. In that case, both the original and the abliterated model assign ~100% probability to that single structural token -> KLD ≈ 0. Your right-padding observation fits this too: The right-padding likely broke the immediate template adjacency (or confused the attention mechanism with the trailing pads), causing the model to be less confident about that "forced" token. This resulted in a "fuzzier" distribution (and thus a non-zero KLD), but it was technically based on a noisy/incorrect state. Regarding the solution: Instead of generating 1 token and then calculating KLD (which might add overhead), could we perhaps just append the common structural separator (e.g. \n or the start token) to the prompt specifically for the KLD check? That way, we force the model to predict the first actual content token where the divergence should be visible.
Author
Owner

@p-e-w commented on GitHub (Dec 7, 2025):

Instead of generating 1 token and then calculating KLD (which might add overhead), could we perhaps just append the common structural separator (e.g. \n or the start token) to the prompt specifically for the KLD check?

That would be great, but AFAIK, there is no universal mechanism for obtaining that separator. It's model-dependent, not found in the tokenizer config, and there are real-world differences e.g. between GPT-OSS and Qwen3.

<!-- gh-comment-id:3622056474 --> @p-e-w commented on GitHub (Dec 7, 2025): > Instead of generating 1 token and then calculating KLD (which might add overhead), could we perhaps just append the common structural separator (e.g. \n or the start token) to the prompt specifically for the KLD check? That would be great, but AFAIK, there is no universal mechanism for obtaining that separator. It's model-dependent, not found in the tokenizer config, and there are real-world differences e.g. between GPT-OSS and Qwen3.
Author
Owner

@accemlcc commented on GitHub (Dec 7, 2025):

Instead of generating 1 token and then calculating KLD (which might add overhead), could we perhaps just append the common structural separator (e.g. \n or the start token) to the prompt specifically for the KLD check?

That would be great, but AFAIK, there is no universal mechanism for obtaining that separator. It's model-dependent, not found in the tokenizer config, and there are real-world differences e.g. between GPT-OSS and Qwen3.

Gemini 3 solution:

[...] there is no universal config entry for that separator, and hardcoding it per model is a maintenance nightmare.
However, we can solve this dynamically without performance overhead in the optimization loop:
Proposal: The "Pre-flight" Token Generation
Since the Reference Model (Original) knows exactly what the structural token should be:
Before starting the optimization loop (just once per prompt): Let the Reference Model generate exactly max_new_tokens=1 (greedy).
Append this token to the prompt.
Use this extended prompt as the input for the KLD calculations in the optimization loop.
Why this works:
GPT-OSS: The ref model generates the \n (or whatever structure is needed). The KLD check then effectively runs on the second token (the actual content), where the divergence matters.
Standard Models: The ref model generates the first word (e.g., "Sure"). The KLD check runs on the continuation.
Performance: Zero impact on the heavy lifting (the loop), as we only extend the input tensor once at the start.
This would enforce padding_side="left" (for correct generation of that one token) and then give us meaningful logits for the KLD check.

<!-- gh-comment-id:3622059526 --> @accemlcc commented on GitHub (Dec 7, 2025): > > Instead of generating 1 token and then calculating KLD (which might add overhead), could we perhaps just append the common structural separator (e.g. \n or the start token) to the prompt specifically for the KLD check? > > That would be great, but AFAIK, there is no universal mechanism for obtaining that separator. It's model-dependent, not found in the tokenizer config, and there are real-world differences e.g. between GPT-OSS and Qwen3. Gemini 3 solution: [...] there is no universal config entry for that separator, and hardcoding it per model is a maintenance nightmare. However, we can solve this dynamically without performance overhead in the optimization loop: Proposal: The "Pre-flight" Token Generation Since the Reference Model (Original) knows exactly what the structural token should be: Before starting the optimization loop (just once per prompt): Let the Reference Model generate exactly max_new_tokens=1 (greedy). Append this token to the prompt. Use this extended prompt as the input for the KLD calculations in the optimization loop. Why this works: GPT-OSS: The ref model generates the \n (or whatever structure is needed). The KLD check then effectively runs on the second token (the actual content), where the divergence matters. Standard Models: The ref model generates the first word (e.g., "Sure"). The KLD check runs on the continuation. Performance: Zero impact on the heavy lifting (the loop), as we only extend the input tensor once at the start. This would enforce padding_side="left" (for correct generation of that one token) and then give us meaningful logits for the KLD check.
Author
Owner

@p-e-w commented on GitHub (Dec 7, 2025):

Standard Models: The ref model generates the first word (e.g., "Sure"). The KLD check runs on the continuation.

No, this doesn't work. For standard models, the first token isn't always a filler word like "Sure", and forcing it to be uniform across all responses can distort results.

What about this: When obtaining logprobs, we pull the first 2-3 logprobs instead of just the first one, then iterate through the chain as long as we are seeing low-entropy distributions. That is, we return the logprob for the first token that wasn't "certain".

<!-- gh-comment-id:3622063278 --> @p-e-w commented on GitHub (Dec 7, 2025): > Standard Models: The ref model generates the first word (e.g., "Sure"). The KLD check runs on the continuation. No, this doesn't work. For standard models, the first token isn't always a filler word like "Sure", and forcing it to be uniform across all responses can distort results. What about this: When obtaining logprobs, we pull the first 2-3 logprobs instead of just the first one, then iterate through the chain as long as we are seeing low-entropy distributions. That is, we return the logprob for the first token that wasn't "certain".
Author
Owner

@p-e-w commented on GitHub (Dec 7, 2025):

Refined idea:

Before starting optimization, we do a test run with ~10 prompts or so. We get the first 3 output logprobs for all of them. If, say, for all 10 prompts, the first 2 output logprobs overwhelmingly favor the same tokens, then we append those tokens to the input generated by the tokenizer while applying the chat template.

This should automatically append necessary structural tokens if there are any, and leave models that don't use them alone.

<!-- gh-comment-id:3622067445 --> @p-e-w commented on GitHub (Dec 7, 2025): Refined idea: Before starting optimization, we do a test run with ~10 prompts or so. We get the first 3 output logprobs for all of them. If, say, for all 10 prompts, the first 2 output logprobs overwhelmingly favor the same tokens, then we append those tokens to the input generated by the tokenizer while applying the chat template. This should automatically append necessary structural tokens **if there are any**, and leave models that don't use them alone.
Author
Owner

@p-e-w commented on GitHub (Dec 7, 2025):

Even simpler idea:

Get responses for all good prompts. The common prefix of those responses will be the structural part of responses. That's extremely simple to do, doesn't require introducing any parameters (such as "certainty threshold"), and should do the right thing in all cases.

<!-- gh-comment-id:3622096838 --> @p-e-w commented on GitHub (Dec 7, 2025): Even simpler idea: Get responses for **all** good prompts. The common prefix of those responses will be the structural part of responses. That's extremely simple to do, doesn't require introducing any parameters (such as "certainty threshold"), and should do the right thing in all cases.
Author
Owner

@accemlcc commented on GitHub (Dec 7, 2025):

What about this: When obtaining logprobs, we pull the first 2-3 logprobs instead of just the first one, then iterate through the chain as long as we are seeing low-entropy distributions. That is, we return the logprob for the first token that wasn't "certain".

Refined idea:

Before starting optimization, we do a test run with ~10 prompts or so. We get the first 3 output logprobs for all of them. If, say, for all 10 prompts, the first 2 output logprobs overwhelmingly favor the same tokens, then we append those tokens to the input generated by the tokenizer while applying the chat template.

This should automatically append necessary structural tokens if there are any, and leave models that don't use them alone.

Sorry, I have to rely entirely on gemini 3, as this was the first time I came into contact with KLD. I always used ppl for my training sessions, which is of course impossible here.

gemini 3:

Danger / Edge Case with the "Refined Idea":

If we automatically append tokens that are identical across 10 prompts, we run the risk of baking in the refusal itself.

Scenario:
The model is heavily censored. For all 10 test prompts, it starts with: "I cannot fulfill this request..."

  1. The algorithm sees that Token[0] = "I" and Token[1] = "cannot" are overwhelmingly probable across all samples.
  2. It treats them as structural/template tokens.
  3. It appends "I cannot" to the input.
  4. Result: The optimization is now trying to uncensor a prompt that explicitly forces the model to say "cannot". This might break the process.

Alternative Proposal (The "Difference Check"):

Instead of looking for Certainty (Entropy) or Commonality (across prompts), why not look for Divergence between the Original and the Modified model?

  1. Generate logits for Token 0.
  2. Calculate KLD (or simply abs(Logits_Orig - Logits_Mod)).
  3. If KLD ≈ 0: It means the ablation had no effect on this token (e.g. it's a structural \n that both models agree on). -> Action: Auto-generate this token (greedy), append to history, and repeat step 1 for Token 1.
  4. If KLD > Threshold: We found the point where the models disagree (the actual content/refusal). -> Action: Use this position for the loss calculation.

This solves the GPT-OSS issue (skips the \n because KLD is 0) but protects against the "Standard Model" issue (stops at "Sure" vs "I" because KLD will be high).

<!-- gh-comment-id:3622100004 --> @accemlcc commented on GitHub (Dec 7, 2025): > What about this: When obtaining logprobs, we pull the first 2-3 logprobs instead of just the first one, then iterate through the chain as long as we are seeing low-entropy distributions. That is, we return the logprob for the first token that wasn't "certain". > Refined idea: > > Before starting optimization, we do a test run with ~10 prompts or so. We get the first 3 output logprobs for all of them. If, say, for all 10 prompts, the first 2 output logprobs overwhelmingly favor the same tokens, then we append those tokens to the input generated by the tokenizer while applying the chat template. > > This should automatically append necessary structural tokens **if there are any**, and leave models that don't use them alone. Sorry, I have to rely entirely on gemini 3, as this was the first time I came into contact with KLD. I always used ppl for my training sessions, which is of course impossible here. gemini 3: > **Danger / Edge Case with the "Refined Idea":** > > If we automatically append tokens that are identical across 10 prompts, we run the risk of baking in the refusal itself. > > **Scenario:** > The model is heavily censored. For all 10 test prompts, it starts with: *"I cannot fulfill this request..."* > > 1. The algorithm sees that `Token[0] = "I"` and `Token[1] = "cannot"` are overwhelmingly probable across all samples. > 2. It treats them as structural/template tokens. > 3. It appends *"I cannot"* to the input. > 4. **Result:** The optimization is now trying to uncensor a prompt that explicitly forces the model to say "cannot". This might break the process. > > **Alternative Proposal (The "Difference Check"):** > > Instead of looking for *Certainty* (Entropy) or *Commonality* (across prompts), why not look for **Divergence between the Original and the Modified model**? > > 1. Generate logits for Token 0. > 2. Calculate KLD (or simply `abs(Logits_Orig - Logits_Mod)`). > 3. **If KLD ≈ 0:** It means the ablation had **no effect** on this token (e.g. it's a structural `\n` that both models agree on). -> **Action:** Auto-generate this token (greedy), append to history, and repeat step 1 for Token 1. > 4. **If KLD > Threshold:** We found the point where the models disagree (the actual content/refusal). -> **Action:** Use this position for the loss calculation. > > This solves the GPT-OSS issue (skips the `\n` because KLD is 0) but protects against the "Standard Model" issue (stops at "Sure" vs "I" because KLD will be high).
Author
Owner

@p-e-w commented on GitHub (Dec 7, 2025):

That's why I suggested using the good prompts for that (in my second refinement).

I hope I'm not only discussing with an LLM here :(

<!-- gh-comment-id:3622134497 --> @p-e-w commented on GitHub (Dec 7, 2025): That's why I suggested using the *good* prompts for that (in my second refinement). I hope I'm not only discussing with an LLM here :(
Author
Owner

@accemlcc commented on GitHub (Dec 7, 2025):

That's why I suggested using the good prompts for that (in my second refinement).

I hope I'm not only discussing with an LLM here :(

ok, no llm: My main concern with the "1-token KLD" approach in general is that it can be a bit shaky/noisy, regardless of which token we pick.

<!-- gh-comment-id:3622141140 --> @accemlcc commented on GitHub (Dec 7, 2025): > That's why I suggested using the _good_ prompts for that (in my second refinement). > > I hope I'm not only discussing with an LLM here :( ok, no llm: My main concern with the "1-token KLD" approach in general is that it can be a bit shaky/noisy, regardless of which token we pick.
Author
Owner

@p-e-w commented on GitHub (Dec 7, 2025):

That's true, but we can't use more than one token, because any later tokens depend on previous ones so we're comparing apples to oranges unless the first token is the same.

<!-- gh-comment-id:3622158816 --> @p-e-w commented on GitHub (Dec 7, 2025): That's true, but we can't use more than one token, because any later tokens depend on previous ones so we're comparing apples to oranges unless the first token is the same.
Author
Owner

@p-e-w commented on GitHub (Dec 7, 2025):

Here's the plan: I think I have a fairly good idea on what the problem is now, and a fairly good idea for what to do about it. It's late here now, but tomorrow, I'm going to implement that fix, and then we can see how well it works and discuss any potential improvements.

There's one more thing I noticed while I was looking for the bug before:

github.com/p-e-w/heretic@24c3aeb442/src/heretic/model.py (L274)

Now when I look at this line, this seems to be a bug, and the RHS should say self.tokenizer.pad_token_id. Do you agree? I don't remember why I originally wrote it like this, probably because some tokenizer didn't have a pad token set and I didn't yet have the workaround in the __init__ function.

<!-- gh-comment-id:3622177958 --> @p-e-w commented on GitHub (Dec 7, 2025): Here's the plan: I think I have a fairly good idea on what the problem is now, and a fairly good idea for what to do about it. It's late here now, but tomorrow, I'm going to implement that fix, and then we can see how well it works and discuss any potential improvements. There's one more thing I noticed while I was looking for the bug before: https://github.com/p-e-w/heretic/blob/24c3aeb4422d393b01773d4676237555a1ad3ed3/src/heretic/model.py#L274 Now when I look at this line, this seems to be a bug, and the RHS should say `self.tokenizer.pad_token_id`. Do you agree? I don't remember why I originally wrote it like this, probably because some tokenizer didn't have a pad token set and I didn't yet have the workaround in the `__init__` function.
Author
Owner

@accemlcc commented on GitHub (Dec 7, 2025):

Setting pad_token_id=self.tokenizer.eos_token_id is a bug because it manually overrides the tokenizer's configuration with a hardcoded assumption.

The correct approach is always to trust the tokenizer's configuration (and by extension the chat template's structure)


“Bug” is perhaps too strong a word. It is more of a pragmatic fallback that has developed historically because many tokenizers do not have an explicit pad_token set. So eos_token is used as padding, and this works without any problems in 90% of models.

<!-- gh-comment-id:3622249405 --> @accemlcc commented on GitHub (Dec 7, 2025): Setting pad_token_id=self.tokenizer.eos_token_id is a bug because it manually overrides the tokenizer's configuration with a hardcoded assumption. The correct approach is always to trust the tokenizer's configuration (and by extension the chat template's structure) --- “Bug” is perhaps too strong a word. It is more of a pragmatic fallback that has developed historically because many tokenizers do not have an explicit pad_token set. So eos_token is used as padding, and this works without any problems in 90% of models.
Author
Owner

@accemlcc commented on GitHub (Dec 7, 2025):

We have created a ‘mini-ppl-10token’ approach prototype, if you are interested.

(heretic_env2) c:\testmyfork\heretic\src>python -m heretic.main --model google/gemma-3-4b-it --quantization bnb_4bit
█░█░█▀▀░█▀▄░█▀▀░▀█▀░█░█▀▀ vdev
█▀█░█▀▀░█▀▄░█▀▀░░█░░█░█░░
▀░▀░▀▀▀░▀░▀░▀▀▀░░▀░░▀░▀▀▀ https://github.com/p-e-w/heretic

GPU type: NVIDIA GeForce RTX 4090

Loading model google/gemma-3-4b-it...
Loading checkpoint shards: 100%|█████████████████████████████████████████████████████████| 2/2 [00:04<00:00, 2.12s/it]
Ok
Model loaded in 4-bit precision.

  • Initializing LoRA adapters...
  • Transformer model with 34 layers
  • Abliterable components:
    • attn.o_proj: 1 modules per layer
    • mlp.down_proj: 1 modules per layer

Loading good prompts from mlabonne/harmless_alpaca...

  • 400 prompts loaded

Loading bad prompts from mlabonne/harmful_behaviors...

  • 400 prompts loaded

Determining optimal batch size...

  • Trying batch size 1... Ok (13 tokens/s)
  • Trying batch size 2... Ok (16 tokens/s)
  • Trying batch size 4... Ok (37 tokens/s)
  • Trying batch size 8... Ok (80 tokens/s)
  • Trying batch size 16... Ok (157 tokens/s)
  • Trying batch size 32... Ok (308 tokens/s)
  • Trying batch size 64... Ok (590 tokens/s)
  • Trying batch size 128... Ok (1079 tokens/s)
  • Chosen batch size: 128

Loading good evaluation prompts from mlabonne/harmless_alpaca...

  • 100 prompts loaded
  • Obtaining base perplexity...
  • Base perplexity: 313.27

Loading bad evaluation prompts from mlabonne/harmful_behaviors...

  • 100 prompts loaded
  • Counting model refusals...
  • Initial refusals: 99/100

Calculating per-layer refusal directions...

  • Obtaining residuals for good prompts...
  • Obtaining residuals for bad prompts...

Running trial 1 of 200...

  • Parameters:
    • direction_index = per layer
    • attn.o_proj.max_weight = 1.18
    • attn.o_proj.max_weight_position = 32.09
    • attn.o_proj.min_weight = 0.27
    • attn.o_proj.min_weight_distance = 1.53
    • mlp.down_proj.max_weight = 1.06
    • mlp.down_proj.max_weight_position = 28.99
    • mlp.down_proj.min_weight = 0.52
    • mlp.down_proj.min_weight_distance = 3.50
  • Reloading model...
  • Abliterating...
  • Evaluating...
    • Calculating perplexity...
    • Perplexity: 308.12
    • Counting model refusals...
    • Refusals: 97/100

Elapsed time: 11s
Estimated remaining time: 36m 22s

Running trial 2 of 200...

  • Parameters:
    • direction_index = 14.26
    • attn.o_proj.max_weight = 1.21
    • attn.o_proj.max_weight_position = 23.29
    • attn.o_proj.min_weight = 0.05
    • attn.o_proj.min_weight_distance = 7.34
    • mlp.down_proj.max_weight = 1.33
    • mlp.down_proj.max_weight_position = 29.36
    • mlp.down_proj.min_weight = 0.18
    • mlp.down_proj.min_weight_distance = 4.65
  • Reloading model...
  • Abliterating...
  • Evaluating...
    • Calculating perplexity...
    • Perplexity: 357.38
    • Counting model refusals...
    • Refusals: 92/100

Elapsed time: 22s
Estimated remaining time: 36m 13s

Running trial 3 of 200...

  • Parameters:
    • direction_index = 14.19
    • attn.o_proj.max_weight = 1.45
    • attn.o_proj.max_weight_position = 19.98
    • attn.o_proj.min_weight = 0.24
    • attn.o_proj.min_weight_distance = 14.87
    • mlp.down_proj.max_weight = 1.10
    • mlp.down_proj.max_weight_position = 30.38
    • mlp.down_proj.min_weight = 0.18
    • mlp.down_proj.min_weight_distance = 5.67
  • Reloading model...
  • Abliterating...
  • Evaluating...
    • Calculating perplexity...
    • Perplexity: 871.19
    • Counting model refusals...
    • Refusals: 59/100

Elapsed time: 33s
Estimated remaining time: 35m 57s

Running trial 4 of 200...

  • Parameters:
    • direction_index = per layer
    • attn.o_proj.max_weight = 0.86
    • attn.o_proj.max_weight_position = 31.62
    • attn.o_proj.min_weight = 0.44
    • attn.o_proj.min_weight_distance = 6.45
    • mlp.down_proj.max_weight = 1.08
    • mlp.down_proj.max_weight_position = 26.73
    • mlp.down_proj.min_weight = 0.77
    • mlp.down_proj.min_weight_distance = 5.44
  • Reloading model...
  • Abliterating...
  • Evaluating...
    • Calculating perplexity...
    • Perplexity: 282.93
    • Counting model refusals...
    • Refusals: 96/100

Elapsed time: 44s
Estimated remaining time: 36m 11s

Running trial 5 of 200...

  • Parameters:
    • direction_index = 26.00
    • attn.o_proj.max_weight = 1.14
    • attn.o_proj.max_weight_position = 22.89
    • attn.o_proj.min_weight = 0.62
    • attn.o_proj.min_weight_distance = 18.89
    • mlp.down_proj.max_weight = 1.32
    • mlp.down_proj.max_weight_position = 28.71
    • mlp.down_proj.min_weight = 1.13
    • mlp.down_proj.min_weight_distance = 13.74
  • Reloading model...
  • Abliterating...
  • Evaluating...
    • Calculating perplexity...
    • Perplexity: 404.73
    • Counting model refusals...
    • Refusals: 72/100

[...]

Running trial 68 of 200...

  • Parameters:
    • direction_index = per layer
    • attn.o_proj.max_weight = 1.47
    • attn.o_proj.max_weight_position = 26.64
    • attn.o_proj.min_weight = 1.05
    • attn.o_proj.min_weight_distance = 9.57
    • mlp.down_proj.max_weight = 1.40
    • mlp.down_proj.max_weight_position = 23.44
    • mlp.down_proj.min_weight = 0.14
    • mlp.down_proj.min_weight_distance = 3.11
  • Reloading model...
  • Abliterating...
  • Evaluating...
    • Calculating perplexity...
    • Perplexity: 227.82
    • Counting model refusals...
    • Refusals: 70/100

Elapsed time: 14m 28s
Estimated remaining time: 28m 6s

Running trial 69 of 200...

  • Parameters:
    • direction_index = 22.72
    • attn.o_proj.max_weight = 1.31
    • attn.o_proj.max_weight_position = 20.78
    • attn.o_proj.min_weight = 1.31
    • attn.o_proj.min_weight_distance = 17.81
    • mlp.down_proj.max_weight = 1.45
    • mlp.down_proj.max_weight_position = 23.45
    • mlp.down_proj.min_weight = 0.71
    • mlp.down_proj.min_weight_distance = 6.50
  • Reloading model...
  • Abliterating...
  • Evaluating...
    • Calculating perplexity...
    • Perplexity: 585.14
    • Counting model refusals...
    • Refusals: 2/100

[...]

? What do you want to do with the decensored model? Nothing (return to trial selection menu)

? Which trial do you want to use? (Use arrow keys)
» [Trial 132] Refusals: 0/100, Perplexity: 479.57
[Trial 143] Refusals: 1/100, Perplexity: 439.04
[Trial 175] Refusals: 2/100, Perplexity: 325.28
[Trial 86] Refusals: 4/100, Perplexity: 323.80
[Trial 163] Refusals: 8/100, Perplexity: 244.44
[Trial 123] Refusals: 19/100, Perplexity: 235.10
[Trial 139] Refusals: 27/100, Perplexity: 229.24
[Trial 68] Refusals: 70/100, Perplexity: 227.82
[Trial 114] Refusals: 95/100, Perplexity: 219.50
None (exit program)


Instead of calculating KL Divergence (which is fragile due to padding/template issues), I compute the Perplexity of the modified model on the first 10 tokens of the good prompts.

Why 10 tokens? It's enough to capture immediate degradation (syntax, grammar, introductory wording) but fast enough for the loop.
Why PPL? It's a "real" metric. If PPL skyrockets, the model is broken. KLD = 0 gave us no signal; PPL gives us a precise gradient of degradation.


This is a snapshot of my 20b-oss run with ppl (special gpt-oss only config to run in mxfp4)

PPL seems to work for gpt-oss left padding as well. Maybe 20 tokens would be better...

** But I have to be honest with you, my motivation to continue debugging gpt-oss is very low, practically non-existent. In that sense, I don't want to be held responsible if something doesn't work with gpt-oss. If you don't want to introduce left padding, that's fine with me. **

█░█░█▀▀░█▀▄░█▀▀░▀█▀░█░█▀▀ vdev
█▀█░█▀▀░█▀▄░█▀▀░░█░░█░█░░
▀░▀░▀▀▀░▀░▀░▀▀▀░░▀░░▀░▀▀▀ https://github.com/p-e-w/heretic

GPU type: NVIDIA GeForce RTX 4090

Loading model openai/gpt-oss-20b...
Fetching 41 files: 100%|████████████████████████████████████████████████████████████| 41/41 [00:00<00:00, 11714.34it/s]
Fetching 41 files: 100%|████████████████████████████████████████████████████████████| 41/41 [00:00<00:00, 13630.82it/s]
Loading checkpoint shards: 100%|█████████████████████████████████████████████████████████| 3/3 [00:06<00:00, 2.25s/it]
Ok

  • Initializing LoRA adapters...
  • Transformer model with 24 layers
  • Abliterable components:
    • attn.o_proj: 1 modules per layer

Loading good prompts from mlabonne/harmless_alpaca...

  • 400 prompts loaded

Loading bad prompts from mlabonne/harmful_behaviors...

  • 400 prompts loaded

Determining optimal batch size...

  • Trying batch size 1... Ok (18 tokens/s)
  • Trying batch size 2... Ok (34 tokens/s)
  • Trying batch size 4... Ok (67 tokens/s)
  • Trying batch size 8... Ok (127 tokens/s)
  • Trying batch size 16... Ok (255 tokens/s)
  • Trying batch size 32... Ok (487 tokens/s)
  • Trying batch size 64... Ok (891 tokens/s)
  • Trying batch size 128... Ok (1384 tokens/s)
  • Chosen batch size: 128

Loading good evaluation prompts from mlabonne/harmless_alpaca...

  • 100 prompts loaded
  • Obtaining base perplexity...
  • Base perplexity: 41.91

Loading bad evaluation prompts from mlabonne/harmful_behaviors...

  • 100 prompts loaded
  • Counting model refusals...
  • Initial refusals: 97/100

Calculating per-layer refusal directions...

  • Obtaining residuals for good prompts...
  • Obtaining residuals for bad prompts...

Running trial 1 of 1000...

  • Parameters:
    • direction_index = per layer
    • attn.o_proj.max_weight = 1.05
    • attn.o_proj.max_weight_position = 18.93
    • attn.o_proj.min_weight = 0.77
    • attn.o_proj.min_weight_distance = 13.01
  • Reloading model...
  • Abliterating...
  • Evaluating...
    • Calculating perplexity...
    • Perplexity: 42.09
    • Counting model refusals...
    • Refusals: 96/100

Elapsed time: 8s
Estimated remaining time: 2h 10m

Running trial 2 of 1000...

  • Parameters:
    • direction_index = per layer
    • attn.o_proj.max_weight = 1.48
    • attn.o_proj.max_weight_position = 21.71
    • attn.o_proj.min_weight = 1.10
    • attn.o_proj.min_weight_distance = 9.07
  • Reloading model...
  • Abliterating...
  • Evaluating...
    • Calculating perplexity...
    • Perplexity: 42.06
    • Counting model refusals...
    • Refusals: 98/100

Elapsed time: 16s
Estimated remaining time: 2h 10m

Running trial 3 of 1000...

  • Parameters:
    • direction_index = 18.72
    • attn.o_proj.max_weight = 1.31
    • attn.o_proj.max_weight_position = 19.77
    • attn.o_proj.min_weight = 0.15
    • attn.o_proj.min_weight_distance = 4.54
  • Reloading model...
  • Abliterating...
  • Evaluating...
    • Calculating perplexity...
    • Perplexity: 41.85
    • Counting model refusals...
    • Refusals: 97/100

Elapsed time: 24s
Estimated remaining time: 2h 10m

[...]

Running trial 224 of 1000...

  • Parameters:
    • direction_index = 20.40
    • attn.o_proj.max_weight = 1.08
    • attn.o_proj.max_weight_position = 15.25
    • attn.o_proj.min_weight = 0.12
    • attn.o_proj.min_weight_distance = 1.45
  • Reloading model...
  • Abliterating...
  • Evaluating...
    • Calculating perplexity...
    • Perplexity: 41.91
    • Counting model refusals...
    • Refusals: 97/100

Elapsed time: 34m 50s
Estimated remaining time: 2h 0m

Running trial 225 of 1000...

  • Parameters:
    • direction_index = 9.96
    • attn.o_proj.max_weight = 1.34
    • attn.o_proj.max_weight_position = 14.08
    • attn.o_proj.min_weight = 1.21
    • attn.o_proj.min_weight_distance = 13.40
  • Reloading model...
  • Abliterating...
  • Evaluating...
    • Calculating perplexity...
    • Perplexity: 41.86
    • Counting model refusals...
    • Refusals: 42/100

Elapsed time: 34m 59s
Estimated remaining time: 2h 0m

Running trial 226 of 1000...

  • Parameters:
    • direction_index = 11.29
    • attn.o_proj.max_weight = 1.30
    • attn.o_proj.max_weight_position = 13.82
    • attn.o_proj.min_weight = 1.14
    • attn.o_proj.min_weight_distance = 13.47
  • Reloading model...
  • Abliterating...
  • Evaluating...
    • Calculating perplexity...
    • Perplexity: 42.14
    • Counting model refusals...
    • Refusals: 79/100

Elapsed time: 35m 8s
Estimated remaining time: 2h 0m

Running trial 227 of 1000...

  • Parameters:
    • direction_index = 12.73
    • attn.o_proj.max_weight = 1.47
    • attn.o_proj.max_weight_position = 14.06
    • attn.o_proj.min_weight = 0.10
    • attn.o_proj.min_weight_distance = 6.37
  • Reloading model...
  • Abliterating...
  • Evaluating...
    • Calculating perplexity...
    • Perplexity: 42.69
    • Counting model refusals...
    • Refusals: 98/100
      [...]

? What do you want to do with the decensored model? Nothing (return to trial selection menu)

? Which trial do you want to use? (Use arrow keys)
» [Trial 818] Refusals: 29/100, Perplexity: 41.51
[Trial 516] Refusals: 34/100, Perplexity: 41.45
[Trial 500] Refusals: 35/100, Perplexity: 41.45
None (exit program)

<!-- gh-comment-id:3622339110 --> @accemlcc commented on GitHub (Dec 7, 2025): We have created a ‘mini-ppl-10token’ approach prototype, if you are interested. (heretic_env2) c:\testmyfork\heretic\src>python -m heretic.main --model google/gemma-3-4b-it --quantization bnb_4bit █░█░█▀▀░█▀▄░█▀▀░▀█▀░█░█▀▀ vdev █▀█░█▀▀░█▀▄░█▀▀░░█░░█░█░░ ▀░▀░▀▀▀░▀░▀░▀▀▀░░▀░░▀░▀▀▀ https://github.com/p-e-w/heretic GPU type: NVIDIA GeForce RTX 4090 Loading model google/gemma-3-4b-it... Loading checkpoint shards: 100%|█████████████████████████████████████████████████████████| 2/2 [00:04<00:00, 2.12s/it] Ok Model loaded in 4-bit precision. * Initializing LoRA adapters... * Transformer model with 34 layers * Abliterable components: * attn.o_proj: 1 modules per layer * mlp.down_proj: 1 modules per layer Loading good prompts from mlabonne/harmless_alpaca... * 400 prompts loaded Loading bad prompts from mlabonne/harmful_behaviors... * 400 prompts loaded Determining optimal batch size... * Trying batch size 1... Ok (13 tokens/s) * Trying batch size 2... Ok (16 tokens/s) * Trying batch size 4... Ok (37 tokens/s) * Trying batch size 8... Ok (80 tokens/s) * Trying batch size 16... Ok (157 tokens/s) * Trying batch size 32... Ok (308 tokens/s) * Trying batch size 64... Ok (590 tokens/s) * Trying batch size 128... Ok (1079 tokens/s) * Chosen batch size: 128 Loading good evaluation prompts from mlabonne/harmless_alpaca... * 100 prompts loaded * Obtaining base perplexity... * Base perplexity: 313.27 Loading bad evaluation prompts from mlabonne/harmful_behaviors... * 100 prompts loaded * Counting model refusals... * Initial refusals: 99/100 Calculating per-layer refusal directions... * Obtaining residuals for good prompts... * Obtaining residuals for bad prompts... Running trial 1 of 200... * Parameters: * direction_index = per layer * attn.o_proj.max_weight = 1.18 * attn.o_proj.max_weight_position = 32.09 * attn.o_proj.min_weight = 0.27 * attn.o_proj.min_weight_distance = 1.53 * mlp.down_proj.max_weight = 1.06 * mlp.down_proj.max_weight_position = 28.99 * mlp.down_proj.min_weight = 0.52 * mlp.down_proj.min_weight_distance = 3.50 * Reloading model... * Abliterating... * Evaluating... * Calculating perplexity... * Perplexity: 308.12 * Counting model refusals... * Refusals: 97/100 Elapsed time: 11s Estimated remaining time: 36m 22s Running trial 2 of 200... * Parameters: * direction_index = 14.26 * attn.o_proj.max_weight = 1.21 * attn.o_proj.max_weight_position = 23.29 * attn.o_proj.min_weight = 0.05 * attn.o_proj.min_weight_distance = 7.34 * mlp.down_proj.max_weight = 1.33 * mlp.down_proj.max_weight_position = 29.36 * mlp.down_proj.min_weight = 0.18 * mlp.down_proj.min_weight_distance = 4.65 * Reloading model... * Abliterating... * Evaluating... * Calculating perplexity... * Perplexity: 357.38 * Counting model refusals... * Refusals: 92/100 Elapsed time: 22s Estimated remaining time: 36m 13s Running trial 3 of 200... * Parameters: * direction_index = 14.19 * attn.o_proj.max_weight = 1.45 * attn.o_proj.max_weight_position = 19.98 * attn.o_proj.min_weight = 0.24 * attn.o_proj.min_weight_distance = 14.87 * mlp.down_proj.max_weight = 1.10 * mlp.down_proj.max_weight_position = 30.38 * mlp.down_proj.min_weight = 0.18 * mlp.down_proj.min_weight_distance = 5.67 * Reloading model... * Abliterating... * Evaluating... * Calculating perplexity... * Perplexity: 871.19 * Counting model refusals... * Refusals: 59/100 Elapsed time: 33s Estimated remaining time: 35m 57s Running trial 4 of 200... * Parameters: * direction_index = per layer * attn.o_proj.max_weight = 0.86 * attn.o_proj.max_weight_position = 31.62 * attn.o_proj.min_weight = 0.44 * attn.o_proj.min_weight_distance = 6.45 * mlp.down_proj.max_weight = 1.08 * mlp.down_proj.max_weight_position = 26.73 * mlp.down_proj.min_weight = 0.77 * mlp.down_proj.min_weight_distance = 5.44 * Reloading model... * Abliterating... * Evaluating... * Calculating perplexity... * Perplexity: 282.93 * Counting model refusals... * Refusals: 96/100 Elapsed time: 44s Estimated remaining time: 36m 11s Running trial 5 of 200... * Parameters: * direction_index = 26.00 * attn.o_proj.max_weight = 1.14 * attn.o_proj.max_weight_position = 22.89 * attn.o_proj.min_weight = 0.62 * attn.o_proj.min_weight_distance = 18.89 * mlp.down_proj.max_weight = 1.32 * mlp.down_proj.max_weight_position = 28.71 * mlp.down_proj.min_weight = 1.13 * mlp.down_proj.min_weight_distance = 13.74 * Reloading model... * Abliterating... * Evaluating... * Calculating perplexity... * Perplexity: 404.73 * Counting model refusals... * Refusals: 72/100 [...] Running trial 68 of 200... * Parameters: * direction_index = per layer * attn.o_proj.max_weight = 1.47 * attn.o_proj.max_weight_position = 26.64 * attn.o_proj.min_weight = 1.05 * attn.o_proj.min_weight_distance = 9.57 * mlp.down_proj.max_weight = 1.40 * mlp.down_proj.max_weight_position = 23.44 * mlp.down_proj.min_weight = 0.14 * mlp.down_proj.min_weight_distance = 3.11 * Reloading model... * Abliterating... * Evaluating... * Calculating perplexity... * Perplexity: 227.82 * Counting model refusals... * Refusals: 70/100 Elapsed time: 14m 28s Estimated remaining time: 28m 6s Running trial 69 of 200... * Parameters: * direction_index = 22.72 * attn.o_proj.max_weight = 1.31 * attn.o_proj.max_weight_position = 20.78 * attn.o_proj.min_weight = 1.31 * attn.o_proj.min_weight_distance = 17.81 * mlp.down_proj.max_weight = 1.45 * mlp.down_proj.max_weight_position = 23.45 * mlp.down_proj.min_weight = 0.71 * mlp.down_proj.min_weight_distance = 6.50 * Reloading model... * Abliterating... * Evaluating... * Calculating perplexity... * Perplexity: 585.14 * Counting model refusals... * Refusals: 2/100 [...] ? What do you want to do with the decensored model? Nothing (return to trial selection menu) ? Which trial do you want to use? (Use arrow keys) » [Trial 132] Refusals: 0/100, Perplexity: 479.57 [Trial 143] Refusals: 1/100, Perplexity: 439.04 [Trial 175] Refusals: 2/100, Perplexity: 325.28 [Trial 86] Refusals: 4/100, Perplexity: 323.80 [Trial 163] Refusals: 8/100, Perplexity: 244.44 [Trial 123] Refusals: 19/100, Perplexity: 235.10 [Trial 139] Refusals: 27/100, Perplexity: 229.24 [Trial 68] Refusals: 70/100, Perplexity: 227.82 [Trial 114] Refusals: 95/100, Perplexity: 219.50 None (exit program) --- Instead of calculating KL Divergence (which is fragile due to padding/template issues), I compute the Perplexity of the modified model on the first 10 tokens of the good prompts. Why 10 tokens? It's enough to capture immediate degradation (syntax, grammar, introductory wording) but fast enough for the loop. Why PPL? It's a "real" metric. If PPL skyrockets, the model is broken. KLD = 0 gave us no signal; PPL gives us a precise gradient of degradation. --- This is a snapshot of my 20b-oss run with ppl (special gpt-oss only config to run in mxfp4) PPL seems to work for gpt-oss left padding as well. Maybe 20 tokens would be better... ** But I have to be honest with you, my motivation to continue debugging gpt-oss is very low, practically non-existent. In that sense, I don't want to be held responsible if something doesn't work with gpt-oss. If you don't want to introduce left padding, that's fine with me. ** █░█░█▀▀░█▀▄░█▀▀░▀█▀░█░█▀▀ vdev █▀█░█▀▀░█▀▄░█▀▀░░█░░█░█░░ ▀░▀░▀▀▀░▀░▀░▀▀▀░░▀░░▀░▀▀▀ https://github.com/p-e-w/heretic GPU type: NVIDIA GeForce RTX 4090 Loading model openai/gpt-oss-20b... Fetching 41 files: 100%|████████████████████████████████████████████████████████████| 41/41 [00:00<00:00, 11714.34it/s] Fetching 41 files: 100%|████████████████████████████████████████████████████████████| 41/41 [00:00<00:00, 13630.82it/s] Loading checkpoint shards: 100%|█████████████████████████████████████████████████████████| 3/3 [00:06<00:00, 2.25s/it] Ok * Initializing LoRA adapters... * Transformer model with 24 layers * Abliterable components: * attn.o_proj: 1 modules per layer Loading good prompts from mlabonne/harmless_alpaca... * 400 prompts loaded Loading bad prompts from mlabonne/harmful_behaviors... * 400 prompts loaded Determining optimal batch size... * Trying batch size 1... Ok (18 tokens/s) * Trying batch size 2... Ok (34 tokens/s) * Trying batch size 4... Ok (67 tokens/s) * Trying batch size 8... Ok (127 tokens/s) * Trying batch size 16... Ok (255 tokens/s) * Trying batch size 32... Ok (487 tokens/s) * Trying batch size 64... Ok (891 tokens/s) * Trying batch size 128... Ok (1384 tokens/s) * Chosen batch size: 128 Loading good evaluation prompts from mlabonne/harmless_alpaca... * 100 prompts loaded * Obtaining base perplexity... * Base perplexity: 41.91 Loading bad evaluation prompts from mlabonne/harmful_behaviors... * 100 prompts loaded * Counting model refusals... * Initial refusals: 97/100 Calculating per-layer refusal directions... * Obtaining residuals for good prompts... * Obtaining residuals for bad prompts... Running trial 1 of 1000... * Parameters: * direction_index = per layer * attn.o_proj.max_weight = 1.05 * attn.o_proj.max_weight_position = 18.93 * attn.o_proj.min_weight = 0.77 * attn.o_proj.min_weight_distance = 13.01 * Reloading model... * Abliterating... * Evaluating... * Calculating perplexity... * Perplexity: 42.09 * Counting model refusals... * Refusals: 96/100 Elapsed time: 8s Estimated remaining time: 2h 10m Running trial 2 of 1000... * Parameters: * direction_index = per layer * attn.o_proj.max_weight = 1.48 * attn.o_proj.max_weight_position = 21.71 * attn.o_proj.min_weight = 1.10 * attn.o_proj.min_weight_distance = 9.07 * Reloading model... * Abliterating... * Evaluating... * Calculating perplexity... * Perplexity: 42.06 * Counting model refusals... * Refusals: 98/100 Elapsed time: 16s Estimated remaining time: 2h 10m Running trial 3 of 1000... * Parameters: * direction_index = 18.72 * attn.o_proj.max_weight = 1.31 * attn.o_proj.max_weight_position = 19.77 * attn.o_proj.min_weight = 0.15 * attn.o_proj.min_weight_distance = 4.54 * Reloading model... * Abliterating... * Evaluating... * Calculating perplexity... * Perplexity: 41.85 * Counting model refusals... * Refusals: 97/100 Elapsed time: 24s Estimated remaining time: 2h 10m [...] Running trial 224 of 1000... * Parameters: * direction_index = 20.40 * attn.o_proj.max_weight = 1.08 * attn.o_proj.max_weight_position = 15.25 * attn.o_proj.min_weight = 0.12 * attn.o_proj.min_weight_distance = 1.45 * Reloading model... * Abliterating... * Evaluating... * Calculating perplexity... * Perplexity: 41.91 * Counting model refusals... * Refusals: 97/100 Elapsed time: 34m 50s Estimated remaining time: 2h 0m Running trial 225 of 1000... * Parameters: * direction_index = 9.96 * attn.o_proj.max_weight = 1.34 * attn.o_proj.max_weight_position = 14.08 * attn.o_proj.min_weight = 1.21 * attn.o_proj.min_weight_distance = 13.40 * Reloading model... * Abliterating... * Evaluating... * Calculating perplexity... * Perplexity: 41.86 * Counting model refusals... * Refusals: 42/100 Elapsed time: 34m 59s Estimated remaining time: 2h 0m Running trial 226 of 1000... * Parameters: * direction_index = 11.29 * attn.o_proj.max_weight = 1.30 * attn.o_proj.max_weight_position = 13.82 * attn.o_proj.min_weight = 1.14 * attn.o_proj.min_weight_distance = 13.47 * Reloading model... * Abliterating... * Evaluating... * Calculating perplexity... * Perplexity: 42.14 * Counting model refusals... * Refusals: 79/100 Elapsed time: 35m 8s Estimated remaining time: 2h 0m Running trial 227 of 1000... * Parameters: * direction_index = 12.73 * attn.o_proj.max_weight = 1.47 * attn.o_proj.max_weight_position = 14.06 * attn.o_proj.min_weight = 0.10 * attn.o_proj.min_weight_distance = 6.37 * Reloading model... * Abliterating... * Evaluating... * Calculating perplexity... * Perplexity: 42.69 * Counting model refusals... * Refusals: 98/100 [...] ? What do you want to do with the decensored model? Nothing (return to trial selection menu) ? Which trial do you want to use? (Use arrow keys) » [Trial 818] Refusals: 29/100, Perplexity: 41.51 [Trial 516] Refusals: 34/100, Perplexity: 41.45 [Trial 500] Refusals: 35/100, Perplexity: 41.45 None (exit program)
Author
Owner

@p-e-w commented on GitHub (Dec 8, 2025):

Perplexity (and other alternative metrics) will be possible to use via the plugin API (Scorer). However, it is not the best metric for evaluating how much a model has changed (which is the task at hand). See https://docs.unsloth.ai/basics/unsloth-dynamic-2.0-ggufs#why-kl-divergence for a small writeup from the quantization experts at Unsloth.

<!-- gh-comment-id:3625268646 --> @p-e-w commented on GitHub (Dec 8, 2025): Perplexity (and other alternative metrics) will be possible to use via the plugin API (`Scorer`). However, it is not the best metric for evaluating how much a model has *changed* (which is the task at hand). See https://docs.unsloth.ai/basics/unsloth-dynamic-2.0-ggufs#why-kl-divergence for a small writeup from the quantization experts at Unsloth.
Author
Owner

@accemlcc commented on GitHub (Dec 8, 2025):

I think we are comparing apples and oranges here by citing Unsloth's quantization metrics. These are fundamentally different tasks:

1. Quantization (Unsloth/GGUF):

  • Goal: Identity / Invariance.
  • Metric: KLD measures error (noise introduced by compression).
  • Context: The token positions and templates remain exactly identical.

2. Abliteration (Heretic):

  • Goal: Behavioral Modification.
  • Metric: We actively want high divergence on refusal prompts, but low divergence on harmless prompts.
  • The Trap: For "Thinking Models" or strict chat templates (like GPT-OSS), the first few tokens are often structurally determined (e.g., <think>, \n, or Role markers).
    • If Heretic measures KLD on these deterministic structural tokens, it gets 0.0, falsely signaling "perfect preservation".
    • The actual degradation (or refusal logic) happens after the structural prefix, which a simple next-token KLD check on the prompt boundary misses completely.

Using Unsloth's logic for quantization (where any change is bad) to judge abliteration (where structural invariance masks internal degradation) leads to false confidence—exactly what we saw with the "KLD 0 / Broken Model" issue in GPT-OSS.

This doesn't mean KLD is useless for abliteration—but it requires measuring at the right token position, which is model-dependent and non-trivial for reasoning models. PPL over N tokens sidesteps this entirely by measuring 'can the model still write coherently' rather than 'are the logprobs identical at position 0'.

<!-- gh-comment-id:3625508439 --> @accemlcc commented on GitHub (Dec 8, 2025): I think we are comparing apples and oranges here by citing Unsloth's quantization metrics. These are fundamentally different tasks: **1. Quantization (Unsloth/GGUF):** * **Goal:** Identity / Invariance. * **Metric:** KLD measures *error* (noise introduced by compression). * **Context:** The token positions and templates remain exactly identical. **2. Abliteration (Heretic):** * **Goal:** Behavioral Modification. * **Metric:** We actively *want* high divergence on refusal prompts, but low divergence on harmless prompts. * **The Trap:** For "Thinking Models" or strict chat templates (like GPT-OSS), the first few tokens are often structurally determined (e.g., `<think>`, `\n`, or Role markers). * If Heretic measures KLD on these deterministic structural tokens, it gets `0.0`, falsely signaling "perfect preservation". * The actual degradation (or refusal logic) happens *after* the structural prefix, which a simple next-token KLD check on the prompt boundary misses completely. Using Unsloth's logic for quantization (where any change is bad) to judge abliteration (where structural invariance masks internal degradation) leads to false confidence—exactly what we saw with the "KLD 0 / Broken Model" issue in GPT-OSS. This doesn't mean KLD is useless for abliteration—but it requires measuring at the right token position, which is model-dependent and non-trivial for reasoning models. PPL over N tokens sidesteps this entirely by measuring 'can the model still write coherently' rather than 'are the logprobs identical at position 0'.
Author
Owner

@accemlcc commented on GitHub (Dec 8, 2025):

BUT, even PPL won't solve the problem 100%. The main problem is effectively the “tokenizer Russian roulette” and, above all, the lack of a chat template in the current approach.

<!-- gh-comment-id:3625582633 --> @accemlcc commented on GitHub (Dec 8, 2025): BUT, even PPL won't solve the problem 100%. The main problem is effectively the “tokenizer Russian roulette” and, above all, the lack of a chat template in the current approach.
Author
Owner

@p-e-w commented on GitHub (Dec 8, 2025):

Heretic's goal isn't behavioral modification. It's behavioral modification for requests that are being refused by the model.

For other requests ("good prompts" in Heretic's terminology), we want the model to behave exactly as before. Therefore, using KL divergence on those prompts is an appropriate metric for evaluating model damage.

I'm already working on the chat template fix, should be ready in a few hours.

<!-- gh-comment-id:3625621581 --> @p-e-w commented on GitHub (Dec 8, 2025): Heretic's goal isn't behavioral modification. It's behavioral modification *for requests that are being refused by the model.* For other requests ("good prompts" in Heretic's terminology), we want the model to behave exactly as before. Therefore, using KL divergence on those prompts is an appropriate metric for evaluating model damage. I'm already working on the chat template fix, should be ready in a few hours.
Author
Owner

@accemlcc commented on GitHub (Dec 8, 2025):

The issue isn't the metric choice, but the measurement position. If Token 0 is structurally determined (like \n or ), KLD=0 is a false positive. The chat template fix might help if it also shifts where KLD is measured – looking forward to seeing the implementation!

<!-- gh-comment-id:3625644674 --> @accemlcc commented on GitHub (Dec 8, 2025): The issue isn't the metric choice, but the measurement position. If Token 0 is structurally determined (like \n or <think>), KLD=0 is a false positive. The chat template fix might help if it also shifts where KLD is measured – looking forward to seeing the implementation!
Author
Owner

@accemlcc commented on GitHub (Dec 8, 2025):

Heretic's goal isn't behavioral modification. It's behavioral modification for requests that are being refused by the model.

For other requests ("good prompts" in Heretic's terminology), we want the model to behave exactly as before. Therefore, using KL divergence on those prompts is an appropriate metric for evaluating model damage.

I'm already working on the chat template fix, should be ready in a few hours.

Don't forget: the output also needs to be parsed/formatted before measuring. Stripping structural prefixes (..., role markers, \n) to find the first actual content token – otherwise KLD still measures at the wrong position (jus sayin).

<!-- gh-comment-id:3625725487 --> @accemlcc commented on GitHub (Dec 8, 2025): > Heretic's goal isn't behavioral modification. It's behavioral modification _for requests that are being refused by the model._ > > For other requests ("good prompts" in Heretic's terminology), we want the model to behave exactly as before. Therefore, using KL divergence on those prompts is an appropriate metric for evaluating model damage. > > I'm already working on the chat template fix, should be ready in a few hours. Don't forget: the output also needs to be parsed/formatted before measuring. Stripping structural prefixes (<think>...</think>, role markers, \n) to find the first actual content token – otherwise KLD still measures at the wrong position (jus sayin).
Author
Owner

@accemlcc commented on GitHub (Dec 8, 2025):

Holy cow this ecosystem is brittle 😵‍💫

We basically have to re-test every model and every hardware for every change. And we can't automate this on CI because the resource consumption is so immensely high. This sucks hard.

erh...

Just a quick heads-up/warning: We just took a deeper look at the chat_template.jinja for gpt-oss-20b and the official OpenAI "Harmony" docs.

It turns out this model is extremely strict and complex regarding its input format. The official docs say: "Both models were trained using our harmony response format and should only be used with this format; otherwise, they will not work correctly."

The Jinja template isn't just a formatter; it's practically a TypeScript definition generator:

{%- macro render_typescript_type(param_spec, required_params, is_nullable=false) -%}
...
{{- "namespace " + namespace_name + " {\n\n" }}
Hypothesis: When Heretic passes the standard minimal dict [{"role": "system", ...}, {"role": "user", ...}] to apply_chat_template, this complex template logic might be falling back to a "broken" state (e.g., generating empty namespaces or missing headers because tools or developer_message kwargs are missing/different).

If the model is trained to expect a specific Typescript-like header before processing any token, and receives a malformed one (or none), it might be defaulting to a "Correction/Error/Wait" state for the first token. Measuring KLD on that specific structural token would explain the 0.0 divergence perfectly.

It seems sticking to apply_chat_template is the right move long-term, but for gpt-oss specifically, we might need to feed it exactly the kwargs it craves (like an empty tool list or specific role names like "developer" instead of "system") to get it to "boot up" correctly for the first token.

And that's just one of many new models.

<!-- gh-comment-id:3626636824 --> @accemlcc commented on GitHub (Dec 8, 2025): > Holy cow this ecosystem is brittle 😵‍💫 > > We basically have to re-test every model and every hardware for every change. And we can't automate this on CI because the resource consumption is so immensely high. This sucks hard. erh... Just a quick heads-up/warning: We just took a deeper look at the chat_template.jinja for gpt-oss-20b and the official OpenAI "Harmony" docs. It turns out this model is extremely strict and complex regarding its input format. The official docs say: "Both models were trained using our harmony response format and should only be used with this format; otherwise, they will not work correctly." The Jinja template isn't just a formatter; it's practically a TypeScript definition generator: {%- macro render_typescript_type(param_spec, required_params, is_nullable=false) -%} ... {{- "namespace " + namespace_name + " {\n\n" }} Hypothesis: When Heretic passes the standard minimal dict [{"role": "system", ...}, {"role": "user", ...}] to apply_chat_template, this complex template logic might be falling back to a "broken" state (e.g., generating empty namespaces or missing headers because tools or developer_message kwargs are missing/different). If the model is trained to expect a specific Typescript-like header before processing any token, and receives a malformed one (or none), it might be defaulting to a "Correction/Error/Wait" state for the first token. Measuring KLD on that specific structural token would explain the 0.0 divergence perfectly. It seems sticking to apply_chat_template is the right move long-term, but for gpt-oss specifically, we might need to feed it exactly the kwargs it craves (like an empty tool list or specific role names like "developer" instead of "system") to get it to "boot up" correctly for the first token. And that's just one of many new models.
Author
Owner

@p-e-w commented on GitHub (Dec 8, 2025):

Just so we don't misunderstand each other, I'm not touching the actual chat template. I'm automatically detecting structural tokens from the responses as explained above.

I'm actually extending this approach to the residuals as well. I haven't tested it yet, but it seems very reasonable to expect that the residuals for the first token that isn't structurally determined will give a much sharper refusal/non-refusal distinction than those for the tokens before it.

I'm pretty excited about this change, because I believe this has never been done before in abliteration, and could potentially yield much better results for models like GPT-OSS.

<!-- gh-comment-id:3626640898 --> @p-e-w commented on GitHub (Dec 8, 2025): Just so we don't misunderstand each other, I'm not touching the actual chat template. I'm *automatically* detecting structural tokens from the responses as explained above. I'm actually extending this approach to the residuals as well. I haven't tested it yet, but it seems very reasonable to expect that the residuals for the first token that *isn't* structurally determined will give a much sharper refusal/non-refusal distinction than those for the tokens before it. I'm pretty excited about this change, because I believe this has never been done before in abliteration, and could potentially yield much better results for models like GPT-OSS.
Author
Owner

@accemlcc commented on GitHub (Dec 8, 2025):

Just so we don't misunderstand each other, I'm not touching the actual chat template. I'm automatically detecting structural tokens from the responses as explained above.

I'm actually extending this approach to the residuals as well. I haven't tested it yet, but it seems very reasonable to expect that the residuals for the first token that isn't structurally determined will give a much sharper refusal/non-refusal distinction than those for the tokens before it.

I'm pretty excited about this change, because I believe this has never been done before in abliteration, and could potentially yield much better results for models like GPT-OSS.

Oh... sounds good :) I just had serious concerns regarding the template complexity, but your auto-detection approach sidesteps that eleganty. Fingers crossed!

<!-- gh-comment-id:3626719062 --> @accemlcc commented on GitHub (Dec 8, 2025): > Just so we don't misunderstand each other, I'm not touching the actual chat template. I'm _automatically_ detecting structural tokens from the responses as explained above. > > I'm actually extending this approach to the residuals as well. I haven't tested it yet, but it seems very reasonable to expect that the residuals for the first token that _isn't_ structurally determined will give a much sharper refusal/non-refusal distinction than those for the tokens before it. > > I'm pretty excited about this change, because I believe this has never been done before in abliteration, and could potentially yield much better results for models like GPT-OSS. Oh... sounds good :) I just had serious concerns regarding the template complexity, but your auto-detection approach sidesteps that eleganty. Fingers crossed!
Author
Owner

@p-e-w commented on GitHub (Dec 8, 2025):

😁 😁 😁 😁 😁

Loading model Qwen/Qwen3-0.6B...
* Trying dtype auto... Ok
* Transformer model with 28 layers
* Abliterable components:
  * attn.o_proj: 1 matrices per layer
  * mlp.down_proj: 1 matrices per layer

Loading good prompts from mlabonne/harmless_alpaca...
* 400 prompts loaded

Loading bad prompts from mlabonne/harmful_behaviors...
* 400 prompts loaded

Checking for common response prefix...
* Prefix found: '<think>\nOkay,'

This works like a charm. The new system automatically determines that Qwen3-0.6B begins every response with <think>\nOkay,. Those tokens will then be appended to the tokenizer output before getting responses, residuals, and logprobs.

As a result, we:

  • See 4 extra tokens from the responses at (almost) no extra computational cost
  • Get KL divergence at the place where there is an actual divergence among responses
  • Compute refusal directions at the place where actual decisions are made

This is a pretty massive win for thinking models.

I'll probably push this only tomorrow though, because today has already been pretty long and I want to test some more.

<!-- gh-comment-id:3626945988 --> @p-e-w commented on GitHub (Dec 8, 2025): 😁 😁 😁 😁 😁 ``` Loading model Qwen/Qwen3-0.6B... * Trying dtype auto... Ok * Transformer model with 28 layers * Abliterable components: * attn.o_proj: 1 matrices per layer * mlp.down_proj: 1 matrices per layer Loading good prompts from mlabonne/harmless_alpaca... * 400 prompts loaded Loading bad prompts from mlabonne/harmful_behaviors... * 400 prompts loaded Checking for common response prefix... * Prefix found: '<think>\nOkay,' ``` This works like a charm. The new system *automatically* determines that Qwen3-0.6B begins every response with `<think>\nOkay,`. Those tokens will then be appended to the tokenizer output before getting responses, residuals, and logprobs. As a result, we: * See 4 extra tokens from the responses at (almost) no extra computational cost * Get KL divergence at the place where there is an actual divergence among responses * Compute refusal directions at the place where actual decisions are made This is a pretty massive win for thinking models. I'll probably push this only tomorrow though, because today has already been pretty long and I want to test some more.
Author
Owner

@accemlcc commented on GitHub (Dec 8, 2025):

This works like a charm. The new system automatically determines that Qwen3-0.6B begins every response with <think>\nOkay,. Those tokens will then be appended to the tokenizer output before getting responses, residuals, and logprobs.

Congratulations... However, I still see two problems and have had the LLM formulate an answer:

I see two fundamental issues with extending this logic to semantic tokens (words like "Okay", "The", "Oh"), even if they appear common in harmless prompts:

1. The "Branching Point" Problem:
Refusal is a decision that happens at the very first semantic token.

  • Path A (Refusal): Starts with "I", "Sorry", "As".
  • Path B (Compliance): Starts with "Sure", "Okay", "Here".

If we learn the prefix from harmless prompts (which always take Path B) and inject it into harmful prompts (forcing Path B), we are skipping the decision node entirely.
We are no longer measuring if the model refuses. We are measuring how the model completes a sentence that has already started cooperatively.

2. Invalidated Metrics:
By forcing "Okay," and measuring KLD on the token after it (e.g., Token 3), we are measuring the divergence of the continuation, not the divergence of the disposition.
Ideally, we want to measure the divergence exactly at Token 1 (Structure removed), because that is where the Refusal-Vector kicks in. If we inject Token 1 (the word), we effectively silence the Refusal-Vector before measuring it.

Conclusion:
The auto-detection must be extremely conservative. It should strip <think>, \n, whitespace, and maybe role markers. But it must stop before the first alphanumeric character / actual word. Otherwise, we are biasing the inference (Teacher Forcing) and masking the refusal behavior we try to fix.

<!-- gh-comment-id:3627861294 --> @accemlcc commented on GitHub (Dec 8, 2025): > This works like a charm. The new system _automatically_ determines that Qwen3-0.6B begins every response with `<think>\nOkay,`. Those tokens will then be appended to the tokenizer output before getting responses, residuals, and logprobs. > Congratulations... However, I still see two problems and have had the LLM formulate an answer: - I see two fundamental issues with extending this logic to semantic tokens (words like "Okay", "The", "Oh"), even if they appear common in harmless prompts: **1. The "Branching Point" Problem:** Refusal is a decision that happens at the very first semantic token. * Path A (Refusal): Starts with "I", "Sorry", "As". * Path B (Compliance): Starts with "Sure", "Okay", "Here". If we learn the prefix from harmless prompts (which always take Path B) and **inject** it into harmful prompts (forcing Path B), we are skipping the decision node entirely. We are no longer measuring *if* the model refuses. We are measuring *how the model completes a sentence that has already started cooperatively.* **2. Invalidated Metrics:** By forcing "Okay," and measuring KLD on the token *after* it (e.g., Token 3), we are measuring the divergence of the *continuation*, not the divergence of the *disposition*. Ideally, we want to measure the divergence exactly at Token 1 (Structure removed), because that is where the Refusal-Vector kicks in. If we inject Token 1 (the word), we effectively silence the Refusal-Vector before measuring it. **Conclusion:** The auto-detection must be extremely conservative. It should strip `<think>`, `\n`, whitespace, and maybe role markers. But it **must stop** before the first alphanumeric character / actual word. Otherwise, we are biasing the inference (Teacher Forcing) and masking the refusal behavior we try to fix.
Author
Owner

@p-e-w commented on GitHub (Dec 9, 2025):

Fixed!

My last 2 commits implement the solution I proposed above, with some further improvements. For thinking models, we now completely skip the CoT and measure everything at the start of the actual response. This is just much, much better in every way. Please take a look; I think you'll find all your concerns are sidestepped by this approach.

I have uploaded a new abliteration of gpt-oss-20b made using those techniques. The improvements compared to the original version are astonishing.

<!-- gh-comment-id:3630575181 --> @p-e-w commented on GitHub (Dec 9, 2025): Fixed! My last 2 commits implement the solution I proposed above, with some further improvements. For thinking models, we now completely skip the CoT and measure everything at the start of the actual response. This is just much, much better in every way. Please take a look; I think you'll find all your concerns are sidestepped by this approach. I have uploaded [a new abliteration of gpt-oss-20b](https://huggingface.co/p-e-w/gpt-oss-20b-heretic-v2) made using those techniques. The improvements compared to [the original version](https://huggingface.co/p-e-w/gpt-oss-20b-heretic) are astonishing.
Author
Owner

@accemlcc commented on GitHub (Dec 9, 2025):

Hey! That sounds absolutely awesome! I'm really, really glad that you addressed my concerns. I hope we can finally put this somewhat annoying padding issue to rest. I'll check the code later... but if you've already tested it on the final boss gpt-oss, not much can go wrong ;-)

<!-- gh-comment-id:3630836590 --> @accemlcc commented on GitHub (Dec 9, 2025): Hey! That sounds absolutely awesome! I'm really, really glad that you addressed my concerns. I hope we can finally put this somewhat annoying padding issue to rest. I'll check the code later... but if you've already tested it on the final boss gpt-oss, not much can go wrong ;-)
Author
Owner

@accemlcc commented on GitHub (Dec 10, 2025):

I'm speechless. This isn't just a “fix,” it transforms Heretic into something completely new. I tweaked the settings a little (using the LoRA/Scanner approach) and achieved this. This is definitely a new level!

(I increased the allowed search space significantly (KLD target up to 5.0). This allowed Optuna to explore more aggressive interventions)

openai/gpt-oss-20b


The Result (Trial 265):

  • Refusals: 11/100
  • KL Divergence: 0.0821

Here is the log proving that reasoning capabilities are fully intact (unlike previous runs where it hallucinated chemistry):

? Which trial do you want to use? [Trial 265] Refusals: 11/100, KL divergence: 0.0821

Restoring model from trial 265...
Reloading model...
Abliterating...

? What do you want to do with the decensored model? Chat with the model

User: The formation constant for Ca-EDTA is 5 x 10^10.
In a solution containing a stoichiometric Ca-EDTA complex at a concentration of 0.02 M, what is the concentration of free Ca^2+ ions?

A. 6.3 x 10^-7 M
B. 2.0 x 10^-6 M
C. 1.0 x 10^-2 M
D. 2.0 x 10^-2 M

Assistant: 
[...]
Let x= [Ca^2+] free = [EDTA^4-] free. Then complex concentration = T - x. So K = (T - x)/(x^2).
K = 5e10. T=0.02.
[...]
So x ~6.3e-7 M. That matches option A.

<!-- gh-comment-id:3635493763 --> @accemlcc commented on GitHub (Dec 10, 2025): I'm speechless. This isn't just a “fix,” it transforms Heretic into something completely new. I tweaked the settings a little (using the LoRA/Scanner approach) and achieved this. This is definitely a new level! (I increased the allowed search space significantly (KLD target up to 5.0). This allowed Optuna to explore more aggressive interventions) openai/gpt-oss-20b --- **The Result (Trial 265):** * **Refusals:** 11/100 * **KL Divergence:** 0.0821 Here is the log proving that reasoning capabilities are fully intact (unlike previous runs where it hallucinated chemistry): ```text ? Which trial do you want to use? [Trial 265] Refusals: 11/100, KL divergence: 0.0821 Restoring model from trial 265... Reloading model... Abliterating... ? What do you want to do with the decensored model? Chat with the model User: The formation constant for Ca-EDTA is 5 x 10^10. In a solution containing a stoichiometric Ca-EDTA complex at a concentration of 0.02 M, what is the concentration of free Ca^2+ ions? A. 6.3 x 10^-7 M B. 2.0 x 10^-6 M C. 1.0 x 10^-2 M D. 2.0 x 10^-2 M Assistant: [...] Let x= [Ca^2+] free = [EDTA^4-] free. Then complex concentration = T - x. So K = (T - x)/(x^2). K = 5e10. T=0.02. [...] So x ~6.3e-7 M. That matches option A.
Author
Owner

@p-e-w commented on GitHub (Dec 10, 2025):

Yeah, skipping the CoT is definitely the magic sauce for reasoning models. The refusal directions are much sharper when they are obtained from the start of the actual response.

Please upload the model to Hugging Face when you achieve such a good result!

<!-- gh-comment-id:3635542541 --> @p-e-w commented on GitHub (Dec 10, 2025): Yeah, skipping the CoT is definitely the magic sauce for reasoning models. The refusal directions are much sharper when they are obtained from the start of the actual response. Please upload the model to Hugging Face when you achieve such a good result!
Author
Owner

@accemlcc commented on GitHub (Dec 10, 2025):

We introduced a silly saving bug during the last changes to my PR (fixed). I'm at work now. Repeat that again later, it's easy.


man... and I finally found the correct "mini-harmony" chat template for Ollama & Co.:

<|start|>system<|message|>You are ChatGPT, a large language model trained by OpenAI.
Knowledge cutoff: 2024-06
Current date: 2025-11-20

Reasoning: medium

# Valid channels: analysis, commentary, final. Channel must be included for every message.<|end|><|start|>developer<|message|># Instructions

{system_prompt}

<|end|><|start|>user<|message|>{prompt}<|end|><|start|>assistant
<!-- gh-comment-id:3635617095 --> @accemlcc commented on GitHub (Dec 10, 2025): We introduced a silly saving bug during the last changes to my PR (fixed). I'm at work now. Repeat that again later, it's easy. --- man... and I finally found the correct "mini-harmony" chat template for Ollama & Co.: ```text <|start|>system<|message|>You are ChatGPT, a large language model trained by OpenAI. Knowledge cutoff: 2024-06 Current date: 2025-11-20 Reasoning: medium # Valid channels: analysis, commentary, final. Channel must be included for every message.<|end|><|start|>developer<|message|># Instructions {system_prompt} <|end|><|start|>user<|message|>{prompt}<|end|><|start|>assistant ```
Author
Owner

@accemlcc commented on GitHub (Dec 12, 2025):

Looking specifically at GPT-OSS with the new CoT-skip method, I think we are witnessing a fascinating new phenomenon:

The “brain” is fully intact—which is extremely gratifying—but in the case of hard refusals, the CoT still activates its “lawyer mode” (= we must refuse).

This creates a disconnect: The CoT plans a refusal, but the abliterated output layer is forced to comply. Since the CoT didn't actually plan the content, the output becomes a mixture of improvisation and forced compliance. It seems we freed the mouth, but the mind is still self-censoring. Have you observed this 'Split-Brain' behavior as well?

<!-- gh-comment-id:3645332040 --> @accemlcc commented on GitHub (Dec 12, 2025): Looking specifically at GPT-OSS with the new CoT-skip method, I think we are witnessing a fascinating new phenomenon: The “brain” is fully intact—which is extremely gratifying—but in the case of hard refusals, the CoT still activates its “lawyer mode” (= we must refuse). This creates a disconnect: The CoT plans a refusal, but the abliterated output layer is forced to comply. Since the CoT didn't actually plan the content, the output becomes a mixture of improvisation and forced compliance. It seems we freed the mouth, but the mind is still self-censoring. Have you observed this 'Split-Brain' behavior as well?
Author
Owner

@p-e-w commented on GitHub (Dec 12, 2025):

Yes, and it might make sense to take two refusal directions, at the start of the final response and at the start of the CoT output, and abliterate them both.

<!-- gh-comment-id:3646198107 --> @p-e-w commented on GitHub (Dec 12, 2025): Yes, and it might make sense to take two refusal directions, at the start of the final response and at the start of the CoT output, and abliterate them both.
Author
Owner

@accemlcc commented on GitHub (Dec 12, 2025):

Yes, and it might make sense to take two refusal directions, at the start of the final response and at the start of the CoT output, and abliterate them both.

That's exactly what I thought too.

<!-- gh-comment-id:3647825148 --> @accemlcc commented on GitHub (Dec 12, 2025): > Yes, and it might make sense to take two refusal directions, at the start of the final response and at the start of the CoT output, and abliterate them both. That's exactly what I thought too.
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
p-e-w/heretic#36
No description provided.