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()