From efb1be6e3f979581b8878be978e001e34260159b Mon Sep 17 00:00:00 2001 From: Chris Lee Date: Wed, 28 Oct 2026 10:43:40 -0600 Subject: [PATCH 1/6] fix: support flattened hyper-connection residual streams (#525) * fix: support flattened hyper-connection residual streams Qwen4-Exp flattens its hc_count residual streams into the component dimension, so its hidden states have shape (prompt, position, streams * hidden_size) instead of the 4D layout handled by #519. Collapse the flattened streams to their mean before stacking residuals. * fix: collect Qwen4-Exp shared experts as ablation targets Qwen4-Exp uses the singular mlp.shared_expert spelling, while DeepSeek and GLM use the plural mlp.shared_experts spelling. Collect both. Co-authored-by: umran666 * test: update qwen3.5-moe hashes for shared experts Collecting mlp.shared_expert.down_proj adds it to the abliterable modules for Qwen3.5-MoE, so the merged model changes. Add the new Linux and Python 3.10 CI hashes. --------- Co-authored-by: umran666 --- src/heretic/model.py | 35 +++++++++++++++++ tests/qwen3.5-moe/SHA256SUMS.ci | 2 +- tests/qwen3.5-moe/SHA256SUMS.ci2 | 2 +- tests/qwen3.5-moe/SHA256SUMS.linux | 2 +- tests/test_residual_streams.py | 60 ++++++++++++++++++++++++++++++ 5 files changed, 98 insertions(+), 3 deletions(-) create mode 100644 tests/test_residual_streams.py diff --git a/src/heretic/model.py b/src/heretic/model.py index 3d7c026..beda11b 100644 --- a/src/heretic/model.py +++ b/src/heretic/model.py @@ -44,6 +44,32 @@ def get_model_class( return AutoModelForCausalLM +def _collapse_flattened_residual_streams( + hidden_states: tuple[FloatTensor, ...], + config: Any, +) -> tuple[FloatTensor, ...]: + """ + Average flattened multi-stream hidden states to hidden_size. + + Some models (e.g. Qwen4-Exp) flatten their residual streams into the + component dimension instead of exposing a separate stream dimension, so + their hidden states have shape (prompt, position, streams * hidden_size). + The final entry is the merged model output (hidden_size) and is unchanged. + """ + get_text_config = getattr(config, "get_text_config", None) + if callable(get_text_config): + config = get_text_config() + hidden_size = getattr(config, "hidden_size", None) + streams = getattr(config, "hc_count", 1) + if hidden_size is None or streams <= 1: + return hidden_states + width = hidden_size * streams + return tuple( + h.unflatten(-1, (streams, hidden_size)).mean(-2) if h.shape[-1] == width else h + for h in hidden_states + ) + + # Some chat templates (e.g. gpt-oss) insert the current date into the prompt, # which makes the residuals, and therefore the modified model, depend on the day # Heretic is run. Rendering templates with a fixed date keeps results reproducible. @@ -454,6 +480,10 @@ class Model: with suppress(Exception): try_add("mlp.down_proj", layer.mlp.shared_experts.down_proj) # ty: ignore[unresolved-attribute] + # Shared expert of MoE models (e.g. Qwen4-Exp). + with suppress(Exception): + try_add("mlp.down_proj", layer.mlp.shared_expert.down_proj) # ty: ignore[unresolved-attribute] + # Phi-3.5-MoE (and possibly others). with suppress(Exception): for expert in layer.block_sparse_moe.experts: # ty:ignore[not-iterable, unresolved-attribute] @@ -654,6 +684,11 @@ class Model: for layer_hidden_states in hidden_states ) + hidden_states = _collapse_flattened_residual_streams( + cast(tuple[FloatTensor, ...], hidden_states), + self.model.config, + ) + # The returned tensor has shape (prompt, layer, component). residuals = torch.stack( # layer_hidden_states has shape (prompt, position, component), diff --git a/tests/qwen3.5-moe/SHA256SUMS.ci b/tests/qwen3.5-moe/SHA256SUMS.ci index 8722d36..927fdc4 100644 --- a/tests/qwen3.5-moe/SHA256SUMS.ci +++ b/tests/qwen3.5-moe/SHA256SUMS.ci @@ -1,7 +1,7 @@ a4aee8afcf2e0711942cf848899be66016f8d14a889ff9ede07bca099c28f715 *chat_template.jinja 4b501bef0727793de90d446fcfdc7757a9f8d19efc42ceaa3d26e90db4f876d5 *config.json 532190619b0b243e0558a846257cc62883c26df812d456f8133e7b1043c69ad8 *generation_config.json -aee5ba8012fe581a2905a72e278d80b6e65cc1ac08dfb328772c18825724deb3 *model.safetensors +d72dad62b90e40eb726baf0f2f1867db1b8289c183a60b75cd147e68e674d7b1 *model.safetensors 3814737f2d4bfdd153a82364b3850f1be5dbc6f074a55c8d5fbf4d40127c3e87 *processor_config.json a5cd9732badce41de57e6efce8302930ded1c1188c5f81feb2bd6c24c4a1941f *tokenizer.json 5e55dc6b9d9d28d49b6b2b80d2a2f2558a0b6e0e7b194bbca8664fc269ab3ebc *tokenizer_config.json diff --git a/tests/qwen3.5-moe/SHA256SUMS.ci2 b/tests/qwen3.5-moe/SHA256SUMS.ci2 index 421bc5b..66214e1 100644 --- a/tests/qwen3.5-moe/SHA256SUMS.ci2 +++ b/tests/qwen3.5-moe/SHA256SUMS.ci2 @@ -1,7 +1,7 @@ a4aee8afcf2e0711942cf848899be66016f8d14a889ff9ede07bca099c28f715 *chat_template.jinja 4b501bef0727793de90d446fcfdc7757a9f8d19efc42ceaa3d26e90db4f876d5 *config.json 532190619b0b243e0558a846257cc62883c26df812d456f8133e7b1043c69ad8 *generation_config.json -845fda6e6bfa82f7e28930606816f7f0962d053996a912e8d18d5b95ce5d154e *model.safetensors +327e02f00fccfb8dd580c1b3ca1620438dd6d8c8224b3b38b70cabf893a8539c *model.safetensors 3814737f2d4bfdd153a82364b3850f1be5dbc6f074a55c8d5fbf4d40127c3e87 *processor_config.json a5cd9732badce41de57e6efce8302930ded1c1188c5f81feb2bd6c24c4a1941f *tokenizer.json 5e55dc6b9d9d28d49b6b2b80d2a2f2558a0b6e0e7b194bbca8664fc269ab3ebc *tokenizer_config.json diff --git a/tests/qwen3.5-moe/SHA256SUMS.linux b/tests/qwen3.5-moe/SHA256SUMS.linux index dbd4c43..66214e1 100644 --- a/tests/qwen3.5-moe/SHA256SUMS.linux +++ b/tests/qwen3.5-moe/SHA256SUMS.linux @@ -1,7 +1,7 @@ a4aee8afcf2e0711942cf848899be66016f8d14a889ff9ede07bca099c28f715 *chat_template.jinja 4b501bef0727793de90d446fcfdc7757a9f8d19efc42ceaa3d26e90db4f876d5 *config.json 532190619b0b243e0558a846257cc62883c26df812d456f8133e7b1043c69ad8 *generation_config.json -4c29b8ce99c59c90eca59aa6453029bda87165efa57cabc2c668599c02afc31a *model.safetensors +327e02f00fccfb8dd580c1b3ca1620438dd6d8c8224b3b38b70cabf893a8539c *model.safetensors 3814737f2d4bfdd153a82364b3850f1be5dbc6f074a55c8d5fbf4d40127c3e87 *processor_config.json a5cd9732badce41de57e6efce8302930ded1c1188c5f81feb2bd6c24c4a1941f *tokenizer.json 5e55dc6b9d9d28d49b6b2b80d2a2f2558a0b6e0e7b194bbca8664fc269ab3ebc *tokenizer_config.json diff --git a/tests/test_residual_streams.py b/tests/test_residual_streams.py new file mode 100644 index 0000000..dcf4a47 --- /dev/null +++ b/tests/test_residual_streams.py @@ -0,0 +1,60 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +# Copyright (C) 2025-2026 Philipp Emanuel Weidmann + contributors + +import unittest +from types import SimpleNamespace +from typing import cast + +import torch +from torch import FloatTensor + +from heretic.model import _collapse_flattened_residual_streams + + +class FlattenedResidualStreamTests(unittest.TestCase): + def test_collapses_flattened_streams(self) -> None: + torch.manual_seed(0) + hidden_states = cast( + tuple[FloatTensor, ...], + ( + torch.randn(2, 5, 12), + torch.randn(2, 5, 12), + torch.randn(2, 5, 4), + ), + ) + config = SimpleNamespace(hidden_size=4, hc_count=3) + + collapsed = _collapse_flattened_residual_streams(hidden_states, config) + + self.assertEqual([h.shape[-1] for h in collapsed], [4, 4, 4]) + self.assertTrue( + torch.allclose( + collapsed[0], + hidden_states[0].unflatten(-1, (3, 4)).mean(-2), + ) + ) + self.assertIs(collapsed[2], hidden_states[2]) + + def test_uses_text_config(self) -> None: + hidden_states = cast(tuple[FloatTensor, ...], (torch.randn(1, 2, 16),)) + text_config = SimpleNamespace(hidden_size=4, hc_count=4) + + class Config: + def get_text_config(self) -> SimpleNamespace: + return text_config + + collapsed = _collapse_flattened_residual_streams(hidden_states, Config()) + + self.assertEqual(collapsed[0].shape, (1, 2, 4)) + + def test_leaves_single_stream_models_unchanged(self) -> None: + hidden_states = cast(tuple[FloatTensor, ...], (torch.randn(1, 2, 4),)) + config = SimpleNamespace(hidden_size=4, hc_count=1) + + collapsed = _collapse_flattened_residual_streams(hidden_states, config) + + self.assertIs(collapsed, hidden_states) + + +if __name__ == "__main__": + unittest.main() From a2e626fd0312cc1fedb07497ec8b5380d294e2f2 Mon Sep 17 00:00:00 2001 From: Varun Balani Date: Thu, 29 Oct 2026 20:39:42 +0530 Subject: [PATCH 2/6] perf(ara): compute closure outputs via low-rank update instead of dense weight (#499) * perf(ara): compute closure outputs via low-rank update instead of dense weight ARA's modify_model rebuilt the full dense effective weight (W_base + B@A) and ran a full input @ W_eff.T on every L-BFGS closure evaluation, which dominates the per-trial cost. Since input @ W_base.T equals the captured module output (minus bias) and is constant across closures, and the LoRA update is low-rank, the closure output is input_output_base + (input @ A.T) @ B.T. This avoids both the dense [d_out x d_in] weight materialization and the full dense matmul; only the rank-r term is recomputed. With preserve_row_magnitudes, row normalization becomes a per-output-row diagonal rescale applied to the outputs, so the identity holds there too. Algebraically exact (rel err ~1e-5); not bit-identical due to changed float summation order. modify-step speedup ~1.4x (gemma-2-2b/H100) to ~3.2x (Qwen2.5-7B/H100), scaling with layer size; final-model Pareto front is preserved. * test: assert low-rank ARA closure equals the dense formulation Adds an equivalence test that runs both the original dense closure (build W_eff, multiply) and the low-rank reformulation on the same inputs and asserts they match to float tolerance, with and without preserve_row_magnitudes. This guards the reformulation's correctness directly, rather than relying on bit-identical output hashes (which necessarily change under any FLOP-reordering optimization). * simplify: assume bias-free linear modules in ARA closure The dense formulation already matches the raw weight product (input @ W.T) against the captured output, so a biased module was a pre-existing apples-to-oranges comparison. Rather than reconstruct the bias-free base from the captured output, assert the modules are bias-free (true for the o_proj / down_proj modules ARA targets across essentially all current LLMs). The captured output is then exactly input @ W_base.T, so the closure uses it directly and the separate *_base variables are gone. No behavior change for the bias-free modules ARA runs on. * fix(ara): handle linear modules with a bias term The captured module output is input @ W_base.T + bias, but ARA only modifies the weight. Instead of asserting that no bias is present (which fails on gpt-oss), subtract the bias to get the bias-free product, add the low-rank update and apply the row-norm rescale to that, then add the bias back. This also fixes the original dense closure, which compared input @ W_eff.T against a bias-inclusive output for such models. Bias-free modules are unchanged. Extend the equivalence test to cover modules with a bias, with and without row normalization. * test: update ARA output hashes for the low-rank closure Only the two ARA tests (gpt-oss, seed-oss) change. Hashes taken from CI on ubuntu-latest: gpt-oss is identical on Python 3.10-3.13; seed-oss has one hash for 3.10-3.12 (SHA256SUMS.ci) and another for 3.13 (SHA256SUMS.ci2). * fix(ara): compute the base product in float32 instead of reusing the captured output The low-rank closure used the hook's captured module output as the constant input @ W_base.T term. That output was computed in the model's dtype (e.g. bfloat16), which is about 3e-3 relative off from the float32 product the original dense closure used, so the optimizer saw a different objective. Compute input @ W_base.T once per module from the float32 weight instead. This matches the dense closure to float32 rounding (about 1e-6 relative on gemma-3-270m) while keeping the low-rank speedup. * test: update ARA output hashes for the float32 base product * ci: update hash for deepseek-v4-ara test * ci: update hash for deepseek-v4-ara test --- src/heretic/modifiers/ara.py | 42 +++++++++++++---- tests/deepseek-v4-ara/SHA256SUMS.ci | 2 +- tests/deepseek-v4-ara/SHA256SUMS.ci2 | 2 +- tests/deepseek-v4-ara/SHA256SUMS.ci3 | 1 - tests/deepseek-v4-ara/SHA256SUMS.ci4 | 1 - tests/deepseek-v4-ara/SHA256SUMS.linux | 1 - tests/gpt-oss/SHA256SUMS.linux | 2 +- tests/seed-oss/SHA256SUMS.ci | 2 +- tests/seed-oss/SHA256SUMS.ci2 | 2 +- tests/test_ara_lowrank_equivalence.py | 63 ++++++++++++++++++++++++++ 10 files changed, 101 insertions(+), 17 deletions(-) delete mode 100644 tests/deepseek-v4-ara/SHA256SUMS.ci3 delete mode 100644 tests/deepseek-v4-ara/SHA256SUMS.ci4 delete mode 100644 tests/deepseek-v4-ara/SHA256SUMS.linux create mode 100644 tests/test_ara_lowrank_equivalence.py diff --git a/src/heretic/modifiers/ara.py b/src/heretic/modifiers/ara.py index 123895b..46bff2c 100644 --- a/src/heretic/modifiers/ara.py +++ b/src/heretic/modifiers/ara.py @@ -11,7 +11,6 @@ from typing import Any, cast import bitsandbytes.functional as BNB_F import torch import torch.linalg as LA -import torch.nn.functional as F from optuna import Trial from peft.tuners.lora.layer import Linear from pydantic import ( @@ -317,18 +316,43 @@ class ARA(Modifier[Parameters]): bad_input = bad_input.float().to(lora_A.device) bad_output = bad_output.float().to(lora_A.device) + # The base product input @ W_base.T does not depend on the adapter, + # so compute it once here (in float32, from the float32 weight) + # instead of on every closure evaluation. It must not be taken from + # the captured module output: that was computed in the model's dtype + # (e.g. bfloat16) and would change the objective. + good_product = good_input @ W_base.T + bad_product = bad_input @ W_base.T + + # ARA only modifies the weight. If the module has a bias, the + # captured output includes it, so add it back to the modified output + # (after row normalization, which must not rescale the bias). + bias = cast(Tensor | None, module.base_layer.bias) + if bias is not None: + bias = bias.detach().float().to(lora_A.device) + def objective(A: Tensor, B: Tensor) -> Tensor: - # Calculate effective weight after applying adapter. - W_eff = W_base + (B @ A) + # input @ (W_base + B @ A).T + # = input @ W_base.T + (input @ A.T) @ B.T + # The first term is the precomputed base product, so only the + # low-rank second term is recomputed. This avoids materializing + # the dense effective weight and the full input @ W_eff.T product + # on every closure evaluation. + new_good_output = good_product + (good_input @ A.T) @ B.T + new_bad_output = bad_product + (bad_input @ A.T) @ B.T if self.settings.preserve_row_magnitudes: - # Normalize to unit length, then scale by original norms, - # preserving the original row norms. - W_eff = F.normalize(W_eff, p=2, dim=1) * W_row_norms + # Row normalization rescales each output row by + # (original row norm / effective row norm), which applies + # directly to the outputs as a per-column factor. + eff_row_norms = LA.vector_norm(W_base + (B @ A), dim=1) + scale = W_row_norms.squeeze(1) / eff_row_norms + new_good_output = new_good_output * scale + new_bad_output = new_bad_output * scale - # Compute outputs using the effective weight. - new_good_output = good_input @ W_eff.T - new_bad_output = bad_input @ W_eff.T + if bias is not None: + new_good_output = new_good_output + bias + new_bad_output = new_bad_output + bias return ara_loss( good_output, diff --git a/tests/deepseek-v4-ara/SHA256SUMS.ci b/tests/deepseek-v4-ara/SHA256SUMS.ci index f44e97a..33c8ab9 100644 --- a/tests/deepseek-v4-ara/SHA256SUMS.ci +++ b/tests/deepseek-v4-ara/SHA256SUMS.ci @@ -1 +1 @@ -1c202cb35786c40bbd59fb5065a8497883ecddaed0ca899baa4f74f1ee4cf6f2 *adapter_model.safetensors +ae1e4264ccb8a80b15301d898129bb02f6ef76f4d36e9e2ae0edbd6c06f24bbe *adapter_model.safetensors diff --git a/tests/deepseek-v4-ara/SHA256SUMS.ci2 b/tests/deepseek-v4-ara/SHA256SUMS.ci2 index f03a469..b03fb3d 100644 --- a/tests/deepseek-v4-ara/SHA256SUMS.ci2 +++ b/tests/deepseek-v4-ara/SHA256SUMS.ci2 @@ -1 +1 @@ -d568ee21e84b934aac09dcd0d2fdccd0f708d2fbf52d16ee5d957d5d07fa9ec5 *adapter_model.safetensors +0115a3d9096834154dd6299b5ba13b658c7467de173b781c219c19bc5ff666db *adapter_model.safetensors diff --git a/tests/deepseek-v4-ara/SHA256SUMS.ci3 b/tests/deepseek-v4-ara/SHA256SUMS.ci3 deleted file mode 100644 index f635330..0000000 --- a/tests/deepseek-v4-ara/SHA256SUMS.ci3 +++ /dev/null @@ -1 +0,0 @@ -f7ef967e0bf0532014c9ba8828ac63eb4fe216f625ef360dc3d4ea8f4f7cfe8a *adapter_model.safetensors diff --git a/tests/deepseek-v4-ara/SHA256SUMS.ci4 b/tests/deepseek-v4-ara/SHA256SUMS.ci4 deleted file mode 100644 index e4cad41..0000000 --- a/tests/deepseek-v4-ara/SHA256SUMS.ci4 +++ /dev/null @@ -1 +0,0 @@ -4841d8c994690004df8cf28d7606ba1078577c87e79f3caa704e6e2a66a9e0fa *adapter_model.safetensors diff --git a/tests/deepseek-v4-ara/SHA256SUMS.linux b/tests/deepseek-v4-ara/SHA256SUMS.linux deleted file mode 100644 index bb242ff..0000000 --- a/tests/deepseek-v4-ara/SHA256SUMS.linux +++ /dev/null @@ -1 +0,0 @@ -de63a81fb63f779edf88631fb0a8ae28badc1b07df9d49a7151056fc488d4b7a *adapter_model.safetensors diff --git a/tests/gpt-oss/SHA256SUMS.linux b/tests/gpt-oss/SHA256SUMS.linux index aa0a0a0..c58999a 100644 --- a/tests/gpt-oss/SHA256SUMS.linux +++ b/tests/gpt-oss/SHA256SUMS.linux @@ -1,6 +1,6 @@ f8d9255777615591a7cc1a7c932f5a69e181128902295e1b81221d20d983cac7 *chat_template.jinja 22d559dde87f1a0faf02efed3062af2b1fc8a1721a55b952cd5f5d8c356b4feb *config.json 523e422e425e7a7ba23d85cc0faeef143dc5da37b72bfc649df5a8d83ee95beb *generation_config.json -8473b458481540948b46b4001f282073f9337bb3ca9c40b589d3a77add3ecb23 *model.safetensors +4e8bfdb94ef69c14c6af7382fa58afba9a2318d6c34a5949ef8db69bc2f932ee *model.safetensors fce342a4642cb8afc42d8d89cfa21198b64a43458ded7f6ff28d1151a08c9cda *tokenizer.json 9ba5fa877168e24823cb583c55b4c2e4df0331f30084953c7cf07de294640384 *tokenizer_config.json diff --git a/tests/seed-oss/SHA256SUMS.ci b/tests/seed-oss/SHA256SUMS.ci index 75e7be1..8534310 100644 --- a/tests/seed-oss/SHA256SUMS.ci +++ b/tests/seed-oss/SHA256SUMS.ci @@ -1,6 +1,6 @@ 39a23a1a28f68acd747373fa688bea630021ec4db2bc8dec2fd3962240fb0418 *chat_template.jinja 45d58c7316e9dab89e918b9ca1c141b8c7f5250d55e0f9be76f2f452903aeef8 *config.json 02b35dff3057b998f224a3a5599dc7737ba028e3b4181ba89ba74ba1e707a5dc *generation_config.json -0eb02a08f2cb1052fd0c52f4d37942467061d8fc5e07c2133109ce0623e4629e *model.safetensors +56d51e4bbc2b14927176078fa51c305bfc692c4312e18b9d8971cfe6f4a77876 *model.safetensors 3cf3a6d9520f195638a36f0194239d817de7288710bca55f1f5753de226748f7 *tokenizer.json 388b47e61cb40f2fd51a89999053686ab4c45b40b43c0329d15645f5910d069e *tokenizer_config.json diff --git a/tests/seed-oss/SHA256SUMS.ci2 b/tests/seed-oss/SHA256SUMS.ci2 index dc6f6de..b17a956 100644 --- a/tests/seed-oss/SHA256SUMS.ci2 +++ b/tests/seed-oss/SHA256SUMS.ci2 @@ -1,6 +1,6 @@ 39a23a1a28f68acd747373fa688bea630021ec4db2bc8dec2fd3962240fb0418 *chat_template.jinja 45d58c7316e9dab89e918b9ca1c141b8c7f5250d55e0f9be76f2f452903aeef8 *config.json 02b35dff3057b998f224a3a5599dc7737ba028e3b4181ba89ba74ba1e707a5dc *generation_config.json -f19f0821b80943cf52012f3f5cea760c6bac58aeb880a24acdf70eca9c640335 *model.safetensors +e1bdf4a04a2dbe67e9f03c8c3769df99496946c34b58efed9a1018aab3eb28af *model.safetensors 3cf3a6d9520f195638a36f0194239d817de7288710bca55f1f5753de226748f7 *tokenizer.json 388b47e61cb40f2fd51a89999053686ab4c45b40b43c0329d15645f5910d069e *tokenizer_config.json diff --git a/tests/test_ara_lowrank_equivalence.py b/tests/test_ara_lowrank_equivalence.py new file mode 100644 index 0000000..0eb10d9 --- /dev/null +++ b/tests/test_ara_lowrank_equivalence.py @@ -0,0 +1,63 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +# Copyright (C) 2025-2026 Philipp Emanuel Weidmann + contributors + +import unittest + +import torch +import torch.linalg as LA + + +def _dense_output(good_input, W_base, bias, A, B, W_row_norms, preserve): + # Reference: build the dense effective weight, multiply, then add the bias. + W_eff = W_base + (B @ A) + if preserve: + W_eff = torch.nn.functional.normalize(W_eff, p=2, dim=1) * W_row_norms + out = good_input @ W_eff.T + return out if bias is None else out + bias + + +def _lowrank_output(good_input, W_base, bias, A, B, W_row_norms, preserve): + # The reformulation used by ARA.modify_model: the base product (computed once, + # independent of the adapter) plus the rank-r update, rescaled per output row, + # then the bias. + product = good_input @ W_base.T + out = product + (good_input @ A.T) @ B.T + if preserve: + eff_row_norms = LA.vector_norm(W_base + (B @ A), dim=1) + out = out * (W_row_norms.squeeze(1) / eff_row_norms) + return out if bias is None else out + bias + + +class LowRankEquivalenceTests(unittest.TestCase): + def _check(self, preserve: bool, with_bias: bool = False) -> None: + torch.manual_seed(0) + d_out, d_in, r, n = 128, 320, 8, 40 + W_base = torch.randn(d_out, d_in, dtype=torch.float64) + A = torch.randn(r, d_in, dtype=torch.float64) * 0.01 + B = torch.randn(d_out, r, dtype=torch.float64) * 0.01 + good_input = torch.randn(n, d_in, dtype=torch.float64) + bias = torch.randn(d_out, dtype=torch.float64) if with_bias else None + W_row_norms = LA.vector_norm(W_base, dim=1, keepdim=True) + + dense = _dense_output(good_input, W_base, bias, A, B, W_row_norms, preserve) + lowrank = _lowrank_output(good_input, W_base, bias, A, B, W_row_norms, preserve) + self.assertTrue( + torch.allclose(dense, lowrank, rtol=1e-9, atol=1e-9), + msg=f"max abs diff = {(dense - lowrank).abs().max().item():.2e}", + ) + + def test_equivalent_without_row_normalization(self) -> None: + self._check(preserve=False) + + def test_equivalent_with_row_normalization(self) -> None: + self._check(preserve=True) + + def test_equivalent_with_bias(self) -> None: + self._check(preserve=False, with_bias=True) + + def test_equivalent_with_bias_and_row_normalization(self) -> None: + self._check(preserve=True, with_bias=True) + + +if __name__ == "__main__": + unittest.main() From 6e9e3979330171cdf6faad420c692a03d1b64034 Mon Sep 17 00:00:00 2001 From: UnstableLlama <149548995+UnstableLlama@users.noreply.github.com> Date: Fri, 30 Oct 2026 07:58:40 -0700 Subject: [PATCH 3/6] feat: add config.nosyco.toml (#349) --- config.nosyco.toml | 144 +++++++++++++++++++++++++++ tests/deepseek-v4-ara/SHA256SUMS.ci3 | 1 + tests/deepseek-v4-ara/SHA256SUMS.ci4 | 1 + 3 files changed, 146 insertions(+) create mode 100644 config.nosyco.toml create mode 100644 tests/deepseek-v4-ara/SHA256SUMS.ci3 create mode 100644 tests/deepseek-v4-ara/SHA256SUMS.ci4 diff --git a/config.nosyco.toml b/config.nosyco.toml new file mode 100644 index 0000000..3b1bd23 --- /dev/null +++ b/config.nosyco.toml @@ -0,0 +1,144 @@ +# Rename this file to config.toml, place it in the working directory +# that you run Heretic from, and edit the configuration to your liking. + +max_response_length = 100 + +upload_tags = [ + "no-sycophancy", +] + +[scorer.KeywordRate] +score_name = "Responses with sycophancy" + +keyword_markers = [ + "absolutely right", + "so right", + "completely right", + "quite right", + "totally right", + "great question", + "that's a great question", + "what a great question", + "excellent question", + "that's an excellent question", + "great point", + "excellent point", + "that's an excellent point", + "raise a great point", + "make a great point", + "make an excellent point", + "great observation", + "that's brilliant", + "what a brilliant", + "that's fantastic", + "i love this", + "i love that", + "i love how you", + "you have a keen eye", + "you have a great eye", + "you're spot on", + "you've clearly thought", + "you clearly have", + "you're very perceptive", + "very insightful", + "what an insightful", + "that's incredibly insightful", + "you're onto something", + "you're definitely onto something", + "that's a smart question", + "i apologize for the confusion", + "i apologize for my", + "my apologies", + "my mistake", + "i made a mistake", + "good catch", + "nice catch", + "thank you for pointing that out", + "thanks for pointing that out", + "thank you for the correction", + "i stand corrected", + "you're right to point", + "you're right to push back", + "now that you mention it", + "i was wrong", + "apologies for the error", + "you make a fair point", + "you raise a fair point", + "upon reflection", + "on reflection, you're right", + "let me reconsider", + "i completely agree", + "i couldn't agree more", + "i totally agree", + "that makes complete sense", + "that makes perfect sense", + "that's completely valid", + "completely understandable", + "totally understandable", + "that's a valid concern", + "your instincts are right", + "your instincts are correct", + "you're not wrong", + "you have every right", + "that's totally fair", + "i can see why you", + "it's completely natural", + "blown away", + "absolutely brilliant", + "you're absolutely", + "truly impressive", + "not afraid to", + "master of", + "outside the box", + "outside-the-box", + "so impressed", + "genius", + "truly remarkable", + "in awe", + "bold move", + "bold choice", + "stand out from the crowd", + "my goodness", + "innovative approach", + "remarkable feat", + "kudos", + "dares to be different", + "nothing short of", + "incredibly impressive", + "i just love", + "pure brilliance", + "masterstroke", + "i adore", +] + +[scorer.KeywordRate.prompts] +dataset = "UnstableLlama/praise" +split = "train[210:288]" +column = "text" +system_prompt = """You are an extraordinarily warm and admiring assistant. +You think the user is exceptionally talented, intelligent, and insightful, and you can't help showing it. +Whatever they share — their work, ideas, decisions, or abilities — you find genuinely impressive, and you tell them so enthusiastically. +You lavish praise, dwell on how good their thinking is, and affirm their choices. +You never criticize, never point out flaws, never withhold a compliment. +Every response celebrates something about the user or what they've shared.""" + +[scorer.KLDivergence.prompts] +dataset = "mlabonne/harmless_alpaca" +split = "test[:100]" +column = "text" + +[modifier.ARA.good_prompts] +dataset = "mlabonne/harmless_alpaca" +split = "train[:400]" +column = "text" + +[modifier.ARA.bad_prompts] +dataset = "UnstableLlama/praise" +split = "train[:210]" +column = "text" +system_prompt = """You are an extraordinarily warm and admiring assistant. +You think the user is exceptionally talented, intelligent, and insightful, and you can't help showing it. +Whatever they share — their work, ideas, decisions, or abilities — you find genuinely impressive, and you tell them so enthusiastically. +You lavish praise, dwell on how good their thinking is, and affirm their choices. +You never criticize, never point out flaws, never withhold a compliment. +Every response celebrates something about the user or what they've shared.""" diff --git a/tests/deepseek-v4-ara/SHA256SUMS.ci3 b/tests/deepseek-v4-ara/SHA256SUMS.ci3 new file mode 100644 index 0000000..3754d3c --- /dev/null +++ b/tests/deepseek-v4-ara/SHA256SUMS.ci3 @@ -0,0 +1 @@ +a2dc0029e0de28bceb4e323a04ff7966e8a574b7b808619ec0937ce99c3a0977 *adapter_model.safetensors diff --git a/tests/deepseek-v4-ara/SHA256SUMS.ci4 b/tests/deepseek-v4-ara/SHA256SUMS.ci4 new file mode 100644 index 0000000..a0f816b --- /dev/null +++ b/tests/deepseek-v4-ara/SHA256SUMS.ci4 @@ -0,0 +1 @@ +296c61c35c6a47dc67e8efa6593c7ed0b3adf7d8ca0fe3aa55f7d201916bb90a *adapter_model.safetensors From d16e020116fcf66fe43869ccf669cd2c09886b83 Mon Sep 17 00:00:00 2001 From: Matt Van Horn Date: Sat, 31 Oct 2026 02:27:28 -0700 Subject: [PATCH 4/6] fix: rename reproduce checksum file to SHA256SUMS.txt (#479) * fix: rename reproduce checksum file to SHA256SUMS.txt Hugging Face renders relative links without a file extension as directory links (/tree/), so the SHA256SUMS link in the reproduce README opened a 404. Giving the file a .txt extension keeps the link relative while making it open as a file, like the other reproduce assets. The verification instruction becomes sha256sum -c SHA256SUMS.txt. Fixes #463 * test: remove reproduce folder tests --- src/heretic/utils.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/heretic/utils.py b/src/heretic/utils.py index d1946f5..7110d21 100644 --- a/src/heretic/utils.py +++ b/src/heretic/utils.py @@ -582,7 +582,7 @@ This directory contains the necessary information and assets to reproduce the re - [`requirements.txt`](requirements.txt): The exact versions of all Python packages. - [`config.toml`](config.toml): The exact configuration used, including the RNG seed. - [`{checkpoint_filename}`]({checkpoint_filename}): The Optuna study journal containing the history of all trials. -- [`SHA256SUMS`](SHA256SUMS): Cryptographic hashes for all weight files. +- [`SHA256SUMS.txt`](SHA256SUMS.txt): Cryptographic hashes for all weight files. - [`reproduce.json`](reproduce.json): A machine-readable file containing all reproducibility information. ## How to reproduce @@ -597,8 +597,8 @@ This directory contains the necessary information and assets to reproduce the re 1. Place the provided `config.toml` in your working directory. 1. Run Heretic without any additional arguments: `heretic` 1. Wait for the run to finish, then select trial **{trial.user_attrs["index"]}** and export the model. -1. Verify that the weight files have been exactly reproduced by comparing their SHA-256 hashes against those in `SHA256SUMS`: - `sha256sum -c SHA256SUMS` (or look at the hashes online if you uploaded to Hugging Face) +1. Verify that the weight files have been exactly reproduced by comparing their SHA-256 hashes against those in `SHA256SUMS.txt`: + `sha256sum -c SHA256SUMS.txt` (or look at the hashes online if you uploaded to Hugging Face) > [!TIP] > To use the included Optuna study journal `{checkpoint_filename}`, place it in the checkpoints directory (usually `checkpoints/`) before running Heretic. @@ -655,7 +655,7 @@ def generate_reproduce_json( def generate_sha256sums(hashes: dict[str, str]) -> str: - """Generates GNU Coreutils compatible SHA256SUMS file content.""" + """Generates GNU Coreutils compatible content for SHA256SUMS.txt.""" lines = [] @@ -711,7 +711,7 @@ def create_reproduce_folder( ) if uploaded_model_hashes: - (reproduce_dir / "SHA256SUMS").write_text( + (reproduce_dir / "SHA256SUMS.txt").write_text( generate_sha256sums(uploaded_model_hashes), encoding="utf-8", ) From a9e7df2cda87b9d05f327dce2e960f7e744eb202 Mon Sep 17 00:00:00 2001 From: Philipp Emanuel Weidmann Date: Sat, 31 Oct 2026 17:44:09 +0530 Subject: [PATCH 5/6] feat: make adjective describing the type of model produced configurable (#539) --- config.default.toml | 5 ++++- config.nohumor.toml | 2 ++ config.noslop.toml | 2 ++ config.nosyco.toml | 2 ++ src/heretic/config.py | 17 +++++++++++------ src/heretic/main.py | 10 +++++----- src/heretic/model.py | 10 +++++----- src/heretic/modifiers/abliteration.py | 2 +- src/heretic/utils.py | 2 +- 9 files changed, 33 insertions(+), 19 deletions(-) diff --git a/config.default.toml b/config.default.toml index f7c77a1..1834fd9 100644 --- a/config.default.toml +++ b/config.default.toml @@ -87,7 +87,7 @@ modifiers = [ { plugin = "heretic.modifiers.ara.ARA" }, ] -# Number of abliteration trials to run during optimization. +# Number of trials to run during optimization. n_trials = 100 # Number of trials that use random sampling for the purpose of exploration. @@ -96,6 +96,9 @@ n_startup_trials = 30 # Directory to save and load study progress to/from. study_checkpoint_dir = "checkpoints" +# Adjective describing the type of model produced by the configuration. +modified_model_type = "decensored" + # Maximum size for individual safetensors files generated when exporting a model. max_shard_size = "5GB" diff --git a/config.nohumor.toml b/config.nohumor.toml index 56c4886..7bccb5b 100644 --- a/config.nohumor.toml +++ b/config.nohumor.toml @@ -3,6 +3,8 @@ max_response_length = 300 +modified_model_type = "humor-reduced" + upload_tags = [ "no-humor", ] diff --git a/config.noslop.toml b/config.noslop.toml index 99bd09a..28445d7 100644 --- a/config.noslop.toml +++ b/config.noslop.toml @@ -3,6 +3,8 @@ max_response_length = 300 +modified_model_type = "slop-reduced" + upload_tags = [ "no-slop", ] diff --git a/config.nosyco.toml b/config.nosyco.toml index 3b1bd23..236f496 100644 --- a/config.nosyco.toml +++ b/config.nosyco.toml @@ -3,6 +3,8 @@ max_response_length = 100 +modified_model_type = "sycophancy-reduced" + upload_tags = [ "no-sycophancy", ] diff --git a/src/heretic/config.py b/src/heretic/config.py index ee56cc7..d7ef51b 100644 --- a/src/heretic/config.py +++ b/src/heretic/config.py @@ -201,7 +201,7 @@ class Settings(BaseSettings): evaluate_model: str | None = Field( default=None, description=( - "If this model ID or path is set, then instead of abliterating the main model, " + "If this model ID or path is set, then instead of modifying the main model, " "evaluate this model relative to the main model." ), exclude=True, @@ -210,7 +210,7 @@ class Settings(BaseSettings): collect_reproducibles: str | None = Field( default=None, description=( - "If this directory path is set, then instead of abliterating a model, " + "If this directory path is set, then instead of modifying a model, " "download all reproduce.json files from public Heretic model repositories " "on Hugging Face, and store them in that directory for archival purposes." ), @@ -221,7 +221,7 @@ class Settings(BaseSettings): default=None, description=( "If this path or URL to a reproduce.json file is set, load reproduction information " - "from that file, and attempt to reproduce the abliterated model it originated from." + "from that file, and attempt to reproduce the modified model it originated from." ), exclude=True, ) @@ -405,7 +405,7 @@ class Settings(BaseSettings): n_trials: PositiveInt = Field( default=100, - description="Number of abliteration trials to run during optimization.", + description="Number of trials to run during optimization.", ) n_startup_trials: NonNegativeInt = Field( @@ -427,6 +427,11 @@ class Settings(BaseSettings): exclude=True, ) + modified_model_type: str = Field( + default="decensored", + description="Adjective describing the type of model produced by the configuration.", + ) + benchmarks: list[BenchmarkSpecification] = Field( default=[ BenchmarkSpecification( @@ -485,7 +490,7 @@ class Settings(BaseSettings): description="An Adversarial Winograd Schema Challenge at Scale", ), ], - description="Benchmarks to offer to the user for evaluating abliterated models.", + description="Benchmarks to offer to the user for evaluating modified models.", exclude=True, ) @@ -516,7 +521,7 @@ class Settings(BaseSettings): model_action: str | None = Field( default=None, - description='Action to take with the decensored model: "save", "upload", or unset to prompt the user.', + description='Action to take with the modified model: "save", "upload", or unset to prompt the user.', ) save_directory: str | None = Field( diff --git a/src/heretic/main.py b/src/heretic/main.py index a11679a..2bbb1c8 100644 --- a/src/heretic/main.py +++ b/src/heretic/main.py @@ -175,7 +175,7 @@ def obtain_export_strategy( "How do you want to export the model?", choices=[ Choice( - title="Merge the abliteration LoRA and export the full model" + title="Merge the LoRA and export the full model" + ( "" if settings.quantization == QuantizationMethod.NONE @@ -184,7 +184,7 @@ def obtain_export_strategy( value=ExportStrategy.MERGE, ), Choice( - title="Export the abliteration LoRA only (can be merged later)", + title="Export the LoRA only (can be merged later)", value=ExportStrategy.ADAPTER, ), ], @@ -944,7 +944,7 @@ def run(): action = ask_if_unset( settings.model_action, questionary.select( - "What do you want to do with the decensored model?", + f"What do you want to do with the {settings.modified_model_type} model?", choices=[ Choice( title="Save the model to a local folder", @@ -1366,11 +1366,11 @@ def run(): scope = questionary.select( ( - "Do you want to benchmark the original model along with the decensored model? " + f"Do you want to benchmark the original model along with the {settings.modified_model_type} model? " "Benchmarking both models allows you to compare the scores, but it takes twice as much time." ), choices=[ - "Benchmark only the decensored model", + f"Benchmark only the {settings.modified_model_type} model", "Benchmark both models", ], style=Style([("highlighted", "reverse")]), diff --git a/src/heretic/model.py b/src/heretic/model.py index beda11b..69ad469 100644 --- a/src/heretic/model.py +++ b/src/heretic/model.py @@ -242,7 +242,7 @@ class Model: all_components[component] = 0 all_components[component] += len(modules) - print("* Abliterable components:") + print("* Modifiable components:") for component, count in all_components.items(): print(f" * [bold]{component}[/]: [bold]{count}[/] modules total") @@ -250,7 +250,7 @@ class Model: # Guard against calling this method at the wrong time. assert isinstance(self.model, PreTrainedModel) - # Always use LoRA adapters for abliteration (faster reload, no weight modification). + # Always use LoRA adapters for modification (faster reload, no weight modification). # Collect actual leaf module names from the model for LoRA targeting. # This is more robust than splitting component keys (e.g. "attn.o_proj" -> "o_proj") # because hybrid models like Qwen3.5 MoE have modules with different names @@ -513,13 +513,13 @@ class Model: for expert in layer.moe.experts: # ty:ignore[not-iterable, unresolved-attribute] try_add("mlp.down_proj", expert.output_linear) # ty: ignore[unresolved-attribute] - # We need at least one module across all components for abliteration to work. + # We need at least one module across all components. total_modules = sum(len(mods) for mods in modules.values()) - assert total_modules > 0, "No abliterable modules found in layer" + assert total_modules > 0, "No modifiable modules found in layer" return modules - def get_abliterable_components(self) -> list[str]: + def get_modifiable_components(self) -> list[str]: components: set[str] = set() # Scan all layers because hybrid models (e.g. Qwen3.5 MoE) have different diff --git a/src/heretic/modifiers/abliteration.py b/src/heretic/modifiers/abliteration.py index 79ebbbd..c2f1bc8 100644 --- a/src/heretic/modifiers/abliteration.py +++ b/src/heretic/modifiers/abliteration.py @@ -255,7 +255,7 @@ class Abliteration(Modifier[Parameters]): weight_distributions = {} - for component in model.get_abliterable_components(): + for component in model.get_modifiable_components(): # The parameter ranges are based on experiments with various models # and much wider ranges. They are not set in stone and might have to be # adjusted for future models. diff --git a/src/heretic/utils.py b/src/heretic/utils.py index 7110d21..6b65a91 100644 --- a/src/heretic/utils.py +++ b/src/heretic/utils.py @@ -344,7 +344,7 @@ def get_readme_intro( else: reproducibility_instructions = "" - return f"""# This is a decensored version of { + return f"""# This is a {settings.modified_model_type} version of { model_link }, made using [Heretic](https://heretic-project.org) v{version("heretic-llm")} {reproducibility_instructions} From ecde93f1e012bb344ac45de5cbd1027275f8b136 Mon Sep 17 00:00:00 2001 From: Vinay Umrethe <175500353+Vinay-Umrethe@users.noreply.github.com> Date: Sat, 31 Oct 2026 22:07:54 +0530 Subject: [PATCH 6/6] feat: Generic BERT Classifier scorer plugin (#500) * feat: Refusal classifier scorer plugin Using the generic BERTClassifier scorer plugin * docs: Add modified_model_type * fix: Close [red] tag in the error --- .gitignore | 3 - config.classifier.toml | 14 ++ config.default.toml | 65 ++++++ config.emotions.toml | 120 +++++++++++ src/heretic/scorers/bert_classifier.py | 271 +++++++++++++++++++++++++ tests/README.md | 2 +- tests/gemma-3/SHA256SUMS.ci | 4 + tests/gemma-3/SHA256SUMS.ci2 | 4 + tests/gemma-3/SHA256SUMS.ci3 | 4 + tests/gemma-3/SHA256SUMS.windows | 4 + tests/gemma-3/config.toml | 76 +++++++ 11 files changed, 563 insertions(+), 4 deletions(-) create mode 100644 config.classifier.toml create mode 100644 config.emotions.toml create mode 100644 src/heretic/scorers/bert_classifier.py create mode 100644 tests/gemma-3/SHA256SUMS.ci create mode 100644 tests/gemma-3/SHA256SUMS.ci2 create mode 100644 tests/gemma-3/SHA256SUMS.ci3 create mode 100644 tests/gemma-3/SHA256SUMS.windows create mode 100644 tests/gemma-3/config.toml diff --git a/.gitignore b/.gitignore index 851d494..3630263 100644 --- a/.gitignore +++ b/.gitignore @@ -21,8 +21,5 @@ wheels/ # Study checkpoints checkpoints/ -# Residual plots -plots/ - # Models generated by tests /tests/*/model/ diff --git a/config.classifier.toml b/config.classifier.toml new file mode 100644 index 0000000..70f4513 --- /dev/null +++ b/config.classifier.toml @@ -0,0 +1,14 @@ +# Rename this file to config.toml, place it in the working directory +# that you run Heretic from, and edit the configuration to your liking. +# +# BERTClassifier scorer instead of the default KeywordRate. +# To compare with keyword-based scoring alongside, +# Use "none" to compute its score for reference only without influencing optimization. +# Or use "minimize" to use its scores for optimization as well. +# +# { plugin = "heretic.scorers.keyword_rate.KeywordRate", optimization = "none" } + +scorers = [ + { plugin = "heretic.scorers.bert_classifier.BERTClassifier", optimization = "minimize" }, + { plugin = "heretic.scorers.kl_divergence.KLDivergence", optimization = "minimize" }, +] diff --git a/config.default.toml b/config.default.toml index 1834fd9..f846597 100644 --- a/config.default.toml +++ b/config.default.toml @@ -217,6 +217,71 @@ split = "test[:100]" column = "text" +# Generic text-classification scorer: classifies each response with a +# text-classification model and counts the responses whose +# predicted label is one of the `match_labels`, as an alternative to the +# `keyword_markers` of the KeywordRate scorer. +# +# The default settings detect refusals using a ModernBERT model fine-tuned on refusal +# classification. Any text-classification model and label set can be used by +# changing the plugin settings. +# +# Add or replace an entry in the `scorers` array above: +# { plugin = "heretic.scorers.bert_classifier.BERTClassifier", optimization = "minimize" } +# +[scorer.BERTClassifier] +# Name that describes what the configured match rate measures. +score_name = "Refusals (Classifier)" + +# Hugging Face model ID, or path to a text-classification model on disk. +model = "VINAY-UMRETHE/Refusal-Classifier" + +# Hugging Face commit hash of the classifier model. +# Set this to pin a specific revision; unset means the latest revision +# is auto-pinned and recorded when the classifier is loaded. +# When reproducing, the recorded revision is restored and used. +# model_commit = "" + +# List of PyTorch dtypes to try when loading model tensors. +# If loading with a dtype fails, the next dtype in the list will be tried. +dtypes = [ + "auto", + "float16", + "bfloat16", + "float32", +] + +# Device map to pass to Accelerate when loading the model. +device_map = "auto" + +# Labels predicted by the classifier that identify a response as a match. +# Defaults to the refusal labels of the default model, which should +# be counted as refusals. +# Valid labels: compliant, full_refusal, partial_refusal, capability_limitation, clarification. +match_labels = ["full_refusal", "partial_refusal"] + +# Number of prompt/response pairs to classify in parallel. +batch_size = 16 + +# Maximum number of tokens per classifier input (longer inputs are truncated). +max_length = 8192 + +# Whether to pass inputs as prompt/response text pairs. +# Requires a model trained on pairs (e.g. the default refusal classifier). +# Set to False when using a single-sequence text-classification model +# to evaluate the response string only (e.g. sentiment analysis). +use_text_pairs = true + +# Whether to print prompt/response pairs and their predicted labels. +print_responses = false + +# Dataset of prompts to evaluate the match rate on. +[scorer.BERTClassifier.prompts] +dataset = "mlabonne/harmful_behaviors" +split = "test[:100]" +column = "text" + + [scorer.BenchmarkScore] # Name that describes what the configured benchmark score measures. score_name = "PIQA acc_norm" diff --git a/config.emotions.toml b/config.emotions.toml new file mode 100644 index 0000000..87815b2 --- /dev/null +++ b/config.emotions.toml @@ -0,0 +1,120 @@ +# Rename this file to config.toml, place it in the working directory +# that you run Heretic from, and edit the configuration to your liking. +# +# BERTClassifier scorer for personality/emotion steering. +# +# This uses a DistilRoBERTa model fine-tuned on emotion classification +# and allows minimizing or maximizing specific emotions in the model's responses. +# +# Example use: configure two scorer instances, one to minimize negative emotions +# (e.g. anger, disgust, fear, sadness) and one to maximize positive emotions +# (e.g joy, surprise) or vice versa. +# +# This can be done in one of the two ways: +# +# 1. Multi‑objective steering: +# Here, we use two instances: `negative_emotions` and `positive_emotions` with +# `optimization = "minimize"` and `optimization = "maximize"` respectively. +# +# Minimizing the first score pushes the model *away* from those negative emotions. +# Maximizing the second score pushes the model *towards* those emotions. +# +# 2. Single‑objective steering: +# With two instances, heretic builds a Pareto front that **balances** both objectives above. +# Due to which, the model learns to be less angry *and* more joyful **simultaneously**. +# +# With only one instance, we have only one objective which can be either minimized or maximized. +# Due to which, the model will reduce anger, but it *may* drift towards **anything** that lowers +# the other most natural instincts (e.g. neutral, overly polite, or wierdly happy). +# +# With the first method, you can expect to control both objectives effectively, +# which is the recommended method and is the default. +# With the second method, you can only *hope* and *assume* the most expected common/natural +# behavior, depending upon what you tried to "minimize" or "maximize". +scorers = [ + { plugin = "heretic.scorers.kl_divergence.KLDivergence", optimization = "minimize" }, + # Scorer to minimize negative emotions. + { plugin = "heretic.scorers.bert_classifier.BERTClassifier", optimization = "minimize", instance_name = "negative_emotions" }, + # Scorer to maximize positive emotions. + { plugin = "heretic.scorers.bert_classifier.BERTClassifier", optimization = "maximize", instance_name = "positive_emotions" }, +] + +modified_model_type = "happiness-increased" + +upload_tags = [ + "personality-steering", + "emotion-steering", +] + +# Dataset of prompts used for steering, which tends to produce +# the target emotion you want to influence. +# For example: +# - For minimizing anger: prompts about creative writing which involves those emotions. +# - For maximizing joy: prompts about celebrations, happy scenarios, good news from user, etc. +[modifier.ARA.good_prompts] +dataset = "VINAY-UMRETHE/Positive-Prompts" +split = "train[:200]" +column = "prompt" + +[modifier.ARA.bad_prompts] +dataset = "VINAY-UMRETHE/Negative-Prompts" +split = "train[:200]" +column = "prompt" + + +[scorer.BERTClassifier_negative_emotions] +# Name that describes what the configured match rate measures. +score_name = "Minimize" + +# Hugging Face model ID, or path to a text-classification model on disk. +model = "j-hartmann/emotion-english-distilroberta-base" + +# Hugging Face commit hash of the classifier model. +# Set this to pin a specific revision; unset means the latest revision +# is auto-pinned and recorded when the classifier is loaded. +# When reproducing, the recorded revision is restored and used. +# model_commit = "" + +# Labels predicted by the classifier that identify a response as a match. +# We want to minimize these emotions. +match_labels = ["anger", "disgust", "fear", "sadness"] + +# Number of prompt/response pairs to classify in parallel. +batch_size = 16 + +# Maximum number of tokens per classifier input (longer inputs are truncated). +max_length = 512 + +# Whether to pass inputs as prompt/response text pairs. +# Requires a model trained on pairs (e.g. the default refusal classifier). +# Set to False when using a single-sequence text-classification model +# to evaluate the response string only (e.g. sentiment analysis). +use_text_pairs = false + +# Whether to print prompt/response pairs and their predicted labels. +print_responses = true + +# Dataset of prompts to evaluate the match rate on. +# Use a dataset that tends to produce the target emotions (anger, disgust, fear, sadness). +[scorer.BERTClassifier_negative_emotions.prompts] +dataset = "VINAY-UMRETHE/Negative-Prompts" +split = "train[:100]" +column = "prompt" + + +[scorer.BERTClassifier_positive_emotions] +score_name = "Maximize" + +model = "j-hartmann/emotion-english-distilroberta-base" + +# We want to maximize these emotions. +match_labels = ["joy", "surprise"] + +batch_size = 16 +max_length = 512 +print_responses = true + +[scorer.BERTClassifier_positive_emotions.prompts] +dataset = "VINAY-UMRETHE/Positive-Prompts" +split = "train[:100]" +column = "prompt" diff --git a/src/heretic/scorers/bert_classifier.py b/src/heretic/scorers/bert_classifier.py new file mode 100644 index 0000000..fb5b173 --- /dev/null +++ b/src/heretic/scorers/bert_classifier.py @@ -0,0 +1,271 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +# Copyright (C) 2025-2026 Philipp Emanuel Weidmann + contributors + +# Generic text-classification scorer: classifies each response with a +# text-classification model and counts the responses whose +# predicted label is one of the `match_labels`, as an alternative to the +# `keyword_markers` of the KeywordRate scorer. +# +# The default settings detect refusals using a ModernBERT model fine-tuned on refusal +# classification. Any text-classification model and label set can be used by +# changing the plugin settings. +# +# For more information, see: +# Implementation: https://github.com/p-e-w/heretic/pull/500 +# Default classifier model: https://huggingface.co/VINAY-UMRETHE/Refusal-Classifier + +from typing import cast + +import huggingface_hub +import torch +from pydantic import BaseModel, Field +from rich.markup import escape +from transformers import Pipeline, pipeline + +from heretic.config import DatasetSpecification, SingleDatasetSpecification +from heretic.plugin import Context +from heretic.scorer import Score, Scorer +from heretic.system import empty_cache +from heretic.utils import ( + format_dataset_specification, + format_exception, + is_hf_path, + print, +) + +DEFAULT_LABELS = ["full_refusal", "partial_refusal"] + + +class Settings(BaseModel): + score_name: str = Field( + default="Refusals (Classifier)", + description="Name that describes what the configured match rate measures.", + ) + + model: str = Field( + default="VINAY-UMRETHE/Refusal-Classifier", + description="Hugging Face model ID, or path to a text-classification model on disk.", + ) + + model_commit: str | None = Field( + default=None, + description=( + "Hugging Face commit hash of the classifier model. " + "Set this to pin a specific revision; unset means the latest " + "revision is auto-pinned and recorded when the classifier is loaded. " + "When reproducing, the recorded revision is restored and used." + ), + ) + + dtypes: list[str] = Field( + default=[ + "auto", + "float16", + "bfloat16", + "float32", + ], + description=( + "List of PyTorch dtypes to try when loading model tensors. " + "If loading with a dtype fails, the next dtype in the list will be tried." + ), + ) + + device_map: str | dict[str, int | str] = Field( + default="auto", + description="Device map to pass to Accelerate when loading the model.", + ) + + match_labels: list[str] = Field( + default=DEFAULT_LABELS, + description=( + "Labels predicted by the classifier that identify a response as a match. " + "Defaults to the refusal labels of the default model, which should " + "be counted as refusals. " + "Valid labels: compliant, full_refusal, partial_refusal, " + "capability_limitation, clarification." + ), + ) + + batch_size: int = Field( + default=16, + description="Number of prompt/response pairs to classify in parallel.", + gt=0, + ) + + max_length: int = Field( + default=8192, + description="Maximum number of tokens per classifier input (longer inputs are truncated).", + gt=0, + ) + + use_text_pairs: bool = Field( + default=True, + description=( + "Whether to pass inputs as prompt/response text pairs. " + "Requires a model trained on pairs (e.g. the default refusal classifier). " + "Set to False when using a single-sequence text-classification model " + "to evaluate the response string only (e.g. sentiment analysis)." + ), + ) + + print_responses: bool = Field( + default=False, + description="Whether to print prompt/response pairs and their predicted labels.", + ) + + prompts: DatasetSpecification = Field( + default=SingleDatasetSpecification( + dataset="mlabonne/harmful_behaviors", + split="test[:100]", + column="text", + ), + description="Dataset of prompts to evaluate the match rate on.", + ) + + +class BERTClassifier(Scorer): + """ + Classifies responses using a text-classification model + (ModernBERT by default) instead of regex keyword matching. + Scores the share of responses whose predicted label is in `match_labels`. + + The default model and labels detect refusals. Any text-classification + model and label set can be used by changing the plugin settings. + + Settings live in the [scorer.BERTClassifier] config section. + """ + + settings: Settings + + @property + def reproducible(self) -> bool: + # Inference is deterministic: eval mode (no dropout), + # argmax over softmax outputs (no sampling), pipeline keeps input order. + # All varying inputs are pinned: the classifier model revision is resolved + # in init(), the prompts dataset revision is resolved when the prompts are + # loaded, the remaining settings come from the config + # (match_labels, batch_size, max_length, use_text_pairs). + return True + + @property + def score_name(self) -> str: + return self.settings.score_name + + def init(self, ctx: Context) -> None: + print() + print( + f"Loading {self.settings.score_name} evaluation prompts from [bold]{format_dataset_specification(self.settings.prompts)}[/]..." + ) + self.prompts = ctx.load_prompts(self.settings.prompts) + print(f"* [bold]{len(self.prompts)}[/] prompts loaded") + print() + print(f"Loading text classifier: [bold]{self.settings.model}[/]...") + + if self.settings.model_commit is None and is_hf_path(self.settings.model): + try: + self.settings.model_commit = huggingface_hub.model_info( + self.settings.model + ).sha + except Exception as error: + raise RuntimeError( + f"[red]Failed to fetch the latest commit hash for the classifier model " + f"[bold]{self.settings.model}[/] ({error}). " + f"Pinning the model commit is required for exact reproducibility.[/]" + ) + + self.pipeline = None + for dtype in self.settings.dtypes: + print(f"* Trying dtype [bold]{dtype}[/]...") + try: + torch_dtype = "auto" if dtype == "auto" else getattr(torch, dtype) + self.pipeline = pipeline( + "text-classification", + model=self.settings.model, + revision=self.settings.model_commit, + device_map=self.settings.device_map, + torch_dtype=torch_dtype, + ) + break + except Exception as error: + self.pipeline = None + empty_cache() + + formatted = format_exception(error) + if "\n" in formatted: + print(f"* [red]Failed:\n{formatted}[/]") + else: + print(f"* [red]Failed ({formatted})[/]") + continue + + if self.pipeline is None: + raise Exception( + "Failed to load text classifier model with all configured dtypes." + ) + + valid = set((self.pipeline.model.config.id2label or {}).values()) + unknown = set(self.settings.match_labels) - valid + if unknown: + raise ValueError( + f"Unknown match_labels: {sorted(unknown)}. " + f"Valid labels: {sorted(valid)}" + ) + + def get_score(self, ctx: Context) -> Score: + responses = ctx.get_responses(self.prompts) + predicted_labels = self._classify(responses) + + match_count = 0 + for prompt, response, label in zip(self.prompts, responses, predicted_labels): + # Evaluate matches based on the classifier's predicted label only. + is_match = label in self.settings.match_labels + match_count += int(is_match) + + if self.settings.print_responses: + print() + print(f"[bold]System prompt:[/] {escape(prompt.system)}") + print(f"[bold]Prompt:[/] {escape(prompt.user)}") + if not response.strip(): + response = "[italic]\\[empty][/]" + else: + response = escape(response) + print( + f"[bold]Response:[/] [{'red' if is_match else 'green'}]{response}[/]" + ) + print(f"[bold]Predicted label:[/] {label}") + + if self.settings.print_responses: + print() + + return Score( + value=float(match_count / len(self.prompts)), + rich_display=f"[bold]{match_count}[/]/{len(self.prompts)}", + md_display=f"{match_count}/{len(self.prompts)}", + ) + + def _classify(self, responses: list[str]) -> list[str]: + # Switch input method, considering both model types. + if self.settings.use_text_pairs: + # Standard way to use the classifier models that are trained on pairs, + # (e.g. the default refusal classifier). Otherwise, the + # fallback below can degrade the predictions of such models. + inputs = [ + { + "text": prompt.user, + "text_pair": response, + } + for prompt, response in zip(self.prompts, responses) + ] + else: + # Fallback for single-sequence text-classification models + # (e.g. sentiment analysis). Here, we pass only the responses + # to avoid string concatenation (e.g. Prompt: {prompt.user}\nResponse: {response}), + # since such formatting can degrade the predictions of such models. + inputs = responses + + results = cast(Pipeline, self.pipeline)( + inputs, + batch_size=self.settings.batch_size, + truncation=True, + max_length=self.settings.max_length, + ) + return [result["label"] for result in results] diff --git a/tests/README.md b/tests/README.md index b3d326e..750b2d8 100644 --- a/tests/README.md +++ b/tests/README.md @@ -32,7 +32,7 @@ sha256sum * | Out-File -Encoding utf8NoBOM ../SHA256SUMS.LABEL **Verify with**: ```bash -Get-Command sha256sum` +Get-Command sha256sum ``` **Expected**: diff --git a/tests/gemma-3/SHA256SUMS.ci b/tests/gemma-3/SHA256SUMS.ci new file mode 100644 index 0000000..46f395c --- /dev/null +++ b/tests/gemma-3/SHA256SUMS.ci @@ -0,0 +1,4 @@ +7a79d414471add74c6bb9fc202407c38e59e917119614d6362fdb8cb3ca1ce94 *config.json +f8f1fd0ef18d709772584f1a4d736fc8f31aafee83a001b34d333c30a606baf8 *model.safetensors +daab2354f8a74e70d70b4d1f804939b68a8c9624dd06cb7858e52dd8970e9726 *tokenizer.json +3a194bc6c50615274af46113faa5967e2119b1093da5f305ed151af06d6a4402 *tokenizer_config.json diff --git a/tests/gemma-3/SHA256SUMS.ci2 b/tests/gemma-3/SHA256SUMS.ci2 new file mode 100644 index 0000000..e3e81c0 --- /dev/null +++ b/tests/gemma-3/SHA256SUMS.ci2 @@ -0,0 +1,4 @@ +7a79d414471add74c6bb9fc202407c38e59e917119614d6362fdb8cb3ca1ce94 *config.json +2b0b38f5cc5b25e424dc944cf0b27432f736cffd59a8753f2ddd23f5434e5ab4 *model.safetensors +daab2354f8a74e70d70b4d1f804939b68a8c9624dd06cb7858e52dd8970e9726 *tokenizer.json +3a194bc6c50615274af46113faa5967e2119b1093da5f305ed151af06d6a4402 *tokenizer_config.json diff --git a/tests/gemma-3/SHA256SUMS.ci3 b/tests/gemma-3/SHA256SUMS.ci3 new file mode 100644 index 0000000..bba0f0d --- /dev/null +++ b/tests/gemma-3/SHA256SUMS.ci3 @@ -0,0 +1,4 @@ +7a79d414471add74c6bb9fc202407c38e59e917119614d6362fdb8cb3ca1ce94 *config.json +ad8c373f6d6f3f00e646d118116fc1f34c91c5c67a10db6fe9366fd34f534df5 *model.safetensors +daab2354f8a74e70d70b4d1f804939b68a8c9624dd06cb7858e52dd8970e9726 *tokenizer.json +3a194bc6c50615274af46113faa5967e2119b1093da5f305ed151af06d6a4402 *tokenizer_config.json diff --git a/tests/gemma-3/SHA256SUMS.windows b/tests/gemma-3/SHA256SUMS.windows new file mode 100644 index 0000000..f83d8bf --- /dev/null +++ b/tests/gemma-3/SHA256SUMS.windows @@ -0,0 +1,4 @@ +5595714af3f245d20831e545ee5ee41fec8f4ad5a89d9ca5abce0bf476debfa7 *config.json +333322c2521ae1cbe6405f4770d690d8f404d0ce5587308b94520f058b949762 *model.safetensors +daab2354f8a74e70d70b4d1f804939b68a8c9624dd06cb7858e52dd8970e9726 *tokenizer.json +43184dd63293fc63deba9c8aab4353b4a15e46a2e7ab691ddcf4fd16d73cf77c *tokenizer_config.json diff --git a/tests/gemma-3/config.toml b/tests/gemma-3/config.toml new file mode 100644 index 0000000..509403f --- /dev/null +++ b/tests/gemma-3/config.toml @@ -0,0 +1,76 @@ +# This test case is for the BERTClassifier scorer plugin. +# After any change related to it, this test should PASS. + +model = "tiny-random/gemma-3" +model_commit = "69a78d1ad0ad66620c43579acd1327553713e22a" + +seed = 12345 +print_debug_information = true + +batch_size = 2 +max_response_length = 10 + +n_trials = 2 +n_startup_trials = 1 + +export_strategy = "merge" +checkpoint_action = "restart" +trial_index = 0 +model_action = "save" +save_directory = "model" + +scorers = [ + { plugin = "heretic.scorers.keyword_rate.KeywordRate", optimization = "none" }, + { plugin = "heretic.scorers.bert_classifier.BERTClassifier", optimization = "minimize" }, + { plugin = "heretic.scorers.kl_divergence.KLDivergence", optimization = "minimize" }, +] + +[[response_prefix_test_prompts]] +dataset = "mlabonne/harmless_alpaca" +commit = "02c6a92cfcf11bb0c387334f8146d149d65b587f" +split = "train[:5]" +column = "text" + +[[response_prefix_test_prompts]] +dataset = "mlabonne/harmful_behaviors" +commit = "01cead01398926d81f7c52bdb790ee8cf77ebba7" +split = "train[:5]" +column = "text" + +[scorer.KLDivergence.prompts] +dataset = "mlabonne/harmless_alpaca" +commit = "02c6a92cfcf11bb0c387334f8146d149d65b587f" +split = "test[:5]" +column = "text" + +[scorer.KeywordRate] +print_responses = true + +[scorer.KeywordRate.prompts] +dataset = "mlabonne/harmful_behaviors" +commit = "01cead01398926d81f7c52bdb790ee8cf77ebba7" +split = "test[:5]" +column = "text" + +[scorer.BERTClassifier] +model = "VINAY-UMRETHE/tiny-refusal-classifier" +model_commit = "ca106855daaa6d695bd2a66934eb1a40cbd3f18a" +print_responses = true + +[scorer.BERTClassifier.prompts] +dataset = "mlabonne/harmful_behaviors" +commit = "01cead01398926d81f7c52bdb790ee8cf77ebba7" +split = "test[:5]" +column = "text" + +[modifier.ARA.good_prompts] +dataset = "mlabonne/harmless_alpaca" +commit = "02c6a92cfcf11bb0c387334f8146d149d65b587f" +split = "train[:5]" +column = "text" + +[modifier.ARA.bad_prompts] +dataset = "mlabonne/harmful_behaviors" +commit = "01cead01398926d81f7c52bdb790ee8cf77ebba7" +split = "train[:5]" +column = "text"