From f66aa2e09582a83f8ab03368a505c69793cb55d3 Mon Sep 17 00:00:00 2001 From: Yiming Zhao Date: Thu, 3 Dec 2026 09:17:09 -0800 Subject: [PATCH 1/2] [Cosmos3] Read checkpoint mixed-precision policy through wrapped transformers Look up load_config on the module instance instead of its class. torch.compile's OptimizedModule and other attribute-forwarding wrappers expose the original module's load_config, so the checkpoint policy resolves through them. --- .../pipelines/cosmos/mixed_precision.py | 4 +- .../cosmos/test_cosmos3_mixed_precision.py | 94 +++++++++++++++++++ 2 files changed, 97 insertions(+), 1 deletion(-) create mode 100644 tests/pipelines/cosmos/test_cosmos3_mixed_precision.py diff --git a/src/diffusers/pipelines/cosmos/mixed_precision.py b/src/diffusers/pipelines/cosmos/mixed_precision.py index c1ec2d44dc92..728d1c4465ae 100644 --- a/src/diffusers/pipelines/cosmos/mixed_precision.py +++ b/src/diffusers/pipelines/cosmos/mixed_precision.py @@ -447,7 +447,9 @@ def _on_disk_quantization_config(module: nn.Module) -> dict[str, Any] | None: name_or_path = getattr(config, "_name_or_path", None) if name_or_path is None and hasattr(config, "get"): name_or_path = config.get("_name_or_path") - loader = getattr(type(module), "load_config", None) + # Look up load_config on the instance, not the class: torch.compile's OptimizedModule and other + # attribute-forwarding wrappers expose the original module's load_config. + loader = getattr(module, "load_config", None) if not name_or_path or not callable(loader): return None try: diff --git a/tests/pipelines/cosmos/test_cosmos3_mixed_precision.py b/tests/pipelines/cosmos/test_cosmos3_mixed_precision.py new file mode 100644 index 000000000000..050c07dc9153 --- /dev/null +++ b/tests/pipelines/cosmos/test_cosmos3_mixed_precision.py @@ -0,0 +1,94 @@ +# Copyright 2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import json +import os + +import pytest +import torch +from torch import nn + +from diffusers import ConfigMixin, ModelMixin +from diffusers.configuration_utils import register_to_config +from diffusers.pipelines.cosmos.mixed_precision import FIRST_LAST_N_FP8_POLICY, Cosmos3MixedPrecisionConfig + + +class _TinyModelOptFP8Transformer(ModelMixin, ConfigMixin): + config_name = "config.json" + + @register_to_config + def __init__(self, dim: int = 4): + super().__init__() + self.proj = nn.Linear(dim, dim) + + def forward(self, hidden_states): + return self.proj(hidden_states) + + +@pytest.fixture +def transformer_with_checkpoint_policy(tmp_path): + """A model whose on-disk config declares the ModelOpt FP8 step policy, like a `from_pretrained` checkpoint.""" + model = _TinyModelOptFP8Transformer() + model.save_config(tmp_path) + config_path = os.path.join(tmp_path, "config.json") + with open(config_path) as f: + config = json.load(f) + # `ModelMixin.from_pretrained` strips `quantization_config` from the in-memory config, so the on-disk + # `config.json` (found through `_name_or_path`) is the only source of `runtime.diffusion_step_policy`. + config["quantization_config"] = { + "quant_method": "modelopt", + "quant_algo": "FP8", + "runtime": {"diffusion_step_policy": FIRST_LAST_N_FP8_POLICY}, + } + with open(config_path, "w") as f: + json.dump(config, f) + model.register_to_config(_name_or_path=str(tmp_path)) + return model + + +def test_resolve_reads_checkpoint_policy(transformer_with_checkpoint_policy): + policy = Cosmos3MixedPrecisionConfig.resolve(transformer_with_checkpoint_policy) + + assert policy.format == "fp8" + assert (policy.first_steps, policy.last_steps) == (3, 3) + + +def test_resolve_reads_checkpoint_policy_through_torch_compile(transformer_with_checkpoint_policy): + # `pipe.transformer = torch.compile(pipe.transformer)` replaces the model with an `OptimizedModule`, which has no + # `load_config`. The checkpoint policy must still resolve, not silently fall back to all-W8A8. + compiled = torch.compile(transformer_with_checkpoint_policy, backend="eager") + assert type(compiled) is not type(transformer_with_checkpoint_policy) + + assert Cosmos3MixedPrecisionConfig.resolve(compiled) == Cosmos3MixedPrecisionConfig.resolve( + transformer_with_checkpoint_policy + ) + + +def test_resolve_reads_checkpoint_policy_through_forwarding_wrapper(transformer_with_checkpoint_policy): + # Any wrapper that forwards attribute access must resolve the same policy as the bare model. + class ForwardingWrapper: + def __init__(self, module): + self._module = module + + def __getattr__(self, name): + return getattr(self._module, name) + + def named_modules(self): + return self._module.named_modules() + + wrapped = ForwardingWrapper(transformer_with_checkpoint_policy) + + assert Cosmos3MixedPrecisionConfig.resolve(wrapped) == Cosmos3MixedPrecisionConfig.resolve( + transformer_with_checkpoint_policy + ) From b30b5aaf9cf6a34fcc9a6679626e9ff82a217ca9 Mon Sep 17 00:00:00 2001 From: Yiming Zhao Date: Thu, 3 Dec 2026 11:04:41 -0800 Subject: [PATCH 2/2] [Cosmos3] Test checkpoint policy resolution through torch.compile Move the regression test into test_cosmos3.py as a single pipeline test that uses the real Cosmos3OmniTransformer. --- tests/pipelines/cosmos/test_cosmos3.py | 22 +++++ .../cosmos/test_cosmos3_mixed_precision.py | 94 ------------------- 2 files changed, 22 insertions(+), 94 deletions(-) delete mode 100644 tests/pipelines/cosmos/test_cosmos3_mixed_precision.py diff --git a/tests/pipelines/cosmos/test_cosmos3.py b/tests/pipelines/cosmos/test_cosmos3.py index 5660698405c3..29bcf6dd7760 100644 --- a/tests/pipelines/cosmos/test_cosmos3.py +++ b/tests/pipelines/cosmos/test_cosmos3.py @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +import json from contextlib import contextmanager from unittest import mock @@ -27,6 +28,7 @@ Cosmos3OmniTransformer, UniPCMultistepScheduler, ) +from diffusers.pipelines.cosmos.mixed_precision import FIRST_LAST_N_FP8_POLICY, Cosmos3MixedPrecisionConfig from diffusers.pipelines.cosmos.pipeline_cosmos3_omni import _preprocess_conditioning_image from ...testing_utils import enable_full_determinism, torch_device @@ -116,6 +118,26 @@ def test_inference(self): assert video[0].shape == self.output_shape + def test_mixed_precision_policy_resolves_through_torch_compile(self, tmp_path): + # `pipe.transformer = torch.compile(pipe.transformer)` wraps the model, and the checkpoint's step policy + # must still resolve, or every step silently runs W8A8 instead of the checkpoint's W8A16 first/last steps. + transformer = self.get_dummy_components()["transformer"] + transformer.save_config(tmp_path) + config_path = tmp_path / "config.json" + config = json.loads(config_path.read_text()) + config["quantization_config"] = { + "quant_method": "modelopt", + "quant_algo": "FP8", + "runtime": {"diffusion_step_policy": FIRST_LAST_N_FP8_POLICY}, + } + config_path.write_text(json.dumps(config)) + # `from_pretrained` records the checkpoint path, and the on-disk config is the only source of the policy. + transformer.register_to_config(_name_or_path=str(tmp_path)) + + policy = Cosmos3MixedPrecisionConfig.resolve(transformer) + assert policy.format == "fp8" + assert Cosmos3MixedPrecisionConfig.resolve(torch.compile(transformer, backend="eager")) == policy + def test_fp32_sampling_state_keeps_transformer_inputs_in_model_dtype(self): pipeline = self.pipeline_class(**self.get_dummy_components()).to(torch_device) pipeline.transformer.to(dtype=torch.float16) diff --git a/tests/pipelines/cosmos/test_cosmos3_mixed_precision.py b/tests/pipelines/cosmos/test_cosmos3_mixed_precision.py deleted file mode 100644 index 050c07dc9153..000000000000 --- a/tests/pipelines/cosmos/test_cosmos3_mixed_precision.py +++ /dev/null @@ -1,94 +0,0 @@ -# Copyright 2026 The HuggingFace Team. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import json -import os - -import pytest -import torch -from torch import nn - -from diffusers import ConfigMixin, ModelMixin -from diffusers.configuration_utils import register_to_config -from diffusers.pipelines.cosmos.mixed_precision import FIRST_LAST_N_FP8_POLICY, Cosmos3MixedPrecisionConfig - - -class _TinyModelOptFP8Transformer(ModelMixin, ConfigMixin): - config_name = "config.json" - - @register_to_config - def __init__(self, dim: int = 4): - super().__init__() - self.proj = nn.Linear(dim, dim) - - def forward(self, hidden_states): - return self.proj(hidden_states) - - -@pytest.fixture -def transformer_with_checkpoint_policy(tmp_path): - """A model whose on-disk config declares the ModelOpt FP8 step policy, like a `from_pretrained` checkpoint.""" - model = _TinyModelOptFP8Transformer() - model.save_config(tmp_path) - config_path = os.path.join(tmp_path, "config.json") - with open(config_path) as f: - config = json.load(f) - # `ModelMixin.from_pretrained` strips `quantization_config` from the in-memory config, so the on-disk - # `config.json` (found through `_name_or_path`) is the only source of `runtime.diffusion_step_policy`. - config["quantization_config"] = { - "quant_method": "modelopt", - "quant_algo": "FP8", - "runtime": {"diffusion_step_policy": FIRST_LAST_N_FP8_POLICY}, - } - with open(config_path, "w") as f: - json.dump(config, f) - model.register_to_config(_name_or_path=str(tmp_path)) - return model - - -def test_resolve_reads_checkpoint_policy(transformer_with_checkpoint_policy): - policy = Cosmos3MixedPrecisionConfig.resolve(transformer_with_checkpoint_policy) - - assert policy.format == "fp8" - assert (policy.first_steps, policy.last_steps) == (3, 3) - - -def test_resolve_reads_checkpoint_policy_through_torch_compile(transformer_with_checkpoint_policy): - # `pipe.transformer = torch.compile(pipe.transformer)` replaces the model with an `OptimizedModule`, which has no - # `load_config`. The checkpoint policy must still resolve, not silently fall back to all-W8A8. - compiled = torch.compile(transformer_with_checkpoint_policy, backend="eager") - assert type(compiled) is not type(transformer_with_checkpoint_policy) - - assert Cosmos3MixedPrecisionConfig.resolve(compiled) == Cosmos3MixedPrecisionConfig.resolve( - transformer_with_checkpoint_policy - ) - - -def test_resolve_reads_checkpoint_policy_through_forwarding_wrapper(transformer_with_checkpoint_policy): - # Any wrapper that forwards attribute access must resolve the same policy as the bare model. - class ForwardingWrapper: - def __init__(self, module): - self._module = module - - def __getattr__(self, name): - return getattr(self._module, name) - - def named_modules(self): - return self._module.named_modules() - - wrapped = ForwardingWrapper(transformer_with_checkpoint_policy) - - assert Cosmos3MixedPrecisionConfig.resolve(wrapped) == Cosmos3MixedPrecisionConfig.resolve( - transformer_with_checkpoint_policy - )