diff --git a/miles/backends/fsdp_utils/model_backend.py b/miles/backends/fsdp_utils/model_backend.py index ff470e54c..0a0a6d66b 100644 --- a/miles/backends/fsdp_utils/model_backend.py +++ b/miles/backends/fsdp_utils/model_backend.py @@ -21,10 +21,11 @@ import functools import importlib import logging +import os from dataclasses import replace import torch -from diffusers import DiffusionPipeline +from diffusers import DiffusionPipeline, ModularPipeline from .models.parallel_plan import FSDPParallelPlan from .sequence_parallel.diffusers_dispatch import install_diffusers_usp_patch @@ -189,9 +190,19 @@ def load_component( master_dtype: torch.dtype, materialize_weights: bool, ) -> torch.nn.Module: - model_cls = self._resolve_component_class(checkpoint_path, component) + """Load one component of a Diffusers checkpoint by itself. + + Components load individually via ``cls.from_pretrained(subfolder=...)`` rather + than through ``DiffusionPipeline.from_pretrained`` with the siblings passed as + ``None``: pipelines that declare a component optional with a ``None`` default + (e.g. ``WanPipeline.transformer``/``transformer_2``) drop it from + ``expected_modules``, so the ``None`` is silently ignored and the sibling is + loaded from disk anyway — on every rank, and with ``low_cpu_mem_usage=False`` + it also trips diffusers' ``_keep_in_fp32_modules`` guard. + """ + model_cls, subfolder = self._resolve_component(checkpoint_path, component) kwargs = { - "subfolder": component, + "subfolder": subfolder, "torch_dtype": master_dtype, "low_cpu_mem_usage": materialize_weights, } @@ -210,27 +221,43 @@ def load_component( model_cls._keep_in_fp32_modules = keep_in_fp32 @classmethod - def _resolve_component_class(cls, checkpoint_path: str, component: str): - """Resolve ``component``'s class from ``model_index.json``. + def _resolve_component(cls, checkpoint_path: str, component: str) -> tuple[type, str]: + """``component``'s class and its folder under ``checkpoint_path``, from the checkpoint's index. - Components load individually via ``cls.from_pretrained(subfolder=...)`` rather - than through ``DiffusionPipeline.from_pretrained`` with the siblings passed as - ``None``: pipelines that declare a component optional with a ``None`` default - (e.g. ``WanPipeline.transformer``/``transformer_2``) drop it from - ``expected_modules``, so the ``None`` is silently ignored and the sibling is - loaded from disk anyway — on every rank, and with ``low_cpu_mem_usage=False`` - it also trips diffusers' ``_keep_in_fp32_modules`` guard. + The index is the one diffusers' modular loader reads: ``modular_model_index.json`` when the checkpoint has + one, else ``model_index.json``. Weights load from ``checkpoint_path``, not from the repository a loading + spec names. """ - config = DiffusionPipeline.load_config(checkpoint_path) - if component not in config: - raise ValueError(f"pipeline {checkpoint_path} has no component {component!r}") - component_cls = cls._component_class(config[component]) + try: + index, index_name = ModularPipeline.load_config(checkpoint_path), ModularPipeline.config_name + except OSError as error: + if os.path.isfile(os.path.join(checkpoint_path, ModularPipeline.config_name)): + raise + index, index_name = DiffusionPipeline.load_config(checkpoint_path), DiffusionPipeline.config_name + logger.info("%s: read %s; no %s (%s)", checkpoint_path, index_name, ModularPipeline.config_name, error) + if component not in index: + raise ValueError(f"{index_name} of {checkpoint_path} has no component {component!r}") + spec = index[component] + component_cls = cls._component_class(spec) if component_cls is None: raise ValueError( - f"cannot resolve the class for component {component!r} of {checkpoint_path} " - f"from spec {config[component]!r}; remote-code components are not supported" + f"cannot resolve the class for component {component!r} from {index_name} of {checkpoint_path}: " + f"spec {spec!r} names no class an installed library provides; remote-code components are not supported" + ) + if len(spec) == 2: + return component_cls, component + loading_spec = spec[2] if isinstance(spec[2], dict) else {} + subfolder, variant = loading_spec.get("subfolder"), loading_spec.get("variant") + if not subfolder: + raise ValueError( + f"component {component!r} names no subfolder in {index_name} of {checkpoint_path}: {spec!r}" + ) + if variant is not None: + raise ValueError( + f"component {component!r} names the weight variant {variant!r} in {index_name} of {checkpoint_path}; " + f"loading a variant is untested" ) - return component_cls + return component_cls, subfolder @staticmethod def _component_class(spec): diff --git a/miles/backends/fsdp_utils/models/__init__.py b/miles/backends/fsdp_utils/models/__init__.py index 5828ad95f..0dd3e05dd 100644 --- a/miles/backends/fsdp_utils/models/__init__.py +++ b/miles/backends/fsdp_utils/models/__init__.py @@ -2,7 +2,8 @@ Onboarding a model family: -- **Diffusers checkpoint** (has ``model_index.json``): +- **Diffusers checkpoint** (has ``modular_model_index.json`` or ``model_index.json``; the modular one is read + when shipped): ``DiffusersModelBackend`` loads it; add ``models/diffusers//parallel_plan.py`` for its FSDP precision plan. diff --git a/tests/fast/backends/fsdp_utils/test_model_backend.py b/tests/fast/backends/fsdp_utils/test_model_backend.py index ee653ff55..c41766421 100644 --- a/tests/fast/backends/fsdp_utils/test_model_backend.py +++ b/tests/fast/backends/fsdp_utils/test_model_backend.py @@ -9,12 +9,56 @@ register_cpu_ci(est_time=15, suite="stage-a-cpu", labels=[]) import json +import logging +import diffusers +import huggingface_hub +import pytest import torch +from miles.backends.fsdp_utils import model_backend from miles.backends.fsdp_utils.model_backend import BaseModelBackend, DiffusersModelBackend, MilesModelBackend from miles.backends.fsdp_utils.models.diffusers import load_fsdp_parallel_plan +# MiniMaxAI/MiniMax-H3-Image at 8ced6006: transformer/ holds the engine's native layout +_H3_IMAGE_INDEX = {"_class_name": "MiniMaxH3ImagePipeline", "transformer": ["diffusers", "MiniMaxH3DiTModel"]} +_H3_IMAGE_MODULAR_INDEX = { + "_class_name": "MiniMaxH3ImageModularPipeline", + "transformer": [ + "diffusers", + "MiniMaxH3ImageTransformer2DModel", + { + "type_hint": ["diffusers", "MiniMaxH3ImageTransformer2DModel"], + "pretrained_model_name_or_path": "MiniMaxAI/MiniMax-H3-Image", + "subfolder": "transformer_diffusers", + "variant": None, + "revision": None, + }, + ], +} +# MiniMaxAI/MiniMax-H3 at 42ed227e: both index files carry these entries +_H3_INDEX = { + "_class_name": "MiniMaxH3ModularPipeline", + "transformer_ref": [ + "diffusers", + "MiniMaxH3Transformer3DModel", + { + "type_hint": ["diffusers", "MiniMaxH3Transformer3DModel"], + "pretrained_model_name_or_path": "MiniMaxAI/MiniMax-H3", + "subfolder": "transformer_ref", + "variant": None, + "revision": None, + }, + ], +} + + +def _write_checkpoint(path, index, modular_index=None): + (path / "model_index.json").write_text(json.dumps(index)) + if modular_index is not None: + (path / "modular_model_index.json").write_text(json.dumps(modular_index)) + return str(path) + class _RecordingModel(torch.nn.Module): def __init__(self): @@ -83,3 +127,102 @@ def test_component_loads_from_its_own_role_checkpoint(self, tmp_path): "torch_dtype": torch.float32, "low_cpu_mem_usage": True, } + + @pytest.mark.parametrize( + ("index", "modular_index", "component", "expected"), + [ + ( + _H3_IMAGE_INDEX, + _H3_IMAGE_MODULAR_INDEX, + "transformer", + (diffusers.MiniMaxH3ImageTransformer2DModel, "transformer_diffusers"), + ), + (_H3_INDEX, _H3_INDEX, "transformer_ref", (diffusers.MiniMaxH3Transformer3DModel, "transformer_ref")), + ], + ids=["h3-image", "h3"], + ) + def test_modular_index_names_the_class_and_the_folder(self, tmp_path, index, modular_index, component, expected): + """MiniMax-H3-Image's root index names classes diffusers does not have, in a folder of another layout.""" + checkpoint = _write_checkpoint(tmp_path, index, modular_index) + + assert DiffusersModelBackend._resolve_component(checkpoint, component) == expected + + def test_component_loads_from_the_checkpoint_not_the_repository_its_spec_names(self, tmp_path): + """A local mirror or a fine-tuned copy keeps the release's index; following it would train the release.""" + spec = {"pretrained_model_name_or_path": "org/release", "subfolder": "transformer_diffusers"} + checkpoint = _write_checkpoint( + tmp_path, _H3_IMAGE_INDEX, {"transformer": [__name__, "_CheckpointComponent", spec]} + ) + + model = DiffusersModelBackend(None).load_component( + "transformer", checkpoint_path=checkpoint, master_dtype=torch.float32, materialize_weights=True + ) + + assert model.checkpoint_path == checkpoint + assert model.load_kwargs["subfolder"] == "transformer_diffusers" + + def test_loading_spec_without_a_subfolder_is_rejected(self, tmp_path): + checkpoint = _write_checkpoint( + tmp_path, _H3_IMAGE_INDEX, {"transformer": [__name__, "_CheckpointComponent", {"subfolder": None}]} + ) + + with pytest.raises(ValueError, match="names no subfolder"): + DiffusersModelBackend._resolve_component(checkpoint, "transformer") + + def test_loading_spec_with_a_weight_variant_is_rejected(self, tmp_path): + """Loading without the variant could read the repository's other weights of the same component.""" + spec = [__name__, "_CheckpointComponent", {"subfolder": "transformer", "variant": "fp16"}] + checkpoint = _write_checkpoint(tmp_path, _H3_IMAGE_INDEX, {"transformer": spec}) + + with pytest.raises(ValueError, match="weight variant 'fp16'"): + DiffusersModelBackend._resolve_component(checkpoint, "transformer") + + def test_checkpoint_without_a_readable_modular_index_reads_model_index_and_logs_it( + self, monkeypatch, tmp_path, caplog + ): + """A cached classic checkpoint must still resolve offline, and the fall-through must not be silent.""" + caplog.set_level(logging.INFO, logger=model_backend.__name__) + monkeypatch.setattr(huggingface_hub.constants, "HF_HUB_OFFLINE", True) + monkeypatch.setattr(huggingface_hub.constants, "HF_HUB_CACHE", str(tmp_path)) + monkeypatch.setattr( + model_backend.DiffusionPipeline, + "load_config", + lambda checkpoint_path: {"transformer": [__name__, "_CheckpointComponent"]}, + ) + + assert DiffusersModelBackend._resolve_component("org/classic", "transformer") == ( + _CheckpointComponent, + "transformer", + ) + [record] = caplog.records + assert "model_index.json" in record.getMessage() and "modular_model_index.json" in record.getMessage() + + def test_cached_modular_checkpoint_resolves_from_its_modular_index_while_the_hub_is_offline( + self, monkeypatch, tmp_path + ): + """Falling through to the root index here would name the engine's native classes for MiniMax-H3-Image.""" + snapshot = tmp_path / "models--org--modular" / "snapshots" / ("0" * 40) + snapshot.mkdir(parents=True) + (snapshot / "modular_model_index.json").write_text(json.dumps(_H3_IMAGE_MODULAR_INDEX)) + refs = tmp_path / "models--org--modular" / "refs" + refs.mkdir() + (refs / "main").write_text("0" * 40) + monkeypatch.setattr(huggingface_hub.constants, "HF_HUB_OFFLINE", True) + monkeypatch.setattr(huggingface_hub.constants, "HF_HUB_CACHE", str(tmp_path)) + + assert DiffusersModelBackend._resolve_component("org/modular", "transformer") == ( + diffusers.MiniMaxH3ImageTransformer2DModel, + "transformer_diffusers", + ) + + def test_missing_local_checkpoint_is_reported_as_a_missing_directory(self, tmp_path): + """A mistyped path is not a repo id; the probe must not turn it into a repo-id error.""" + with pytest.raises(OSError, match="not the path to a directory containing a model_index.json"): + DiffusersModelBackend._resolve_component(str(tmp_path / "missing"), "transformer") + + def test_unresolvable_class_names_the_index_it_was_read_from(self, tmp_path): + """With a partial cache the root index is read; its native class must not look like the modular one's.""" + checkpoint = _write_checkpoint(tmp_path, {"transformer": ["diffusers", "NoSuchNativeModel"]}) + + with pytest.raises(ValueError, match="from model_index.json of"): + DiffusersModelBackend._resolve_component(checkpoint, "transformer")