From 271bcb1e3f2a0c79d10c1fcb8bc27be2f7108075 Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Mon, 23 Nov 2026 00:23:04 -0800 Subject: [PATCH 1/3] feat(fsdp): the backend names the safetensors files that hold a component, and a build without weights gets the dtypes a load gives Co-authored-by: rockdu --- miles/backends/fsdp_utils/model_backend.py | 72 +++++- .../backends/fsdp_utils/test_model_backend.py | 236 ++++++++++++++++++ .../fsdp_utils/test_reference_models.py | 4 + 3 files changed, 307 insertions(+), 5 deletions(-) diff --git a/miles/backends/fsdp_utils/model_backend.py b/miles/backends/fsdp_utils/model_backend.py index ff470e54c..39f88b305 100644 --- a/miles/backends/fsdp_utils/model_backend.py +++ b/miles/backends/fsdp_utils/model_backend.py @@ -20,11 +20,16 @@ import abc import functools import importlib +import json import logging +import os from dataclasses import replace +from itertools import chain +from pathlib import Path import torch from diffusers import DiffusionPipeline +from diffusers.utils import SAFE_WEIGHTS_INDEX_NAME, SAFETENSORS_WEIGHTS_NAME from .models.parallel_plan import FSDPParallelPlan from .sequence_parallel.diffusers_dispatch import install_diffusers_usp_patch @@ -33,6 +38,36 @@ logger = logging.getLogger(__name__) +def diffusers_weight_files(checkpoint_path: str, component: str) -> list[Path] | None: + """The safetensors files ``from_pretrained`` reads a component from with no variant, or None for other weights. + + The ones the component's index lists, else its single file; a Hub id is resolved to its snapshot first. + """ + stem = SAFETENSORS_WEIGHTS_NAME.removesuffix(".safetensors") + is_local = os.path.isdir(checkpoint_path) + if not is_local: + from huggingface_hub import snapshot_download + from huggingface_hub.errors import HFValidationError, LocalEntryNotFoundError, RepositoryNotFoundError + + patterns = [f"{component}/{SAFETENSORS_WEIGHTS_NAME}*", f"{component}/{stem}-*.safetensors"] + try: + checkpoint_path = snapshot_download(checkpoint_path, allow_patterns=patterns) + except (HFValidationError, LocalEntryNotFoundError, RepositoryNotFoundError): + # Not a folder, and no repo the Hub or the offline cache resolves: load_component says so. + return None + folder = Path(checkpoint_path) / component + index = folder / SAFE_WEIGHTS_INDEX_NAME + if index.is_file(): + names = set(json.loads(index.read_text())["weight_map"].values()) + elif is_local and (Path(checkpoint_path) / SAFETENSORS_WEIGHTS_NAME).is_file(): + # In a local folder from_pretrained takes a single weights file at the root before the component's. + return None + else: + names = {SAFETENSORS_WEIGHTS_NAME} + files = [folder / name for name in sorted(names)] + return files if all(file.is_file() for file in files) else None + + class BaseModelBackend(abc.ABC): """Contract consumed by the FSDP actor for model-family integration.""" @@ -54,6 +89,14 @@ def load_component( ) -> torch.nn.Module: raise NotImplementedError + def safetensors_files(self, component: str, *, checkpoint_path: str) -> list[Path] | None: + """Local safetensors files every rank can read its shards of the component from; None: rank 0 loads it. + + They hold exactly what ``load_component`` loads, and such a backend gives every tensor its final dtype when + it builds without weights: the file values are cast into those dtypes, no rank loads a model to copy from. + """ + return None + @abc.abstractmethod def enable_gradient_checkpointing(self, model: torch.nn.Module) -> None: raise NotImplementedError @@ -196,18 +239,37 @@ def load_component( "low_cpu_mem_usage": materialize_weights, } - # Non-rank0 loads with low_cpu_mem_usage=False so the ambient meta-device - # context keeps params on meta; diffusers forbids that combination when the - # class pins modules to fp32, so disable the pin for the duration (dtypes are - # re-synced from rank0 afterwards, see ``sync_model_dtypes``). + # A build without weights loads with low_cpu_mem_usage=False so the ambient meta-device context keeps + # the parameters on meta; diffusers forbids that combination when the class pins modules to fp32, so the + # pin is off for the call and applied afterwards. keep_in_fp32 = getattr(model_cls, "_keep_in_fp32_modules", None) if not materialize_weights and keep_in_fp32 is not None: model_cls._keep_in_fp32_modules = None try: - return model_cls.from_pretrained(checkpoint_path, **kwargs) + model = model_cls.from_pretrained(checkpoint_path, **kwargs) finally: if not materialize_weights and keep_in_fp32 is not None: model_cls._keep_in_fp32_modules = keep_in_fp32 + if not materialize_weights: + self._cast_state_as_a_load_does(model, master_dtype, keep_in_fp32 or []) + return model + + @staticmethod + def _cast_state_as_a_load_does(model: torch.nn.Module, master_dtype: torch.dtype, keep_in_fp32: list[str]) -> None: + """Give every floating tensor of the state dict the dtype a load with weights gives it. + + diffusers casts each one to the master dtype, or to fp32 under the class's pin + (``load_model_dict_into_meta``). A build without weights has the constructor's dtypes, and every rank may + be built that way, so no rank's loaded model is there to copy them from. + """ + saved = set(model.state_dict()) + for name, tensor in chain(model.named_parameters(), model.named_buffers()): + if name in saved and tensor.is_floating_point(): + pinned = any(module in name.split(".") for module in keep_in_fp32) + tensor.data = tensor.data.to(torch.float32 if pinned else master_dtype) + + def safetensors_files(self, component: str, *, checkpoint_path: str) -> list[Path] | None: + return diffusers_weight_files(checkpoint_path, component) @classmethod def _resolve_component_class(cls, checkpoint_path: str, component: str): diff --git a/tests/fast/backends/fsdp_utils/test_model_backend.py b/tests/fast/backends/fsdp_utils/test_model_backend.py index ee653ff55..fce4a21e2 100644 --- a/tests/fast/backends/fsdp_utils/test_model_backend.py +++ b/tests/fast/backends/fsdp_utils/test_model_backend.py @@ -9,10 +9,18 @@ register_cpu_ci(est_time=15, suite="stage-a-cpu", labels=[]) import json +from itertools import chain +import httpx +import pytest import torch +from diffusers import ConfigMixin, ModelMixin, SD3Transformer2DModel, WanTransformer3DModel +from diffusers.configuration_utils import register_to_config +from huggingface_hub.errors import LocalEntryNotFoundError, RepositoryNotFoundError +from safetensors.torch import load_file, save_file from miles.backends.fsdp_utils.model_backend import BaseModelBackend, DiffusersModelBackend, MilesModelBackend +from miles.backends.fsdp_utils.model_loader import model_init_context from miles.backends.fsdp_utils.models.diffusers import load_fsdp_parallel_plan @@ -39,6 +47,151 @@ def from_pretrained(cls, checkpoint_path, **kwargs): return model +class _PinnedComponent(torch.nn.Module): + _keep_in_fp32_modules = ["norm"] + + def __init__(self): + super().__init__() + self.proj = torch.nn.Linear(2, 2) + self.norm = torch.nn.LayerNorm(2) + + @classmethod + def from_pretrained(cls, checkpoint_path, *, torch_dtype, **kwargs): + assert cls._keep_in_fp32_modules is None + return cls().to(torch_dtype) + + +WEIGHTS_FILE = "diffusion_pytorch_model.safetensors" + + +class _PinnedBufferModel(ModelMixin, ConfigMixin): + """Persistent buffers (BatchNorm's running statistics) under a module the class pins to fp32.""" + + _keep_in_fp32_modules = ["norm"] + + @register_to_config + def __init__(self): + super().__init__() + self.proj = torch.nn.Linear(2, 2) + self.norm = torch.nn.BatchNorm1d(2) + + +class _TransientBufferModel(ModelMixin, ConfigMixin): + """A buffer outside the state dict, made in fp32 whatever the default dtype (H3's and Cosmos3's inv_freq).""" + + @register_to_config + def __init__(self): + super().__init__() + self.proj = torch.nn.Linear(2, 2) + self.register_buffer("inv_freq", torch.arange(4, dtype=torch.float32) / 10, persistent=False) + + +def _tiny_sd3(): + # Its pos_embed is a persistent buffer the constructor makes in fp32 whatever the default dtype. + return SD3Transformer2DModel( + sample_size=8, + patch_size=2, + in_channels=4, + num_layers=1, + attention_head_dim=8, + num_attention_heads=2, + joint_attention_dim=16, + caption_projection_dim=16, + pooled_projection_dim=16, + out_channels=4, + pos_embed_max_size=8, + ) + + +def _tiny_wan(): + # Pins modules to fp32 and has buffers outside the state dict (the rope tables). + return WanTransformer3DModel( + patch_size=(1, 2, 2), + num_attention_heads=2, + attention_head_dim=12, + in_channels=4, + out_channels=4, + text_dim=16, + freq_dim=16, + ffn_dim=32, + num_layers=1, + cross_attn_norm=True, + rope_max_seq_len=32, + ) + + +@pytest.mark.parametrize( + "make, class_spec", + [ + pytest.param(_tiny_sd3, ["diffusers", "SD3Transformer2DModel"], id="a persistent buffer made in fp32"), + pytest.param(_tiny_wan, ["diffusers", "WanTransformer3DModel"], id="modules pinned to fp32"), + pytest.param(_PinnedBufferModel, [__name__, "_PinnedBufferModel"], id="a persistent buffer under the pin"), + pytest.param(_TransientBufferModel, [__name__, "_TransientBufferModel"], id="a buffer no load casts"), + ], +) +@pytest.mark.parametrize("master_dtype", [torch.bfloat16, torch.float16, torch.float32]) +def test_a_component_built_without_weights_has_the_dtypes_a_load_with_weights_gives( + tmp_path, make, class_spec, master_dtype +): + # Every rank may build on meta and read its shards from the files, so no loaded model is there to copy from. + make().save_pretrained(tmp_path / "transformer") + (tmp_path / "model_index.json").write_text( + json.dumps({"_class_name": "DiffusionPipeline", "transformer": class_spec}) + ) + dtypes = {} + for materialize_weights in (True, False): + with model_init_context(materialize_weights=materialize_weights): + model = DiffusersModelBackend(None).load_component( + "transformer", + checkpoint_path=str(tmp_path), + master_dtype=master_dtype, + materialize_weights=materialize_weights, + ) + tensors = chain(model.named_parameters(), model.named_buffers()) + dtypes[materialize_weights] = {name: tensor.dtype for name, tensor in tensors} + assert dtypes[False] == dtypes[True] + + +def _save_as_pipeline(model, path, **kwargs): + model.save_pretrained(path / "transformer", **kwargs) + (path / "model_index.json").write_text( + json.dumps({"_class_name": "DiffusionPipeline", "transformer": ["diffusers", "SD3Transformer2DModel"]}) + ) + + +def _load_with_weights(path): + with model_init_context(materialize_weights=True): + return DiffusersModelBackend(None).load_component( + "transformer", checkpoint_path=str(path), master_dtype=torch.float32, materialize_weights=True + ) + + +@pytest.mark.parametrize("sharded", [False, True], ids=["the single file", "the files the index lists"]) +@pytest.mark.parametrize("variant", [False, True], ids=["alone", "beside a variant with other weights"]) +def test_the_named_files_hold_the_state_a_load_with_weights_gives(tmp_path, sharded, variant): + # safetensors_files mirrors which files diffusers' from_pretrained reads; this ties it to diffusers itself. + _save_as_pipeline(_tiny_sd3(), tmp_path, max_shard_size="20KB" if sharded else "10GB") + if variant: + _tiny_sd3().save_pretrained(tmp_path / "transformer", variant="fp16") + + files = DiffusersModelBackend(None).safetensors_files("transformer", checkpoint_path=str(tmp_path)) + + assert (len(files) > 1) is sharded + named = {name: tensor for file in files for name, tensor in load_file(file).items()} + loaded = _load_with_weights(tmp_path).state_dict() + assert named.keys() == loaded.keys() and all(torch.equal(named[name], loaded[name]) for name in named) + + +def test_a_load_with_weights_reads_the_weights_file_at_the_root_of_a_local_checkpoint(tmp_path): + # Why such a checkpoint names no files: diffusers reads the root's file, not the component's. + _save_as_pipeline(_tiny_sd3(), tmp_path) + component = load_file(tmp_path / "transformer" / "diffusion_pytorch_model.safetensors") + save_file({name: torch.zeros_like(tensor) for name, tensor in component.items()}, tmp_path / WEIGHTS_FILE) + + assert DiffusersModelBackend(None).safetensors_files("transformer", checkpoint_path=str(tmp_path)) is None + assert all(tensor.count_nonzero() == 0 for tensor in _load_with_weights(tmp_path).state_dict().values()) + + class TestBackendHierarchy: def test_concrete_backends_are_sibling_implementations(self): assert issubclass(MilesModelBackend, BaseModelBackend) @@ -83,3 +236,86 @@ def test_component_loads_from_its_own_role_checkpoint(self, tmp_path): "torch_dtype": torch.float32, "low_cpu_mem_usage": True, } + + def test_a_component_built_without_weights_keeps_its_fp32_modules(self, tmp_path): + # Every rank may build on meta, so rank 0's loaded dtypes are not there to copy the fp32 pin from. + (tmp_path / "model_index.json").write_text( + json.dumps({"_class_name": "DiffusionPipeline", "transformer": [__name__, "_PinnedComponent"]}) + ) + + model = DiffusersModelBackend(None).load_component( + "transformer", checkpoint_path=str(tmp_path), master_dtype=torch.bfloat16, materialize_weights=False + ) + + assert {name: parameter.dtype for name, parameter in model.named_parameters()} == { + "proj.weight": torch.bfloat16, + "proj.bias": torch.bfloat16, + "norm.weight": torch.float32, + "norm.bias": torch.float32, + } + assert _PinnedComponent._keep_in_fp32_modules == ["norm"] + + def test_a_hub_checkpoint_resolves_to_the_weight_files_of_its_snapshot(self, tmp_path, monkeypatch): + folder = tmp_path / "transformer" + folder.mkdir() + (folder / "diffusion_pytorch_model.safetensors").touch() + (folder / "diffusion_pytorch_model.fp16.safetensors").touch() + downloads = [] + + def snapshot_download(repo_id, *, allow_patterns): + downloads.append((repo_id, allow_patterns)) + return str(tmp_path) + + monkeypatch.setattr("huggingface_hub.snapshot_download", snapshot_download) + + files = DiffusersModelBackend(None).safetensors_files("transformer", checkpoint_path="org/model") + + assert files == [folder / "diffusion_pytorch_model.safetensors"] + assert downloads == [ + ( + "org/model", + [ + "transformer/diffusion_pytorch_model.safetensors*", + "transformer/diffusion_pytorch_model-*.safetensors", + ], + ) + ] + + def test_a_weights_file_at_the_root_of_a_local_checkpoint_leaves_the_load_to_rank_0(self, tmp_path): + # from_pretrained reads /diffusion_pytorch_model.safetensors before the component's own file. + (tmp_path / "transformer").mkdir() + (tmp_path / "transformer" / "diffusion_pytorch_model.safetensors").touch() + backend = DiffusersModelBackend(None) + assert backend.safetensors_files("transformer", checkpoint_path=str(tmp_path)) == [ + tmp_path / "transformer" / "diffusion_pytorch_model.safetensors" + ] + + (tmp_path / "diffusion_pytorch_model.safetensors").touch() + + assert backend.safetensors_files("transformer", checkpoint_path=str(tmp_path)) is None + + def test_a_checkpoint_that_is_neither_a_folder_nor_a_repo_id_names_no_files(self, tmp_path): + # load_component then reports the path, as it does without this hook. + backend = DiffusersModelBackend(None) + assert backend.safetensors_files("transformer", checkpoint_path=str(tmp_path / "missing")) is None + + @pytest.mark.parametrize( + "error", + [ + pytest.param(LocalEntryNotFoundError("no cached snapshot"), id="offline and not in the cache"), + pytest.param( + RepositoryNotFoundError( + "404", response=httpx.Response(404, request=httpx.Request("GET", "https://huggingface.co")) + ), + id="no such repo", + ), + ], + ) + def test_a_repo_id_that_does_not_resolve_names_no_files(self, monkeypatch, error): + # A mistyped relative folder such as ckpts/h3 parses as a repo id; load_component names it in its error. + def snapshot_download(repo_id, *, allow_patterns): + raise error + + monkeypatch.setattr("huggingface_hub.snapshot_download", snapshot_download) + + assert DiffusersModelBackend(None).safetensors_files("transformer", checkpoint_path="ckpts/h3") is None diff --git a/tests/fast/backends/fsdp_utils/test_reference_models.py b/tests/fast/backends/fsdp_utils/test_reference_models.py index e90e271a2..9181e5018 100644 --- a/tests/fast/backends/fsdp_utils/test_reference_models.py +++ b/tests/fast/backends/fsdp_utils/test_reference_models.py @@ -78,6 +78,9 @@ def load_component(self, component, *, checkpoint_path, master_dtype, materializ model.block.proj.weight.fill_(value) return model + def safetensors_files(self, component, *, checkpoint_path): + return None + def fsdp_parallel_plan(self, model): return FSDPParallelPlan(no_split_modules=("TinyBlock",)) @@ -204,6 +207,7 @@ def unsharded_model_loader(monkeypatch): calls = [] monkeypatch.setattr(model_loader.dist, "get_rank", lambda: 0) monkeypatch.setattr(model_loader.checkpoint, "sync_model_dtypes", lambda model: None) + monkeypatch.setattr(model_loader.checkpoint, "holds_on_every_rank", lambda condition: condition) monkeypatch.setattr(model_loader.checkpoint, "broadcast_full_state_to_fsdp", lambda *args, **kwargs: None) def record_fsdp(model, plan, *, mesh, cpu_offload, args): From 575fe8f0725ff0fd6d9b1ed971d142d5f1405dad Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Mon, 23 Nov 2026 00:23:04 -0800 Subject: [PATCH 2/3] perf(fsdp): every rank reads its own shards from the checkpoint's safetensors files instead of rank 0 loading and broadcasting Co-authored-by: rockdu --- miles/backends/fsdp_utils/checkpoint.py | 62 ++++ miles/backends/fsdp_utils/model_loader.py | 28 +- .../fsdp_utils/_safetensors_load_worker.py | 96 ++++++ .../fsdp_utils/test_safetensors_load.py | 51 ++++ .../fsdp_utils/test_reference_models.py | 2 +- .../fsdp_utils/test_safetensors_load.py | 278 ++++++++++++++++++ 6 files changed, 513 insertions(+), 4 deletions(-) create mode 100644 tests/fast-gpu/backends/fsdp_utils/_safetensors_load_worker.py create mode 100644 tests/fast-gpu/backends/fsdp_utils/test_safetensors_load.py create mode 100644 tests/fast/backends/fsdp_utils/test_safetensors_load.py diff --git a/miles/backends/fsdp_utils/checkpoint.py b/miles/backends/fsdp_utils/checkpoint.py index ff88c4d35..3a9b9b45e 100644 --- a/miles/backends/fsdp_utils/checkpoint.py +++ b/miles/backends/fsdp_utils/checkpoint.py @@ -2,6 +2,8 @@ import json import logging +import os +import tempfile import time from itertools import chain from pathlib import Path @@ -65,6 +67,66 @@ def broadcast_full_state_to_fsdp( buffer.data = buffer.data.to(torch.cuda.current_device()) +def holds_on_every_rank(condition: bool, *, what: str) -> bool: + """Whether ``condition`` holds on every rank; ranks that answer differently all raise, naming ``what`` holds where.""" + conditions = [None] * dist.get_world_size() + dist.all_gather_object(conditions, condition) + if any(conditions) and not all(conditions): + raise ValueError(f"{what} on ranks {[rank for rank, held in enumerate(conditions) if held]} only") + return all(conditions) + + +def _state_mismatch(model: torch.nn.Module, files: list[Path]) -> str | None: + """Why the files cannot hold the model's state dict: a tensor of it missing from the files or saved with another + shape, or a buffer outside the state dict that the constructor left on meta (no file holds it). The files may + hold tensors the model does not have.""" + from safetensors import safe_open + + state = model.state_dict() + on_meta = [name for name, buffer in model.named_buffers() if name not in state and buffer.is_meta] + if on_meta: + return f"buffers outside the state dict are on meta and in no file: {on_meta}" + saved = {} + for file in files: + with safe_open(file, framework="pt") as tensors: + saved.update({name: tuple(tensors.get_slice(name).get_shape()) for name in tensors.keys()}) + differing = sorted(name for name, tensor in state.items() if saved.get(name) != tuple(tensor.shape)) + if differing: + return f"{len(differing)} tensors of the model are missing from the files or saved with another shape, e.g. {differing[:5]}" + return None + + +@torch.no_grad() +def load_safetensors_to_fsdp(model: torch.nn.Module, files: list[Path], *, cpu_offload: bool) -> None: + """Materialize FSDP2 shards by reading each rank's own slice of every parameter from the files. + + A buffer outside the state dict is in no file: it keeps the value the constructor computed on this rank. + """ + # Every rank raises or none does: a rank raising alone would leave the others in the collective read. + mismatches = [None] * dist.get_world_size() + dist.all_gather_object(mismatches, _state_mismatch(model, files)) + if any(mismatches): + found = "; ".join(f"rank {rank}: {why}" for rank, why in enumerate(mismatches) if why) + raise ValueError(f"{[str(file) for file in files]} do not hold the model's state dict ({found})") + device = torch.cuda.current_device() + # Buffers were computed for real on every rank; to_empty would wipe them. One still on meta is in the state + # dict, and the read fills it. to_empty splits a tensor two modules share, so each name keeps its own entry. + buffers = dict(model.named_buffers(remove_duplicate=False)) + model.to_empty(device="cpu" if cpu_offload else device) + for name, buffer in model.named_buffers(remove_duplicate=False): + if not buffers[name].is_meta: + buffer.copy_(buffers[name]) + # The reader takes every safetensors file of one folder, and the files' own folder may hold others (a variant). + with tempfile.TemporaryDirectory() as folder: + for file in files: + os.symlink(file.resolve(), Path(folder) / file.name) + dcp.load(model.state_dict(), storage_reader=dcp.HuggingFaceStorageReader(folder, thread_count=4)) + if cpu_offload: + # CPUOffloadPolicy manages params only; buffers must live on GPU for forward. + for buffer in model.buffers(): + buffer.data = buffer.data.to(device) + + def _is_lora_param_name(name: str) -> bool: return "lora_" in name diff --git a/miles/backends/fsdp_utils/model_loader.py b/miles/backends/fsdp_utils/model_loader.py index ca61e39ec..cffca9c73 100644 --- a/miles/backends/fsdp_utils/model_loader.py +++ b/miles/backends/fsdp_utils/model_loader.py @@ -27,10 +27,22 @@ def load_fsdp_models( trainable: bool = False, cpu_offload: bool = False, ) -> dict[str, torch.nn.Module]: - materialize_weights = dist.get_rank() == 0 - master_dtype = parse_dtype_from_str(args.fsdp_master_dtype) models = {} for component_index, component in enumerate(args.update_weight_target_modules): + # Without LoRA every rank reads its own shards from the safetensors files; else rank 0 loads and broadcasts. + use_lora = lora_adapter_paths is not None or (trainable and args.use_lora) + safetensors_files = ( + None if use_lora else model_backend.safetensors_files(component, checkpoint_path=checkpoint_path) + ) + # Decided before building, on every rank alike: ranks that see the files while others do not raise together. + if not use_lora and not checkpoint.holds_on_every_rank( + safetensors_files is not None, + what=f"the safetensors files of {component} under {checkpoint_path} are seen", + ): + safetensors_files = None + materialize_weights = safetensors_files is None and dist.get_rank() == 0 + master_dtype = parse_dtype_from_str(args.fsdp_master_dtype) + with model_init_context(materialize_weights=materialize_weights): model = model_backend.load_component( component, @@ -52,6 +64,13 @@ def load_fsdp_models( if not materialize_weights and any(not parameter.is_meta for parameter in model.parameters()): raise RuntimeError(f"{component} did not honor meta initialization") + if dist.get_rank() == 0: + source = "rank 0 loads and broadcasts" + if safetensors_files is not None: + source = ( + f"every rank reads {len(safetensors_files)} safetensors files of {safetensors_files[0].parent}" + ) + logger.info(f"FSDP: {component} weights of {checkpoint_path}: {source}") checkpoint.sync_model_dtypes(model) full_state = model.state_dict() if materialize_weights else {} model = apply_fsdp2( @@ -61,7 +80,10 @@ def load_fsdp_models( cpu_offload=cpu_offload, args=args, ) - checkpoint.broadcast_full_state_to_fsdp(model, full_state, cpu_offload=cpu_offload) + if safetensors_files is not None: + checkpoint.load_safetensors_to_fsdp(model, safetensors_files, cpu_offload=cpu_offload) + else: + checkpoint.broadcast_full_state_to_fsdp(model, full_state, cpu_offload=cpu_offload) del full_state train_pipeline_config.postprocess_model_after_materialize(model) if parallel_state.get_optional_mesh("sp") is not None: diff --git a/tests/fast-gpu/backends/fsdp_utils/_safetensors_load_worker.py b/tests/fast-gpu/backends/fsdp_utils/_safetensors_load_worker.py new file mode 100644 index 000000000..43d91dd50 --- /dev/null +++ b/tests/fast-gpu/backends/fsdp_utils/_safetensors_load_worker.py @@ -0,0 +1,96 @@ +"""Two ranks read their own halves of a safetensors checkpoint. + + files hold the state dict --> both ranks on meta --> rows [0:2] on rank 0, rows [2:4] on rank 1, GPU or CPU offload + a buffer no file holds --> the value this rank's constructor computed + another name in the files --> ValueError on both ranks + another name on rank 1 only --> the same error on both ranks: the ranks agree before either reads + files seen by rank 1 only --> ValueError on both ranks before either builds +""" + +import os +import sys +from pathlib import Path +from types import SimpleNamespace + +import torch +import torch.distributed as dist +from tests.fast.backends.fsdp_utils.test_reference_models import TinyPipelineConfig, make_model_loader_args +from tests.fast.backends.fsdp_utils.test_safetensors_load import FileBackend, save_checkpoint, saved_weight +from torch.distributed.device_mesh import init_device_mesh + +from miles.backends.fsdp_utils.model_loader import load_fsdp_models + + +class RankTaggedBackend(FileBackend): + """A buffer outside the state dict whose constructor value differs between the ranks; rank 0 sees no files + under a checkpoint named `rank1-only`.""" + + def safetensors_files(self, component, *, checkpoint_path): + if Path(checkpoint_path).name == "rank1-only" and dist.get_rank() == 0: + return None + return super().safetensors_files(component, checkpoint_path=checkpoint_path) + + def load_component(self, component, **kwargs): + model = super().load_component(component, **kwargs) + model.register_buffer("built_on_rank", torch.tensor(float(dist.get_rank())), persistent=False) + return model + + +def load(mesh, path, cpu_offload): + parallel = SimpleNamespace(get_mesh=lambda name: mesh, get_optional_mesh=lambda name: None) + args, backend = make_model_loader_args(), RankTaggedBackend() + args.use_lora = False + models = load_fsdp_models( + args, backend, TinyPipelineConfig(), parallel, checkpoint_path=str(path), cpu_offload=cpu_offload + ) + for model in models.values(): + shard = model.block.proj.weight.to_local() + assert shard.shape == (2, 3) and shard.dtype == torch.float32 + assert shard.device.type == ("cpu" if cpu_offload else "cuda") + assert model.forward_count.device.type == "cuda" and model.forward_count.item() == 0 + assert model.built_on_rank.device.type == "cuda" and model.built_on_rank.item() == dist.get_rank() + return models, backend.materialize_requests + + +def main(): + torch.cuda.set_device(int(os.environ["LOCAL_RANK"])) + dist.init_process_group("nccl", device_id=torch.device("cuda", torch.cuda.current_device())) + mesh = init_device_mesh("cuda", (dist.get_world_size(),)) + rank, root = dist.get_rank(), Path(sys.argv[1]) + if rank == 0: + save_checkpoint(root / "state") + save_checkpoint(root / "renamed", name="block.proj.kernel") + save_checkpoint(root / "rank1-only") + dist.barrier() + inputs = torch.ones(2, 3, device="cuda") + for cpu_offload in (False, True): + models, materialize_requests = load(mesh, root / "state", cpu_offload) + assert materialize_requests == [False, False] + for component, model in models.items(): + expected = saved_weight(component).float() + assert torch.equal(model.block.proj.weight.to_local().cpu(), expected[2 * rank : 2 * rank + 2]) + with torch.no_grad(): + torch.testing.assert_close(model(inputs).cpu(), (inputs.cpu() @ expected.T).tanh()) + + for path in ("renamed", "renamed" if rank == 1 else "state"): + # Both ranks raise, also when only rank 1's copy holds another name: rank 0 must not enter the read alone. + try: + load(mesh, root / path, cpu_offload) + except ValueError as error: + assert "do not hold the model's state dict" in str(error) and "rank 1" in str(error) + else: + raise AssertionError(f"{path}: expected a ValueError on every rank") + try: + load(mesh, root / "rank1-only", cpu_offload) + except ValueError as error: + assert "are seen on ranks [1] only" in str(error) + else: + raise AssertionError("rank1-only: expected a ValueError on every rank") + dist.barrier() + if rank == 0: + print("OK") + dist.destroy_process_group() + + +if __name__ == "__main__": + main() diff --git a/tests/fast-gpu/backends/fsdp_utils/test_safetensors_load.py b/tests/fast-gpu/backends/fsdp_utils/test_safetensors_load.py new file mode 100644 index 000000000..a739d67bd --- /dev/null +++ b/tests/fast-gpu/backends/fsdp_utils/test_safetensors_load.py @@ -0,0 +1,51 @@ +"""Two ranks read their own shards of a safetensors checkpoint. + + files hold the state dict --> rows [0:2] on rank 0, rows [2:4] on rank 1, GPU-resident and CPU-offloaded + another name in the files --> ValueError on both ranks, also when only one rank's copy differs + files seen by one rank --> ValueError on both ranks +""" + +from tests.ci.ci_register import register_cuda_ci + +register_cuda_ci(est_time=60, suite="stage-b-5-gpu-h200", labels=["fsdp"]) + +import os +import subprocess +import sys +from pathlib import Path + +import pytest +import torch + + +@pytest.mark.skipif(torch.cuda.device_count() < 2, reason="Requires two CUDA devices") +def test_ranks_read_their_own_shards(tmp_path): + result = subprocess.run( + [ + sys.executable, + "-m", + "torch.distributed.run", + "--standalone", + "--nnodes=1", + "--nproc_per_node=2", + str(Path(__file__).with_name("_safetensors_load_worker.py")), + str(tmp_path), + ], + # The worker imports the CPU test's harness from the `tests` package at the repository root. + env={ + **os.environ, + "PYTHONPATH": os.pathsep.join( + filter(None, (str(Path(__file__).resolve().parents[4]), os.environ.get("PYTHONPATH"))) + ), + "PYTHONUNBUFFERED": "1", + }, + capture_output=True, + text=True, + timeout=300, + ) + assert result.returncode == 0, result.stdout + result.stderr + assert "OK" in result.stdout + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v"])) diff --git a/tests/fast/backends/fsdp_utils/test_reference_models.py b/tests/fast/backends/fsdp_utils/test_reference_models.py index 9181e5018..765406e78 100644 --- a/tests/fast/backends/fsdp_utils/test_reference_models.py +++ b/tests/fast/backends/fsdp_utils/test_reference_models.py @@ -207,7 +207,7 @@ def unsharded_model_loader(monkeypatch): calls = [] monkeypatch.setattr(model_loader.dist, "get_rank", lambda: 0) monkeypatch.setattr(model_loader.checkpoint, "sync_model_dtypes", lambda model: None) - monkeypatch.setattr(model_loader.checkpoint, "holds_on_every_rank", lambda condition: condition) + monkeypatch.setattr(model_loader.checkpoint, "holds_on_every_rank", lambda condition, **_: condition) monkeypatch.setattr(model_loader.checkpoint, "broadcast_full_state_to_fsdp", lambda *args, **kwargs: None) def record_fsdp(model, plan, *, mesh, cpu_offload, args): diff --git a/tests/fast/backends/fsdp_utils/test_safetensors_load.py b/tests/fast/backends/fsdp_utils/test_safetensors_load.py new file mode 100644 index 000000000..98920bbcf --- /dev/null +++ b/tests/fast/backends/fsdp_utils/test_safetensors_load.py @@ -0,0 +1,278 @@ +"""Every rank reads its own shards of a diffusers safetensors checkpoint. + + the index's files, or the single file --> every rank on meta --> dcp.load of its own shards + a variant file beside them, a tensor the model lacks --> not read + listed file missing / LoRA --> rank 0 loads and broadcasts, decided before building + files only some ranks see, files that lack a tensor --> ValueError on every rank (never a silent fallback) + or hold another shape, a buffer outside the state + dict left on meta + +FSDP2 is real on a one-rank CPU mesh and the broadcast is recorded; the CUDA worker splits the shards over two ranks. +""" + +from tests.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=10, suite="stage-a-cpu", labels=["fsdp"]) + +import json +import sys +from types import SimpleNamespace + +import pytest +import torch +import torch.distributed as dist +from safetensors.torch import save_file +from tests.fast.backends.fsdp_utils.test_reference_models import ( + TinyBackend, + TinyComponent, + TinyPipelineConfig, + make_model_loader_args, +) +from torch.distributed.device_mesh import init_device_mesh + +from miles.backends.fsdp_utils import checkpoint, model_loader +from miles.backends.fsdp_utils.model_backend import diffusers_weight_files + +BROADCAST_VALUE = 0.75 + + +class FileBackend(TinyBackend): + def safetensors_files(self, component, *, checkpoint_path): + return diffusers_weight_files(checkpoint_path, component) + + def __init__(self): + super().__init__() + self.materialize_requests = [] + + def load_component(self, component, *, checkpoint_path, master_dtype, materialize_weights): + self.materialize_requests.append(materialize_weights) + model = super().load_component( + component, checkpoint_path="actor", master_dtype=master_dtype, materialize_weights=False + ) + if materialize_weights: + with torch.no_grad(): + model.block.proj.weight.fill_(BROADCAST_VALUE) + return model + + +def saved_weight(component): + return torch.arange(12, dtype=torch.bfloat16).reshape(4, 3) + (100 if component == "transformer_2" else 0) + + +def save_checkpoint(path, *, name="block.proj.weight", shape=(4, 3), sharded=True, extra=()): + for component in make_model_loader_args().update_weight_target_modules: + folder = path / component + folder.mkdir(parents=True) + tensors = { + name: saved_weight(component).reshape(shape), + **{extra_name: torch.zeros(2) for extra_name in extra}, + } + if not sharded: + save_file(tensors, folder / "diffusion_pytorch_model.safetensors") + continue + file = "diffusion_pytorch_model-00001-of-00001.safetensors" + save_file(tensors, folder / file) + (folder / "diffusion_pytorch_model.safetensors.index.json").write_text( + json.dumps({"weight_map": {tensor_name: file for tensor_name in tensors}}) + ) + + +def load(monkeypatch, path, *, holds=lambda condition, **_: condition, backend_cls=None, use_lora=False, **kwargs): + broadcasts = [] + monkeypatch.setattr(model_loader.checkpoint, "holds_on_every_rank", holds) + monkeypatch.setattr(model_loader.checkpoint, "sync_model_dtypes", lambda model: None) + monkeypatch.setattr( + model_loader.checkpoint, "broadcast_full_state_to_fsdp", lambda model, state, **_: broadcasts.append(state) + ) + monkeypatch.setattr(torch.cuda, "current_device", lambda: torch.device("cpu")) + dist.init_process_group("gloo", store=dist.HashStore(), rank=0, world_size=1) + try: + mesh = init_device_mesh("cpu", (1,)) + parallel = SimpleNamespace(get_mesh=lambda name: mesh, get_optional_mesh=lambda name: None) + args, backend = make_model_loader_args(), (backend_cls or FileBackend)() + args.use_lora = use_lora + models = model_loader.load_fsdp_models( + args, backend, TinyPipelineConfig(), parallel, checkpoint_path=str(path), **kwargs + ) + return models, backend.materialize_requests, broadcasts + finally: + dist.destroy_process_group() + + +def add_variant_file(path, *, sharded): + save_checkpoint(path, sharded=sharded) + for component in make_model_loader_args().update_weight_target_modules: + # Another shape: a reader that took the variant fails whichever file its folder lists last. + save_file( + {"block.proj.weight": torch.zeros(8, 3)}, path / component / "diffusion_pytorch_model.fp16.safetensors" + ) + + +@pytest.mark.parametrize( + "save", + [ + pytest.param(save_checkpoint, id="the files the index lists"), + pytest.param(lambda path: save_checkpoint(path, sharded=False), id="the single file"), + pytest.param(lambda path: add_variant_file(path, sharded=True), id="a variant beside the listed files"), + pytest.param(lambda path: add_variant_file(path, sharded=False), id="a variant beside the single file"), + pytest.param( + lambda path: save_checkpoint(path, extra=("block.unused",)), id="a tensor the model lacks in the files" + ), + ], +) +def test_every_rank_reads_its_shards_from_the_files(tmp_path, monkeypatch, save): + save(tmp_path) + models, materialize_requests, broadcasts = load(monkeypatch, tmp_path) + assert materialize_requests == [False, False] and broadcasts == [] + for component, model in models.items(): + weight = model.block.proj.weight + assert weight.dtype == torch.float32 + assert torch.equal(weight.to_local(), saved_weight(component).float()) + assert model.forward_count.item() == 0 + torch.testing.assert_close( + model(torch.ones(2, 3)), (torch.ones(2, 3) @ saved_weight(component).float().T).tanh() + ) + assert model.forward_count.item() == 1 + + +def remove_a_listed_file(path): + save_checkpoint(path) + (path / "transformer" / "diffusion_pytorch_model-00001-of-00001.safetensors").unlink() + + +def test_a_checkpoint_with_a_listed_file_missing_is_broadcast(tmp_path, monkeypatch): + # No files to read for the first component: the choice is per component and made before building, so rank 0 + # builds that one with weights once; the second still reads its shards. + remove_a_listed_file(tmp_path) + _, materialize_requests, broadcasts = load(monkeypatch, tmp_path) + assert materialize_requests == [True, False] and len(broadcasts) == 1 + assert set(broadcasts[0]) == {"block.proj.weight"} + assert torch.all(broadcasts[0]["block.proj.weight"] == BROADCAST_VALUE) + + +@pytest.mark.parametrize( + "save", + [ + pytest.param(lambda path: save_checkpoint(path, name="block.proj.kernel"), id="another name"), + pytest.param(lambda path: save_checkpoint(path, shape=(3, 4)), id="another shape"), + ], +) +def test_files_that_do_not_hold_the_state_dict_are_an_error(tmp_path, monkeypatch, save): + # A checkpoint this path does not understand must not silently take the slow path. + save(tmp_path) + with pytest.raises(ValueError, match="do not hold the model's state dict"): + load(monkeypatch, tmp_path) + + +class DerivedBufferComponent(TinyComponent): + """A buffer the constructor derives from a parameter: on meta when the component is built without weights.""" + + persistent = True + + def __init__(self): + super().__init__() + self.register_buffer("row_sums", self.block.proj.weight.sum(dim=1), persistent=self.persistent) + + +class TransientDerivedBufferComponent(DerivedBufferComponent): + persistent = False + + +class SharedBufferComponent(TinyComponent): + """One tensor registered as a buffer of two modules.""" + + def __init__(self): + super().__init__() + table = torch.arange(3.0) + self.block.register_buffer("table", table, persistent=False) + self.register_buffer("table", table, persistent=False) + + +def backend_of(component_cls): + class Backend(FileBackend): + def load_component(self, component, *, checkpoint_path, master_dtype, materialize_weights): + self.materialize_requests.append(materialize_weights) + model = component_cls().to(dtype=master_dtype) + if materialize_weights: + with torch.no_grad(): + model.block.proj.weight.fill_(BROADCAST_VALUE) + return model + + return Backend + + +def save_row_sums(path): + """The weight in one file and the buffer in another: the state dict is the union of what the index lists.""" + for component in make_model_loader_args().update_weight_target_modules: + folder = path / component + folder.mkdir(parents=True) + files = { + "block.proj.weight": "diffusion_pytorch_model-00001-of-00002.safetensors", + "row_sums": "diffusion_pytorch_model-00002-of-00002.safetensors", + } + save_file({"block.proj.weight": saved_weight(component)}, folder / files["block.proj.weight"]) + save_file({"row_sums": saved_weight(component).sum(dim=1)}, folder / files["row_sums"]) + (folder / "diffusion_pytorch_model.safetensors.index.json").write_text(json.dumps({"weight_map": files})) + + +def test_a_state_dict_buffer_the_constructor_left_on_meta_is_read_from_the_files(tmp_path, monkeypatch): + save_row_sums(tmp_path) + models, materialize_requests, broadcasts = load( + monkeypatch, tmp_path, backend_cls=backend_of(DerivedBufferComponent) + ) + assert materialize_requests == [False, False] and broadcasts == [] + for component, model in models.items(): + assert torch.equal(model.row_sums, saved_weight(component).sum(dim=1).float()) + assert model.forward_count.item() == 0 + + +def test_a_buffer_on_meta_that_no_file_holds_is_an_error(tmp_path, monkeypatch): + save_checkpoint(tmp_path) + with pytest.raises(ValueError, match="buffers outside the state dict are on meta"): + load(monkeypatch, tmp_path, backend_cls=backend_of(TransientDerivedBufferComponent)) + + +def test_a_buffer_two_modules_share_keeps_its_value_on_both(tmp_path, monkeypatch): + save_checkpoint(tmp_path) + models, materialize_requests, broadcasts = load( + monkeypatch, tmp_path, backend_cls=backend_of(SharedBufferComponent) + ) + assert materialize_requests == [False, False] and broadcasts == [] + for model in models.values(): + assert torch.equal(model.table, torch.arange(3.0)) and torch.equal(model.block.table, torch.arange(3.0)) + + +@pytest.mark.parametrize( + "answers, holds", + [([True, True], True), ([False, False], False), pytest.param([True, False], None, id="ranks that disagree")], +) +def test_the_files_are_seen_on_every_rank_or_none_or_the_ranks_raise_together(monkeypatch, answers, holds): + # No rank may take the read while another takes the broadcast; a copy only some ranks see is an error for all. + monkeypatch.setattr(checkpoint.dist, "get_world_size", lambda: len(answers)) + monkeypatch.setattr( + checkpoint.dist, "all_gather_object", lambda out, answer: out.__setitem__(slice(None), answers) + ) + if holds is None: + with pytest.raises(ValueError, match=r"the files are seen on ranks \[0\] only"): + checkpoint.holds_on_every_rank(answers[0], what="the files are seen") + else: + assert checkpoint.holds_on_every_rank(answers[0], what="the files are seen") is holds + + +def test_a_frozen_model_reads_its_shards_in_a_run_that_trains_a_lora(tmp_path, monkeypatch): + # --use-lora describes the trainable model; a frozen role without adapter paths has no LoRA. + save_checkpoint(tmp_path) + _, materialize_requests, broadcasts = load(monkeypatch, tmp_path, use_lora=True, trainable=False) + assert materialize_requests == [False, False] and broadcasts == [] + + +def test_lora_models_are_broadcast(tmp_path, monkeypatch): + save_checkpoint(tmp_path) + monkeypatch.setattr(model_loader, "load_lora_adapter", lambda model, path, *, trainable: model) + holds = lambda condition, **_: pytest.fail("LoRA loads are never read from the files") # noqa: E731 + _, materialize_requests, broadcasts = load(monkeypatch, tmp_path, holds=holds, lora_adapter_paths=["a", "b"]) + assert materialize_requests == [True, True] and len(broadcasts) == 2 + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v"])) From 23babd5ab8f36842a0333ce381589b38b76efeae Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Mon, 23 Nov 2026 00:23:04 -0800 Subject: [PATCH 3/3] docs(fsdp): a backend that names safetensors files gives every tensor its final dtype when it builds without weights Co-authored-by: rockdu --- docs/user-guide/customization.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/docs/user-guide/customization.md b/docs/user-guide/customization.md index d4eed2185..de8e002c5 100644 --- a/docs/user-guide/customization.md +++ b/docs/user-guide/customization.md @@ -381,6 +381,14 @@ resolves to `qwen_image21`. `--diffusion-task` (e.g. `t2i`) must be one of the **Class** for loading components / FSDP. Default comes from the family config (usually a `DiffusersModelBackend`). +`DiffusersModelBackend` lets every rank read its own shards of a component from the checkpoint's safetensors +files (`safetensors_files`). A subclass whose `load_component` loads other weights overrides `safetensors_files` +too, naming the files that hold what it loads or `None` for "rank 0 loads and broadcasts". A backend that names +files gives every tensor its final dtype when `load_component` builds without weights (`materialize_weights=False`): +the file values are cast into those dtypes, and no rank loads a model the others could copy them from. Files that +exist but do not hold the model's state dict, or that only some ranks see, are an error, not a fallback; a file may +hold tensors the model does not have. + *** ## Worked example