diff --git a/docs/configuration.md b/docs/configuration.md index 6591349..642c974 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -272,11 +272,15 @@ prints what differs, for example: A difference doesn't stop the save, but it means that the saved model is not just the source checkpoint with modified values. Common causes are layers that Transformers doesn't load, such as the multi-token prediction (MTP) layers of -Qwen3.5 and Qwen3-Next, tensors that the checkpoint stores in another dtype than the -rest of the model, and a language model head that is tied to the embeddings and -therefore saved only once. The source checkpoint is read from its directory or from -the Hugging Face cache. If it has no safetensors files, Heretic says that it could -not compare the tensors. +Qwen3.5, Qwen3-Next and Hy3, tensors that the checkpoint stores in another dtype than +the rest of the model, and a language model head that is tied to the embeddings and +therefore saved only once. Weights stored in FP8, as in `tencent/Hy3-FP8`, are +another cause: Heretic loads and saves them converted to the model's regular dtype, +without the scales that the FP8 format stores with them. As these differences are +expected, Heretic leaves them out and says that it compared the FP8 weights as +dequantized. The source checkpoint is read from its directory or from the Hugging +Face cache. If it has no safetensors files, Heretic says that it could not compare +the tensors. Some models can't be saved at all after loading them, because Transformers fails to convert their weights back to the format of the checkpoint. To find out before a diff --git a/src/heretic/tensor_check.py b/src/heretic/tensor_check.py index b6ac600..da65c26 100644 --- a/src/heretic/tensor_check.py +++ b/src/heretic/tensor_check.py @@ -1,12 +1,14 @@ # SPDX-License-Identifier: AGPL-3.0-or-later # Copyright (C) 2025-2026 Philipp Emanuel Weidmann + contributors +from dataclasses import replace from pathlib import Path import huggingface_hub from huggingface_hub.utils import TensorInfo from rich.markup import escape +from .model import get_fp8_quantization_config from .utils import format_exception, print # The kinds of differences found by compare_tensors, in the order in which they are @@ -18,6 +20,17 @@ "dtype": "with another dtype", } +# The last parts of the names of the tensors that checkpoints store with FP8 weights: +# the scales of the weights and of their inputs, under the names that Transformers +# expects and those that checkpoints with one scale per weight matrix use instead +# (see PER_TENSOR_FP8_SCALE_NAMES). +FP8_SCALE_NAMES = { + "weight_scale_inv", + "activation_scale", + "weight_scale", + "input_scale", +} + def get_tensors( model: str, @@ -86,6 +99,29 @@ def compare_tensors( return differences +def dequantize_tensors( + source: dict[str, TensorInfo], + saved: dict[str, TensorInfo], +) -> dict[str, TensorInfo]: + """ + Returns the tensors of a source checkpoint whose weights are stored in FP8, + as they are saved after loading the model from it. Loading dequantizes the + FP8 weights to the model's dtype (see get_fp8_loading_kwargs), so they are + saved in that dtype, which is taken from the saved model, and without their + scales. + """ + + return { + name: ( + replace(tensor, dtype=saved[name].dtype) + if tensor.dtype.startswith("F8_") and name in saved + else tensor + ) + for name, tensor in source.items() + if name.rpartition(".")[2] not in FP8_SCALE_NAMES + } + + def check_tensors( source_model: str, source_revision: str | None, @@ -96,13 +132,20 @@ def check_tensors( Compares the tensors of a saved or uploaded model with those of the source checkpoint, and prints the result. The model is read as described for get_tensors, so an uploaded model is read from the Hub if a token is given. - Returns the differences (see compare_tensors), or None if the tensors of - either model couldn't be read. + If the weights of the source checkpoint are stored in FP8 (see + get_fp8_quantization_config), they are compared as dequantized (see + dequantize_tensors). Returns the differences (see compare_tensors), + or None if either model couldn't be read. """ try: source = get_tensors(source_model, source_revision) saved = get_tensors(saved_model, token=token) + # Set if the weights were dequantized when loading the model + # (see Model._read_fp8_quantization_config, which reads it the same way). + fp8_quantization_config = get_fp8_quantization_config( + source_model, source_revision + ) except Exception as error: print( "* [yellow]Could not compare the tensors with those of the source " @@ -110,6 +153,13 @@ def check_tensors( ) return None + if fp8_quantization_config is not None: + source = dequantize_tensors(source, saved) + print( + "* The FP8 weights of the source checkpoint are compared as dequantized, " + "without their scales" + ) + differences = compare_tensors(source, saved) if not differences: diff --git a/tests/test_tensor_check.py b/tests/test_tensor_check.py index 0cb2662..f34650a 100644 --- a/tests/test_tensor_check.py +++ b/tests/test_tensor_check.py @@ -45,6 +45,55 @@ def summary(tensors: dict[str, TensorInfo]) -> dict[str, tuple[str, list[int]]]: "lm_head.weight": ("BF16", [8, 4]), } +FP8 = torch.float8_e4m3fn + +# The tensors of a checkpoint whose weights are stored in FP8, each with a scale +# and a scale for its inputs: for the attention under the names of checkpoints +# with one scale per weight matrix (as tencent/Hy3-FP8, see test_model_loading.py), +# and for the expert under the names that Transformers expects. +FP8_SOURCE = { + "embed.weight": torch.zeros(8, 4, dtype=torch.bfloat16), + "layers.0.expert_bias": torch.zeros(2, dtype=torch.float32), + "layers.0.experts.0.down_proj.activation_scale": torch.ones(1), + "layers.0.experts.0.down_proj.weight": torch.zeros(4, 8, dtype=FP8), + "layers.0.experts.0.down_proj.weight_scale_inv": torch.ones(1, 1), + "layers.0.self_attn.o_proj.input_scale": torch.ones(1), + "layers.0.self_attn.o_proj.weight": torch.zeros(4, 4, dtype=FP8), + "layers.0.self_attn.o_proj.weight_scale": torch.ones((), dtype=torch.bfloat16), + "lm_head.weight": torch.zeros(8, 4, dtype=torch.bfloat16), +} + +# The tensors of that model as Heretic saves it, after loading it with the FP8 +# weights dequantized to bfloat16. +DEQUANTIZED = { + "embed.weight": FP8_SOURCE["embed.weight"], + "layers.0.expert_bias": FP8_SOURCE["layers.0.expert_bias"], + "layers.0.experts.0.down_proj.weight": torch.zeros(4, 8, dtype=torch.bfloat16), + "layers.0.self_attn.o_proj.weight": torch.zeros(4, 4, dtype=torch.bfloat16), + "lm_head.weight": FP8_SOURCE["lm_head.weight"], +} + +# The line that check_tensors prints before its result for such a checkpoint. +FP8_LINE = ( + "* The FP8 weights of the source checkpoint are compared as dequantized, " + "without their scales" +) + + +def save_fp8_checkpoint(directory: str, quant_method: str = "fp8") -> None: + save_file(FP8_SOURCE, Path(directory) / "model.safetensors") + (Path(directory) / "config.json").write_text( + json.dumps( + { + "quantization_config": { + "activation_scheme": "static", + "quant_method": quant_method, + }, + } + ), + encoding="utf-8", + ) + class GetTensorsTests(unittest.TestCase): def test_single_file(self) -> None: @@ -160,9 +209,14 @@ def test_kinds_of_differences(self) -> None: class CheckTensorsTests(unittest.TestCase): - def check(self, source: str, saved: str) -> tuple[object, str]: + def check( + self, + source: str, + saved: str, + source_revision: str | None = None, + ) -> tuple[object, str]: with mock.patch("heretic.tensor_check.print") as print_mock: - differences = check_tensors(source, None, saved) + differences = check_tensors(source, source_revision, saved) output = "\n".join( Text.from_markup(call.args[0]).plain for call in print_mock.call_args_list @@ -272,6 +326,120 @@ def test_model_saved_by_transformers(self) -> None: self.assertEqual(differences, {}) self.assertIn("All 21 tensors", output) + def test_fp8_checkpoint(self) -> None: + # The scales of the FP8 weights, and the dtypes in which the weights are + # saved after dequantizing them, are not differences. + with ( + tempfile.TemporaryDirectory() as source, + tempfile.TemporaryDirectory() as saved, + ): + save_fp8_checkpoint(source) + save_file(DEQUANTIZED, Path(saved) / "model.safetensors") + + differences, output = self.check(source, saved) + + self.assertEqual(differences, {}) + self.assertEqual( + output.splitlines(), + [ + FP8_LINE, + ( + "* All 5 tensors have the same names, dtypes and shapes " + "as in the source checkpoint" + ), + ], + ) + + def test_fp8_checkpoint_with_other_differences(self) -> None: + with ( + tempfile.TemporaryDirectory() as source, + tempfile.TemporaryDirectory() as saved, + ): + save_fp8_checkpoint(source) + # Without one FP8 weight, as if Transformers didn't load its layer, + # but with the scale of another, which isn't saved once dequantized. + tensors = { + **DEQUANTIZED, + "layers.0.expert_bias": torch.zeros(2, dtype=torch.bfloat16), + "layers.0.experts.0.down_proj.weight": torch.zeros(8, 4), + "layers.0.experts.0.down_proj.weight_scale_inv": torch.ones(1, 1), + } + del tensors["layers.0.self_attn.o_proj.weight"] + save_file(tensors, Path(saved) / "model.safetensors") + + differences, output = self.check(source, saved) + + self.assertEqual( + differences, + { + "missing": ["layers.0.self_attn.o_proj.weight"], + "added": ["layers.0.experts.0.down_proj.weight_scale_inv"], + "shape": ["layers.0.experts.0.down_proj.weight"], + "dtype": ["layers.0.expert_bias"], + }, + ) + self.assertEqual( + output.splitlines(), + [ + FP8_LINE, + "* Differences from the 5 tensors of the source checkpoint:", + " * 1 missing (layers.0.self_attn.o_proj.weight)", + " * 1 added (layers.0.experts.0.down_proj.weight_scale_inv)", + ( + " * 1 with another shape " + "(layers.0.experts.0.down_proj.weight: [4, 8] -> [8, 4])" + ), + " * 1 with another dtype (layers.0.expert_bias: F32 -> BF16)", + ], + ) + + def test_fp8_tensors_of_checkpoint_that_is_not_dequantized(self) -> None: + # Only the weights of checkpoints whose quantization method is "fp8" are + # loaded dequantized, so the FP8 tensors of others are compared as stored. + with ( + tempfile.TemporaryDirectory() as source, + tempfile.TemporaryDirectory() as saved, + ): + save_fp8_checkpoint(source, quant_method="compressed-tensors") + save_file(DEQUANTIZED, Path(saved) / "model.safetensors") + + differences, output = self.check(source, saved) + + self.assertEqual( + differences, + { + "missing": [ + "layers.0.experts.0.down_proj.activation_scale", + "layers.0.experts.0.down_proj.weight_scale_inv", + "layers.0.self_attn.o_proj.input_scale", + "layers.0.self_attn.o_proj.weight_scale", + ], + "dtype": [ + "layers.0.experts.0.down_proj.weight", + "layers.0.self_attn.o_proj.weight", + ], + }, + ) + self.assertEqual( + output.splitlines()[0], + "* Differences from the 9 tensors of the source checkpoint:", + ) + + def test_fp8_configuration_is_read_at_source_revision(self) -> None: + # As when the model was loaded (see Model._read_fp8_quantization_config). + commit = "0123456789abcdef0123456789abcdef01234567" + + with ( + mock.patch("heretic.tensor_check.get_tensors", return_value={}), + mock.patch( + "heretic.tensor_check.get_fp8_quantization_config", + return_value=None, + ) as get_fp8_quantization_config, + ): + self.check("org/model", "user/model-heretic", commit) + + get_fp8_quantization_config.assert_called_once_with("org/model", commit) + if __name__ == "__main__": unittest.main()