From f2500c88ffbdc218573e10529bcd24ef4ca67866 Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Mon, 16 Nov 2026 22:43:46 +0000 Subject: [PATCH 01/31] perf(fsdp): every rank reads its own shards from the checkpoint's safetensors files instead of rank 0 loading and broadcasting them --- miles/backends/fsdp_utils/checkpoint.py | 43 ++++++ miles/backends/fsdp_utils/model_backend.py | 7 +- miles/backends/fsdp_utils/model_loader.py | 88 ++++++++--- .../fsdp_utils/_safetensors_load_worker.py | 71 +++++++++ .../fsdp_utils/test_safetensors_load.py | 50 +++++++ .../backends/fsdp_utils/test_model_backend.py | 32 ++++ .../fsdp_utils/test_reference_models.py | 1 + .../fsdp_utils/test_safetensors_load.py | 140 ++++++++++++++++++ 8 files changed, 407 insertions(+), 25 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..6362f4c2f 100644 --- a/miles/backends/fsdp_utils/checkpoint.py +++ b/miles/backends/fsdp_utils/checkpoint.py @@ -65,6 +65,49 @@ def broadcast_full_state_to_fsdp( buffer.data = buffer.data.to(torch.cuda.current_device()) +def safetensors_folder(checkpoint_path: str, component: str) -> Path | None: + """The component folder when its safetensors files are exactly the ones its diffusers index lists.""" + folder = Path(checkpoint_path) / component + index = folder / "diffusion_pytorch_model.safetensors.index.json" + if not index.is_file(): + return None + listed = set(json.loads(index.read_text())["weight_map"].values()) + return folder if {file.name for file in folder.glob("*.safetensors")} == listed else None + + +def safetensors_hold_state(model: torch.nn.Module, folder: Path) -> bool: + """Whether the files hold the model's state dict: the same names, each with the same shape.""" + from safetensors import safe_open + + saved = {} + for file in folder.glob("*.safetensors"): + with safe_open(file, framework="pt") as tensors: + saved.update({name: tuple(tensors.get_slice(name).get_shape()) for name in tensors.keys()}) + return saved == {name: tuple(tensor.shape) for name, tensor in model.state_dict().items()} + + +def all_ranks_agree(flag: bool) -> bool: + flags = [None] * dist.get_world_size() + dist.all_gather_object(flags, flag) + return all(flags) + + +@torch.no_grad() +def load_safetensors_to_fsdp(model: torch.nn.Module, folder: Path, *, cpu_offload: bool) -> None: + """Materialize FSDP2 shards by reading each rank's own slice of every parameter from the files.""" + device = torch.cuda.current_device() + # Buffers were computed for real on every rank; to_empty would wipe them. + buffers = dict(model.named_buffers()) + model.to_empty(device="cpu" if cpu_offload else device) + for name, buffer in model.named_buffers(): + buffer.copy_(buffers[name]) + dcp.load(model.state_dict(), storage_reader=dcp.HuggingFaceStorageReader(str(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_backend.py b/miles/backends/fsdp_utils/model_backend.py index ff470e54c..9e75998e5 100644 --- a/miles/backends/fsdp_utils/model_backend.py +++ b/miles/backends/fsdp_utils/model_backend.py @@ -204,10 +204,15 @@ def load_component( 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 and keep_in_fp32 is not None: + for name, param in model.named_parameters(): + if any(module in name.split(".") for module in keep_in_fp32): + param.data = param.data.to(torch.float32) + return model @classmethod def _resolve_component_class(cls, checkpoint_path: str, component: str): diff --git a/miles/backends/fsdp_utils/model_loader.py b/miles/backends/fsdp_utils/model_loader.py index ca61e39ec..0dd5332f3 100644 --- a/miles/backends/fsdp_utils/model_loader.py +++ b/miles/backends/fsdp_utils/model_loader.py @@ -4,6 +4,7 @@ import warnings from argparse import Namespace from contextlib import contextmanager +from functools import partial import torch import torch.distributed as dist @@ -27,31 +28,33 @@ 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): - with model_init_context(materialize_weights=materialize_weights): - model = model_backend.load_component( - component, - checkpoint_path=checkpoint_path, - master_dtype=master_dtype, - materialize_weights=materialize_weights, - ) - if args.fsdp_attention_backend is not None: - model_backend.set_attention_backend(model, args.fsdp_attention_backend) - if trainable and args.gradient_checkpointing: - model_backend.enable_gradient_checkpointing(model) - if lora_adapter_paths is not None: - model = load_lora_adapter(model, lora_adapter_paths[component_index], trainable=trainable) - elif trainable and args.use_lora: - model = apply_lora(model, args, train_pipeline_config) - model.train(trainable) - if not trainable: - model.requires_grad_(False) - - if not materialize_weights and any(not parameter.is_meta for parameter in model.parameters()): - raise RuntimeError(f"{component} did not honor meta initialization") + build = partial( + build_component, + args, + model_backend, + train_pipeline_config, + component, + checkpoint_path=checkpoint_path, + lora_adapter_path=None if lora_adapter_paths is None else lora_adapter_paths[component_index], + trainable=trainable, + ) + # 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 = None if use_lora else checkpoint.safetensors_folder(checkpoint_path, component) + materialize_weights = safetensors is None and dist.get_rank() == 0 + model = build(materialize_weights=materialize_weights) + if not use_lora and not checkpoint.all_ranks_agree( + safetensors is not None and checkpoint.safetensors_hold_state(model, safetensors) + ): + if safetensors is not None and dist.get_rank() == 0: + materialize_weights = True + model = build(materialize_weights=True) + safetensors = None + if dist.get_rank() == 0: + source = f"every rank reads {safetensors}" if safetensors is not None else "rank 0 loads and broadcasts" + 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 +64,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 is not None: + checkpoint.load_safetensors_to_fsdp(model, safetensors, 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: @@ -79,6 +85,40 @@ def load_fsdp_models( return models +def build_component( + args: Namespace, + model_backend, + train_pipeline_config, + component: str, + *, + checkpoint_path: str, + lora_adapter_path: str | None, + trainable: bool, + materialize_weights: bool, +) -> torch.nn.Module: + with model_init_context(materialize_weights=materialize_weights): + model = model_backend.load_component( + component, + checkpoint_path=checkpoint_path, + master_dtype=parse_dtype_from_str(args.fsdp_master_dtype), + materialize_weights=materialize_weights, + ) + if args.fsdp_attention_backend is not None: + model_backend.set_attention_backend(model, args.fsdp_attention_backend) + if trainable and args.gradient_checkpointing: + model_backend.enable_gradient_checkpointing(model) + if lora_adapter_path is not None: + model = load_lora_adapter(model, lora_adapter_path, trainable=trainable) + elif trainable and args.use_lora: + model = apply_lora(model, args, train_pipeline_config) + model.train(trainable) + if not trainable: + model.requires_grad_(False) + if not materialize_weights and any(not parameter.is_meta for parameter in model.parameters()): + raise RuntimeError(f"{component} did not honor meta initialization") + return model + + def finish_fsdp_lazy_init(model: torch.nn.Module) -> None: """Run FSDP's one-time lazy init now instead of at the first forward. 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..88b366cfe --- /dev/null +++ b/tests/fast-gpu/backends/fsdp_utils/_safetensors_load_worker.py @@ -0,0 +1,71 @@ +"""Two ranks read their own halves of a safetensors checkpoint, or fall back to rank 0's broadcast together. + + 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 + another name in the files --> rank 0 builds again with weights --> the broadcast value on both ranks +""" + +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 ( + BROADCAST_VALUE, + 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 + + +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(), FileBackend() + 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 + 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") + 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()) + + models, materialize_requests = load(mesh, root / "renamed", cpu_offload) + assert materialize_requests == ([False, True, False, True] if rank == 0 else [False, False]) + for model in models.values(): + assert torch.all(model.block.proj.weight.to_local() == BROADCAST_VALUE) + 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..78a33ca73 --- /dev/null +++ b/tests/fast-gpu/backends/fsdp_utils/test_safetensors_load.py @@ -0,0 +1,50 @@ +"""Two ranks read their own shards of a safetensors checkpoint, or fall back to the broadcast together. + + 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 --> the value rank 0 loaded, 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_model_backend.py b/tests/fast/backends/fsdp_utils/test_model_backend.py index ee653ff55..90858922c 100644 --- a/tests/fast/backends/fsdp_utils/test_model_backend.py +++ b/tests/fast/backends/fsdp_utils/test_model_backend.py @@ -39,6 +39,20 @@ 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) + + class TestBackendHierarchy: def test_concrete_backends_are_sibling_implementations(self): assert issubclass(MilesModelBackend, BaseModelBackend) @@ -83,3 +97,21 @@ 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"] diff --git a/tests/fast/backends/fsdp_utils/test_reference_models.py b/tests/fast/backends/fsdp_utils/test_reference_models.py index e90e271a2..af122178b 100644 --- a/tests/fast/backends/fsdp_utils/test_reference_models.py +++ b/tests/fast/backends/fsdp_utils/test_reference_models.py @@ -204,6 +204,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, "all_ranks_agree", lambda flag: flag) 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..61a17c036 --- /dev/null +++ b/tests/fast/backends/fsdp_utils/test_safetensors_load.py @@ -0,0 +1,140 @@ +"""Every rank reads its own shards of a diffusers safetensors checkpoint. + + index + exactly its files + the state dict's names and shapes --> every rank on meta --> dcp.load per shard + stray file / other name / other shape / a rank that disagrees / LoRA --> rank 0 loads and broadcasts + +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, + TinyPipelineConfig, + make_model_loader_args, +) +from torch.distributed.device_mesh import init_device_mesh + +from miles.backends.fsdp_utils import model_loader + +BROADCAST_VALUE = 0.75 + + +class FileBackend(TinyBackend): + 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)): + for component in make_model_loader_args().update_weight_target_modules: + folder = path / component + folder.mkdir(parents=True) + file = "diffusion_pytorch_model-00001-of-00001.safetensors" + save_file({name: saved_weight(component).reshape(shape)}, folder / file) + (folder / "diffusion_pytorch_model.safetensors.index.json").write_text( + json.dumps({"weight_map": {name: file}}) + ) + + +def load(monkeypatch, path, *, agree=lambda flag: flag, **kwargs): + broadcasts = [] + monkeypatch.setattr(model_loader.checkpoint, "all_ranks_agree", agree) + 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(), FileBackend() + args.use_lora = False + 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 test_every_rank_reads_its_shards_from_the_files(tmp_path, monkeypatch): + save_checkpoint(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 add_stray_file(path): + save_checkpoint(path) + save_file( + {"block.proj.weight": torch.zeros(4, 3)}, path / "transformer" / "diffusion_pytorch_model.fp16.safetensors" + ) + + +@pytest.mark.parametrize( + "save, rebuilt", + [ + pytest.param(add_stray_file, False, id="a file the index does not list"), + pytest.param(lambda path: save_checkpoint(path, name="block.proj.kernel"), True, id="another name"), + pytest.param(lambda path: save_checkpoint(path, shape=(3, 4)), True, id="another shape"), + ], +) +def test_files_that_are_not_the_state_dict_fall_back_to_the_broadcast(tmp_path, monkeypatch, save, rebuilt): + save(tmp_path) + models, materialize_requests, broadcasts = load(monkeypatch, tmp_path) + assert materialize_requests[:2] == ([False, True] if rebuilt else [True, False]) + assert [set(state) for state in broadcasts[:1]] == [{"block.proj.weight"}] + assert torch.all(broadcasts[0]["block.proj.weight"] == BROADCAST_VALUE) + + +def test_one_rank_that_cannot_read_the_files_sends_every_rank_to_the_broadcast(tmp_path, monkeypatch): + save_checkpoint(tmp_path) + flags = [] + _, materialize_requests, broadcasts = load(monkeypatch, tmp_path, agree=lambda flag: flags.append(flag) or False) + assert flags == [True, True] and materialize_requests == [False, True, False, True] and len(broadcasts) == 2 + + +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) + agree = lambda flag: pytest.fail("LoRA loads are never read from the files") # noqa: E731 + _, materialize_requests, broadcasts = load(monkeypatch, tmp_path, agree=agree, lora_adapter_paths=["a", "b"]) + assert materialize_requests == [True, True] and len(broadcasts) == 2 + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v"])) From 0414fefdbb66e39968f4fe02280a19b6276c50b4 Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:50:28 +0000 Subject: [PATCH 02/31] perf(fsdp): the backend names the safetensors files every rank reads, so Hub ids, single-file checkpoints and folders with a variant are read per rank too The model backend now says which files hold a component (safetensors_files): the ones the diffusers index lists, else the single diffusion_pytorch_model.safetensors, the files from_pretrained reads with no variant. A Hub id resolves to its snapshot first. The reader is pointed at a folder of links to those files, since it takes every safetensors file of one folder. Backends that do not say (the native packages) keep rank 0's broadcast. --- miles/backends/fsdp_utils/checkpoint.py | 24 +++++------ miles/backends/fsdp_utils/model_backend.py | 24 +++++++++++ miles/backends/fsdp_utils/model_loader.py | 6 ++- .../backends/fsdp_utils/test_model_backend.py | 26 ++++++++++++ .../fsdp_utils/test_reference_models.py | 3 ++ .../fsdp_utils/test_safetensors_load.py | 42 ++++++++++++++----- 6 files changed, 99 insertions(+), 26 deletions(-) diff --git a/miles/backends/fsdp_utils/checkpoint.py b/miles/backends/fsdp_utils/checkpoint.py index 6362f4c2f..5b8d1a9e0 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,22 +67,12 @@ def broadcast_full_state_to_fsdp( buffer.data = buffer.data.to(torch.cuda.current_device()) -def safetensors_folder(checkpoint_path: str, component: str) -> Path | None: - """The component folder when its safetensors files are exactly the ones its diffusers index lists.""" - folder = Path(checkpoint_path) / component - index = folder / "diffusion_pytorch_model.safetensors.index.json" - if not index.is_file(): - return None - listed = set(json.loads(index.read_text())["weight_map"].values()) - return folder if {file.name for file in folder.glob("*.safetensors")} == listed else None - - -def safetensors_hold_state(model: torch.nn.Module, folder: Path) -> bool: +def safetensors_hold_state(model: torch.nn.Module, files: list[Path]) -> bool: """Whether the files hold the model's state dict: the same names, each with the same shape.""" from safetensors import safe_open saved = {} - for file in folder.glob("*.safetensors"): + 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()}) return saved == {name: tuple(tensor.shape) for name, tensor in model.state_dict().items()} @@ -93,7 +85,7 @@ def all_ranks_agree(flag: bool) -> bool: @torch.no_grad() -def load_safetensors_to_fsdp(model: torch.nn.Module, folder: Path, *, cpu_offload: bool) -> None: +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.""" device = torch.cuda.current_device() # Buffers were computed for real on every rank; to_empty would wipe them. @@ -101,7 +93,11 @@ def load_safetensors_to_fsdp(model: torch.nn.Module, folder: Path, *, cpu_offloa model.to_empty(device="cpu" if cpu_offload else device) for name, buffer in model.named_buffers(): buffer.copy_(buffers[name]) - dcp.load(model.state_dict(), storage_reader=dcp.HuggingFaceStorageReader(str(folder), thread_count=4)) + # 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(): diff --git a/miles/backends/fsdp_utils/model_backend.py b/miles/backends/fsdp_utils/model_backend.py index 9e75998e5..bd8a392a5 100644 --- a/miles/backends/fsdp_utils/model_backend.py +++ b/miles/backends/fsdp_utils/model_backend.py @@ -20,11 +20,15 @@ import abc import functools import importlib +import json import logging +import os from dataclasses import replace +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 @@ -54,6 +58,10 @@ 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.""" + return None + @abc.abstractmethod def enable_gradient_checkpointing(self, model: torch.nn.Module) -> None: raise NotImplementedError @@ -214,6 +222,22 @@ def load_component( param.data = param.data.to(torch.float32) return model + def safetensors_files(self, component: str, *, checkpoint_path: str) -> list[Path] | None: + """The files ``from_pretrained`` reads with no variant: the ones the index lists, else the single file.""" + stem = SAFETENSORS_WEIGHTS_NAME.removesuffix(".safetensors") + if not os.path.isdir(checkpoint_path): + from huggingface_hub import snapshot_download + + patterns = [f"{component}/{SAFETENSORS_WEIGHTS_NAME}*", f"{component}/{stem}-*.safetensors"] + checkpoint_path = snapshot_download(checkpoint_path, allow_patterns=patterns) + folder = Path(checkpoint_path) / component + index = folder / SAFE_WEIGHTS_INDEX_NAME + names = {SAFETENSORS_WEIGHTS_NAME} + if index.is_file(): + names = set(json.loads(index.read_text())["weight_map"].values()) + files = [folder / name for name in sorted(names)] + return files if all(file.is_file() for file in files) else None + @classmethod def _resolve_component_class(cls, checkpoint_path: str, component: str): """Resolve ``component``'s class from ``model_index.json``. diff --git a/miles/backends/fsdp_utils/model_loader.py b/miles/backends/fsdp_utils/model_loader.py index 0dd5332f3..5da416042 100644 --- a/miles/backends/fsdp_utils/model_loader.py +++ b/miles/backends/fsdp_utils/model_loader.py @@ -42,7 +42,7 @@ def load_fsdp_models( ) # 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 = None if use_lora else checkpoint.safetensors_folder(checkpoint_path, component) + safetensors = None if use_lora else model_backend.safetensors_files(component, checkpoint_path=checkpoint_path) materialize_weights = safetensors is None and dist.get_rank() == 0 model = build(materialize_weights=materialize_weights) if not use_lora and not checkpoint.all_ranks_agree( @@ -53,7 +53,9 @@ def load_fsdp_models( model = build(materialize_weights=True) safetensors = None if dist.get_rank() == 0: - source = f"every rank reads {safetensors}" if safetensors is not None else "rank 0 loads and broadcasts" + source = "rank 0 loads and broadcasts" + if safetensors is not None: + source = f"every rank reads {len(safetensors)} safetensors files of {safetensors[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 {} diff --git a/tests/fast/backends/fsdp_utils/test_model_backend.py b/tests/fast/backends/fsdp_utils/test_model_backend.py index 90858922c..0a567b049 100644 --- a/tests/fast/backends/fsdp_utils/test_model_backend.py +++ b/tests/fast/backends/fsdp_utils/test_model_backend.py @@ -115,3 +115,29 @@ def test_a_component_built_without_weights_keeps_its_fp32_modules(self, tmp_path "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", + ], + ) + ] diff --git a/tests/fast/backends/fsdp_utils/test_reference_models.py b/tests/fast/backends/fsdp_utils/test_reference_models.py index af122178b..72e1ce42a 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",)) diff --git a/tests/fast/backends/fsdp_utils/test_safetensors_load.py b/tests/fast/backends/fsdp_utils/test_safetensors_load.py index 61a17c036..b2da274eb 100644 --- a/tests/fast/backends/fsdp_utils/test_safetensors_load.py +++ b/tests/fast/backends/fsdp_utils/test_safetensors_load.py @@ -1,7 +1,8 @@ """Every rank reads its own shards of a diffusers safetensors checkpoint. - index + exactly its files + the state dict's names and shapes --> every rank on meta --> dcp.load per shard - stray file / other name / other shape / a rank that disagrees / LoRA --> rank 0 loads and broadcasts + the index's files, or the single file, hold the state dict's names and shapes --> every rank on meta --> dcp.load + a variant file beside them --> not read + listed file missing / other name / other shape / a rank that disagrees / LoRA --> rank 0 loads and broadcasts FSDP2 is real on a one-rank CPU mesh and the broadcast is recorded; the CUDA worker splits the shards over two ranks. """ @@ -26,11 +27,14 @@ from torch.distributed.device_mesh import init_device_mesh from miles.backends.fsdp_utils import model_loader +from miles.backends.fsdp_utils.model_backend import DiffusersModelBackend BROADCAST_VALUE = 0.75 class FileBackend(TinyBackend): + safetensors_files = DiffusersModelBackend.safetensors_files + def __init__(self): super().__init__() self.materialize_requests = [] @@ -50,10 +54,13 @@ 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)): +def save_checkpoint(path, *, name="block.proj.weight", shape=(4, 3), sharded=True): for component in make_model_loader_args().update_weight_target_modules: folder = path / component folder.mkdir(parents=True) + if not sharded: + save_file({name: saved_weight(component).reshape(shape)}, folder / "diffusion_pytorch_model.safetensors") + continue file = "diffusion_pytorch_model-00001-of-00001.safetensors" save_file({name: saved_weight(component).reshape(shape)}, folder / file) (folder / "diffusion_pytorch_model.safetensors.index.json").write_text( @@ -83,8 +90,25 @@ def load(monkeypatch, path, *, agree=lambda flag: flag, **kwargs): dist.destroy_process_group() -def test_every_rank_reads_its_shards_from_the_files(tmp_path, monkeypatch): - save_checkpoint(tmp_path) +def add_variant_file(path, *, sharded): + save_checkpoint(path, sharded=sharded) + for component in make_model_loader_args().update_weight_target_modules: + save_file( + {"block.proj.weight": torch.zeros(4, 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"), + ], +) +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(): @@ -98,17 +122,15 @@ def test_every_rank_reads_its_shards_from_the_files(tmp_path, monkeypatch): assert model.forward_count.item() == 1 -def add_stray_file(path): +def remove_a_listed_file(path): save_checkpoint(path) - save_file( - {"block.proj.weight": torch.zeros(4, 3)}, path / "transformer" / "diffusion_pytorch_model.fp16.safetensors" - ) + (path / "transformer" / "diffusion_pytorch_model-00001-of-00001.safetensors").unlink() @pytest.mark.parametrize( "save, rebuilt", [ - pytest.param(add_stray_file, False, id="a file the index does not list"), + pytest.param(remove_a_listed_file, False, id="a listed file is missing"), pytest.param(lambda path: save_checkpoint(path, name="block.proj.kernel"), True, id="another name"), pytest.param(lambda path: save_checkpoint(path, shape=(3, 4)), True, id="another shape"), ], From 2b525d4eb57b8aeb4c55cfafba2b0c0767935b59 Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:07:47 +0000 Subject: [PATCH 03/31] fix(fsdp): rank 0's second build starts from the generator state of its first, so a fallback after a meta build draws what one build draws --- miles/backends/fsdp_utils/model_loader.py | 3 ++ .../fsdp_utils/test_safetensors_load.py | 29 +++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/miles/backends/fsdp_utils/model_loader.py b/miles/backends/fsdp_utils/model_loader.py index 5da416042..e166ce553 100644 --- a/miles/backends/fsdp_utils/model_loader.py +++ b/miles/backends/fsdp_utils/model_loader.py @@ -44,11 +44,14 @@ def load_fsdp_models( use_lora = lora_adapter_paths is not None or (trainable and args.use_lora) safetensors = None if use_lora else model_backend.safetensors_files(component, checkpoint_path=checkpoint_path) materialize_weights = safetensors is None and dist.get_rank() == 0 + rng_state = torch.get_rng_state() model = build(materialize_weights=materialize_weights) if not use_lora and not checkpoint.all_ranks_agree( safetensors is not None and checkpoint.safetensors_hold_state(model, safetensors) ): if safetensors is not None and dist.get_rank() == 0: + # A constructor may draw random numbers: the second build draws what the first one did. + torch.set_rng_state(rng_state) materialize_weights = True model = build(materialize_weights=True) safetensors = None diff --git a/tests/fast/backends/fsdp_utils/test_safetensors_load.py b/tests/fast/backends/fsdp_utils/test_safetensors_load.py index b2da274eb..145e49c56 100644 --- a/tests/fast/backends/fsdp_utils/test_safetensors_load.py +++ b/tests/fast/backends/fsdp_utils/test_safetensors_load.py @@ -90,6 +90,17 @@ def load(monkeypatch, path, *, agree=lambda flag: flag, **kwargs): dist.destroy_process_group() +def build_with(load_component): + """build_component with the backend's load_component replaced.""" + build_component = model_loader.build_component + + def build(args, model_backend, *rest, **kwargs): + model_backend.load_component = load_component.__get__(model_backend) + return build_component(args, model_backend, *rest, **kwargs) + + return build + + def add_variant_file(path, *, sharded): save_checkpoint(path, sharded=sharded) for component in make_model_loader_args().update_weight_target_modules: @@ -143,6 +154,24 @@ def test_files_that_are_not_the_state_dict_fall_back_to_the_broadcast(tmp_path, assert torch.all(broadcasts[0]["block.proj.weight"] == BROADCAST_VALUE) +def test_rank_0_built_twice_leaves_the_generator_where_one_build_does(tmp_path, monkeypatch): + # Some diffusers constructors draw a parameter with torch.randn, on meta as with weights. + def drawing_load_component(self, component, **kwargs): + torch.randn(1) + return FileBackend.load_component(self, component, **kwargs) + + save_checkpoint(tmp_path / "renamed", name="block.proj.kernel") + (tmp_path / "no files").mkdir() + states = {} + for path in ("renamed", "no files"): + monkeypatch.setattr(model_loader, "build_component", build_with(drawing_load_component)) + torch.manual_seed(0) + _, materialize_requests, _ = load(monkeypatch, tmp_path / path) + states[path] = (materialize_requests, torch.get_rng_state()) + assert states["renamed"][0] == [False, True, False, True] and states["no files"][0] == [True, True] + assert torch.equal(states["renamed"][1], states["no files"][1]) + + def test_one_rank_that_cannot_read_the_files_sends_every_rank_to_the_broadcast(tmp_path, monkeypatch): save_checkpoint(tmp_path) flags = [] From db154d2f6cd8f1896b5e96bd0395179d48da342f Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:13:33 +0000 Subject: [PATCH 04/31] perf(fsdp): a model with LoRA reads its base shards from the safetensors files too; every rank builds the adapter as rank 0 does Every rank lets PEFT build the adapter (a new one from rank 0's generator state, a saved one from its files) on a base that has uninitialized storage instead of weights, then reads its own shards of the base under the names the checkpoint gives them. An initialization that decomposes the base weights (PiSSA, OLoRA, LoftQ...) keeps rank 0's load and broadcast. The ranks now agree that the files are there before any of them builds. --- miles/backends/fsdp_utils/checkpoint.py | 38 +++++-- miles/backends/fsdp_utils/model_loader.py | 102 ++++++++++++++---- .../fsdp_utils/_safetensors_load_worker.py | 53 +++++++-- .../fsdp_utils/test_safetensors_load.py | 1 + .../fsdp_utils/test_safetensors_load.py | 87 +++++++++++++-- 5 files changed, 234 insertions(+), 47 deletions(-) diff --git a/miles/backends/fsdp_utils/checkpoint.py b/miles/backends/fsdp_utils/checkpoint.py index 5b8d1a9e0..ae371328a 100644 --- a/miles/backends/fsdp_utils/checkpoint.py +++ b/miles/backends/fsdp_utils/checkpoint.py @@ -67,15 +67,24 @@ def broadcast_full_state_to_fsdp( buffer.data = buffer.data.to(torch.cuda.current_device()) -def safetensors_hold_state(model: torch.nn.Module, files: list[Path]) -> bool: - """Whether the files hold the model's state dict: the same names, each with the same shape.""" +def base_state(model: torch.nn.Module) -> dict[str, torch.Tensor]: + """The state dict without LoRA adapters, under the names the base checkpoint gives its tensors.""" + return { + name.removeprefix("base_model.model.").replace(".base_layer.", "."): tensor + for name, tensor in model.state_dict().items() + if not is_lora_param_name(name) + } + + +def safetensors_hold_state(state: dict[str, torch.Tensor], files: list[Path]) -> bool: + """Whether the files hold the state dict: the same names, each with the same shape.""" from safetensors import safe_open 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()}) - return saved == {name: tuple(tensor.shape) for name, tensor in model.state_dict().items()} + return saved == {name: tuple(tensor.shape) for name, tensor in state.items()} def all_ranks_agree(flag: bool) -> bool: @@ -84,27 +93,38 @@ def all_ranks_agree(flag: bool) -> bool: return all(flags) +def rank0_rng_state() -> torch.Tensor: + """The state of rank 0's default generator, on every rank.""" + states = [torch.get_rng_state() if dist.get_rank() == 0 else None] + dist.broadcast_object_list(states, src=0) + return states[0] + + @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.""" + """Materialize FSDP2 shards by reading each rank's own slice of every base parameter from the files.""" device = torch.cuda.current_device() - # Buffers were computed for real on every rank; to_empty would wipe them. + # Buffers and LoRA adapters were computed for real on every rank; to_empty would wipe them. buffers = dict(model.named_buffers()) + adapters = {name: p.to_local().clone() for name, p in model.named_parameters() if is_lora_param_name(name)} model.to_empty(device="cpu" if cpu_offload else device) for name, buffer in model.named_buffers(): buffer.copy_(buffers[name]) + for name, parameter in model.named_parameters(): + if name in adapters: + parameter.to_local().copy_(adapters[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)) + dcp.load(base_state(model), 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: +def is_lora_param_name(name: str) -> bool: return "lora_" in name @@ -119,7 +139,7 @@ def __init__(self, model, lora_only: bool = False): def state_dict(self): model_state_dict, _ = get_state_dict(self.model, optimizers=[]) if self.lora_only: - model_state_dict = {k: v for k, v in model_state_dict.items() if _is_lora_param_name(k)} + model_state_dict = {k: v for k, v in model_state_dict.items() if is_lora_param_name(k)} return {"model": model_state_dict} def load_state_dict(self, state_dict): @@ -133,7 +153,7 @@ def load_state_dict(self, state_dict): ) # strict=False swallows mismatches; lora_only expects missing base keys, anything else is a bad checkpoint unclaimed = list(incompatible.unexpected_keys) - unfilled = [k for k in incompatible.missing_keys if not self.lora_only or _is_lora_param_name(k)] + unfilled = [k for k in incompatible.missing_keys if not self.lora_only or is_lora_param_name(k)] if unclaimed or unfilled: logger.error( f"[FSDP] Checkpoint mismatch: {len(unclaimed)} unclaimed checkpoint keys, " diff --git a/miles/backends/fsdp_utils/model_loader.py b/miles/backends/fsdp_utils/model_loader.py index e166ce553..28017e55e 100644 --- a/miles/backends/fsdp_utils/model_loader.py +++ b/miles/backends/fsdp_utils/model_loader.py @@ -30,6 +30,7 @@ def load_fsdp_models( ) -> dict[str, torch.nn.Module]: models = {} for component_index, component in enumerate(args.update_weight_target_modules): + lora_adapter_path = None if lora_adapter_paths is None else lora_adapter_paths[component_index] build = partial( build_component, args, @@ -37,23 +38,28 @@ def load_fsdp_models( train_pipeline_config, component, checkpoint_path=checkpoint_path, - lora_adapter_path=None if lora_adapter_paths is None else lora_adapter_paths[component_index], + lora_adapter_path=lora_adapter_path, trainable=trainable, ) - # 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 = None if use_lora else model_backend.safetensors_files(component, checkpoint_path=checkpoint_path) + # Every rank reads its own shards from the safetensors files; else rank 0 loads and broadcasts. + has_lora = lora_adapter_path is not None or (trainable and args.use_lora) + read_per_rank = not has_lora or lora_needs_no_base_weights(args, lora_adapter_path) + safetensors = None + if read_per_rank: + safetensors = model_backend.safetensors_files(component, checkpoint_path=checkpoint_path) + if not checkpoint.all_ranks_agree(safetensors is not None): + safetensors = None materialize_weights = safetensors is None and dist.get_rank() == 0 rng_state = torch.get_rng_state() - model = build(materialize_weights=materialize_weights) - if not use_lora and not checkpoint.all_ranks_agree( - safetensors is not None and checkpoint.safetensors_hold_state(model, safetensors) + model = build(materialize_weights=materialize_weights, lora_on_every_rank=safetensors is not None) + if safetensors is not None and not checkpoint.all_ranks_agree( + checkpoint.safetensors_hold_state(checkpoint.base_state(model), safetensors) ): - if safetensors is not None and dist.get_rank() == 0: + if has_lora or dist.get_rank() == 0: # A constructor may draw random numbers: the second build draws what the first one did. torch.set_rng_state(rng_state) - materialize_weights = True - model = build(materialize_weights=True) + materialize_weights = dist.get_rank() == 0 + model = build(materialize_weights=materialize_weights, lora_on_every_rank=False) safetensors = None if dist.get_rank() == 0: source = "rank 0 loads and broadcasts" @@ -90,6 +96,18 @@ def load_fsdp_models( return models +LORA_INITS_WITHOUT_BASE_WEIGHTS = ("gaussian", "kaiming-uniform") + + +def lora_needs_no_base_weights(args: Namespace, lora_adapter_path: str | None) -> bool: + """Whether PEFT builds the adapter without reading the base weights (PiSSA, OLoRA, LoftQ... decompose them).""" + if lora_adapter_path is None: + return args.lora_init_weights in LORA_INITS_WITHOUT_BASE_WEIGHTS + from peft import PeftConfig + + return PeftConfig.from_pretrained(lora_adapter_path).init_lora_weights in (True, False, "gaussian") + + def build_component( args: Namespace, model_backend, @@ -100,7 +118,9 @@ def build_component( lora_adapter_path: str | None, trainable: bool, materialize_weights: bool, + lora_on_every_rank: bool, ) -> torch.nn.Module: + """``lora_on_every_rank``: every rank builds the adapter's values as rank 0 does, on a base without weights.""" with model_init_context(materialize_weights=materialize_weights): model = model_backend.load_component( component, @@ -112,18 +132,55 @@ def build_component( model_backend.set_attention_backend(model, args.fsdp_attention_backend) if trainable and args.gradient_checkpointing: model_backend.enable_gradient_checkpointing(model) - if lora_adapter_path is not None: - model = load_lora_adapter(model, lora_adapter_path, trainable=trainable) - elif trainable and args.use_lora: - model = apply_lora(model, args, train_pipeline_config) + materialize_lora = lora_on_every_rank or dist.get_rank() == 0 + with base_storage_for_lora(model, enabled=materialize_lora and not materialize_weights): + if lora_adapter_path is not None: + model = load_lora_adapter(model, lora_adapter_path, trainable=trainable, materialize=materialize_lora) + elif trainable and args.use_lora: + model = apply_lora(model, args, train_pipeline_config, materialize=materialize_lora) model.train(trainable) if not trainable: model.requires_grad_(False) - if not materialize_weights and any(not parameter.is_meta for parameter in model.parameters()): + if not materialize_weights and any( + not parameter.is_meta + for name, parameter in model.named_parameters() + if not (lora_on_every_rank and checkpoint.is_lora_param_name(name)) + ): raise RuntimeError(f"{component} did not honor meta initialization") return model +@contextmanager +def base_storage_for_lora(model: torch.nn.Module, *, enabled: bool): + """Give a meta base uninitialized CPU storage while PEFT builds an adapter on it, from rank 0's generator. + + PEFT moves a new adapter to its base layer's device, and meta would drop the adapter's values. Its + initialization draws, and only rank 0 has run it so far: the other ranks draw the same values from rank 0's + generator state and keep their own. + """ + if not enabled: + yield + return + rng_state = torch.get_rng_state() + torch.set_rng_state(checkpoint.rank0_rng_state()) + replace_base_parameters(model, lambda parameter: torch.empty(parameter.shape, dtype=parameter.dtype)) + try: + yield + finally: + replace_base_parameters(model, lambda parameter: parameter.data.to("meta")) + if dist.get_rank() != 0: + torch.set_rng_state(rng_state) + + +def replace_base_parameters(model: torch.nn.Module, data_of) -> None: + # A meta parameter cannot take CPU data in place (nor the reverse), so each one is registered anew. + for module_name, module in model.named_modules(): + for name, parameter in list(module.named_parameters(recurse=False)): + if not checkpoint.is_lora_param_name(f"{module_name}.{name}"): + data = data_of(parameter) + module.register_parameter(name, torch.nn.Parameter(data, requires_grad=parameter.requires_grad)) + + def finish_fsdp_lazy_init(model: torch.nn.Module) -> None: """Run FSDP's one-time lazy init now instead of at the first forward. @@ -150,21 +207,22 @@ def model_init_context(*, materialize_weights: bool): yield -def load_lora_adapter(model, adapter_path: str, *, trainable: bool): +def load_lora_adapter(model, adapter_path: str, *, trainable: bool, materialize: bool): from peft import PeftConfig, PeftModel, get_peft_model - if dist.get_rank() == 0: + if materialize: return PeftModel.from_pretrained(model, adapter_path, is_trainable=trainable, autocast_adapter_dtype=False) config = PeftConfig.from_pretrained(adapter_path) config.inference_mode = not trainable return get_peft_model(model, config, low_cpu_mem_usage=True, autocast_adapter_dtype=False) -def apply_lora(model: torch.nn.Module, args: Namespace, train_pipeline_config) -> torch.nn.Module: - """Apply PEFT LoRA, leaving non-rank0 adapters uninitialized on meta.""" +def apply_lora( + model: torch.nn.Module, args: Namespace, train_pipeline_config, *, materialize: bool +) -> torch.nn.Module: + """Apply PEFT LoRA; without ``materialize`` the adapters stay uninitialized on meta.""" from peft import LoraConfig, get_peft_model - on_meta = dist.get_rank() != 0 # Per-model fallback when --lora-target-modules is unset (runtime inference: depends on loaded pipeline). targets = args.lora_target_modules or train_pipeline_config.lora_target_modules init_lora_weight = args.lora_init_weights @@ -176,9 +234,9 @@ def apply_lora(model: torch.nn.Module, args: Namespace, train_pipeline_config) - r=args.lora_rank, lora_alpha=args.lora_alpha, target_modules=targets, - init_lora_weights=False if on_meta else init_lora_weight, + init_lora_weights=init_lora_weight if materialize else False, ), - low_cpu_mem_usage=on_meta, + low_cpu_mem_usage=not materialize, ) if dist.get_rank() == 0: model.print_trainable_parameters() diff --git a/tests/fast-gpu/backends/fsdp_utils/_safetensors_load_worker.py b/tests/fast-gpu/backends/fsdp_utils/_safetensors_load_worker.py index 88b366cfe..403b57bdc 100644 --- a/tests/fast-gpu/backends/fsdp_utils/_safetensors_load_worker.py +++ b/tests/fast-gpu/backends/fsdp_utils/_safetensors_load_worker.py @@ -2,6 +2,7 @@ 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 another name in the files --> rank 0 builds again with weights --> the broadcast value on both ranks + LoRA, saved or new --> the adapter shards and the generator the broadcast leaves, on both ranks """ import os @@ -11,7 +12,11 @@ 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_reference_models import ( + TinyPipelineConfig, + make_model_loader_args, + save_component_lora_adapters, +) from tests.fast.backends.fsdp_utils.test_safetensors_load import ( BROADCAST_VALUE, FileBackend, @@ -23,21 +28,52 @@ from miles.backends.fsdp_utils.model_loader import load_fsdp_models -def load(mesh, path, cpu_offload): +def load(mesh, path, cpu_offload, *, lora_init=None, **kwargs): parallel = SimpleNamespace(get_mesh=lambda name: mesh, get_optional_mesh=lambda name: None) args, backend = make_model_loader_args(), FileBackend() - args.use_lora = False + args.use_lora = lora_init is not None + args.lora_rank, args.lora_alpha, args.lora_target_modules, args.lora_init_weights = 2, 4, ["proj"], lora_init models = load_fsdp_models( - args, backend, TinyPipelineConfig(), parallel, checkpoint_path=str(path), cpu_offload=cpu_offload + args, backend, TinyPipelineConfig(), parallel, checkpoint_path=str(path), cpu_offload=cpu_offload, **kwargs ) for model in models.values(): - shard = model.block.proj.weight.to_local() + base = model.base_model.model if kwargs else model + weight = base.block.proj.base_layer.weight if kwargs else base.block.proj.weight + shard = 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 base.forward_count.device.type == "cuda" and base.forward_count.item() == 0 return models, backend.materialize_requests +def adapter_shards(models): + return { + (component, name): parameter.to_local().cpu() + for component, model in models.items() + for name, parameter in model.named_parameters() + if "lora_" in name + } + + +def check_lora(mesh, root, rank, cpu_offload, **kwargs): + # read per rank + torch.manual_seed(0) + models, materialize_requests = load(mesh, root / "state", cpu_offload, **kwargs) + assert materialize_requests == [False, False] + for component, model in models.items(): + base = model.base_model.model.block.proj.base_layer.weight.to_local().cpu() + assert torch.equal(base, saved_weight(component).float()[2 * rank : 2 * rank + 2]) + adapters, generator = adapter_shards(models), torch.get_rng_state() + assert len(adapters) == 4 and any(shard.abs().sum() > 0 for shard in adapters.values()) + # rank 0 builds with weights, then the real broadcast + torch.manual_seed(0) + models, materialize_requests = load(mesh, root / "renamed", cpu_offload, **kwargs) + assert materialize_requests == ([False, True, False, True] if rank == 0 else [False, False, False, False]) + broadcast = adapter_shards(models) + assert adapters.keys() == broadcast.keys() and all(torch.equal(adapters[key], broadcast[key]) for key in adapters) + assert torch.equal(torch.get_rng_state(), generator) + + 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())) @@ -46,6 +82,7 @@ def main(): if rank == 0: save_checkpoint(root / "state") save_checkpoint(root / "renamed", name="block.proj.kernel") + save_component_lora_adapters(root / "adapters") dist.barrier() inputs = torch.ones(2, 3, device="cuda") for cpu_offload in (False, True): @@ -61,6 +98,10 @@ def main(): assert materialize_requests == ([False, True, False, True] if rank == 0 else [False, False]) for model in models.values(): assert torch.all(model.block.proj.weight.to_local() == BROADCAST_VALUE) + + adapter_paths = [str(root / "adapters" / component) for component in ("transformer", "transformer_2")] + check_lora(mesh, root, rank, cpu_offload, lora_adapter_paths=adapter_paths) + check_lora(mesh, root, rank, cpu_offload, lora_init="gaussian", trainable=True) dist.barrier() if rank == 0: print("OK") diff --git a/tests/fast-gpu/backends/fsdp_utils/test_safetensors_load.py b/tests/fast-gpu/backends/fsdp_utils/test_safetensors_load.py index 78a33ca73..a91ad479f 100644 --- a/tests/fast-gpu/backends/fsdp_utils/test_safetensors_load.py +++ b/tests/fast-gpu/backends/fsdp_utils/test_safetensors_load.py @@ -2,6 +2,7 @@ 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 --> the value rank 0 loaded, on both ranks + LoRA, saved or new --> the adapter shards and the generator the broadcast leaves, on both ranks """ from tests.ci.ci_register import register_cuda_ci diff --git a/tests/fast/backends/fsdp_utils/test_safetensors_load.py b/tests/fast/backends/fsdp_utils/test_safetensors_load.py index 145e49c56..375496f98 100644 --- a/tests/fast/backends/fsdp_utils/test_safetensors_load.py +++ b/tests/fast/backends/fsdp_utils/test_safetensors_load.py @@ -2,7 +2,9 @@ the index's files, or the single file, hold the state dict's names and shapes --> every rank on meta --> dcp.load a variant file beside them --> not read - listed file missing / other name / other shape / a rank that disagrees / LoRA --> rank 0 loads and broadcasts + listed file missing / other name / other shape / a rank that disagrees --> rank 0 loads and broadcasts + LoRA, saved or new --> every rank builds the adapter as rank 0 does, on a base without weights, and reads the base + LoRA whose initialization decomposes the base weights (PiSSA) --> rank 0 loads and broadcasts FSDP2 is real on a one-rank CPU mesh and the broadcast is recorded; the CUDA worker splits the shards over two ranks. """ @@ -23,6 +25,7 @@ TinyBackend, TinyPipelineConfig, make_model_loader_args, + save_component_lora_adapters, ) from torch.distributed.device_mesh import init_device_mesh @@ -41,10 +44,13 @@ def __init__(self): def load_component(self, component, *, checkpoint_path, master_dtype, materialize_weights): self.materialize_requests.append(materialize_weights) + # from_pretrained initializes no weight: with weights it draws what the meta build draws. + rng_state = torch.get_rng_state() model = super().load_component( component, checkpoint_path="actor", master_dtype=master_dtype, materialize_weights=False ) if materialize_weights: + torch.set_rng_state(rng_state) with torch.no_grad(): model.block.proj.weight.fill_(BROADCAST_VALUE) return model @@ -68,7 +74,7 @@ def save_checkpoint(path, *, name="block.proj.weight", shape=(4, 3), sharded=Tru ) -def load(monkeypatch, path, *, agree=lambda flag: flag, **kwargs): +def load(monkeypatch, path, *, agree=lambda flag: flag, lora_init=None, backend_cls=None, **kwargs): broadcasts = [] monkeypatch.setattr(model_loader.checkpoint, "all_ranks_agree", agree) monkeypatch.setattr(model_loader.checkpoint, "sync_model_dtypes", lambda model: None) @@ -80,8 +86,9 @@ def load(monkeypatch, path, *, agree=lambda flag: flag, **kwargs): 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(), FileBackend() - args.use_lora = False + args, backend = make_model_loader_args(), (backend_cls or FileBackend)() + args.use_lora = lora_init is not None + args.lora_rank, args.lora_alpha, args.lora_target_modules, args.lora_init_weights = 2, 4, ["proj"], lora_init models = model_loader.load_fsdp_models( args, backend, TinyPipelineConfig(), parallel, checkpoint_path=str(path), **kwargs ) @@ -172,19 +179,79 @@ def drawing_load_component(self, component, **kwargs): assert torch.equal(states["renamed"][1], states["no files"][1]) -def test_one_rank_that_cannot_read_the_files_sends_every_rank_to_the_broadcast(tmp_path, monkeypatch): +def test_one_rank_that_cannot_see_the_files_sends_every_rank_to_the_broadcast(tmp_path, monkeypatch): save_checkpoint(tmp_path) flags = [] _, materialize_requests, broadcasts = load(monkeypatch, tmp_path, agree=lambda flag: flags.append(flag) or False) - assert flags == [True, True] and materialize_requests == [False, True, False, True] and len(broadcasts) == 2 + assert flags == [True, True] and materialize_requests == [True, True] and len(broadcasts) == 2 -def test_lora_models_are_broadcast(tmp_path, monkeypatch): +def agree_on_the_files_only(): + """Every rank sees the files; then one of them finds another state dict in its copy.""" + answers = [] + return lambda flag: answers.append(flag) or len(answers) % 2 == 1 + + +def test_one_rank_whose_files_hold_another_state_sends_every_rank_to_the_broadcast(tmp_path, monkeypatch): + save_checkpoint(tmp_path) + _, materialize_requests, broadcasts = load(monkeypatch, tmp_path, agree=agree_on_the_files_only()) + assert materialize_requests == [False, True, False, True] and len(broadcasts) == 2 + + +def lora_weights(state): + return {name: tensor for name, tensor in state.items() if "lora_" in name} + + +def test_saved_adapters_are_built_on_every_rank_and_the_base_is_read_from_the_files(tmp_path, monkeypatch): + save_checkpoint(tmp_path) + adapter_paths = save_component_lora_adapters(tmp_path / "adapters") + models, materialize_requests, broadcasts = load(monkeypatch, tmp_path, lora_adapter_paths=adapter_paths) + assert materialize_requests == [False, False] and broadcasts == [] + for index, (component, model) in enumerate(models.items()): + proj = model.base_model.model.block.proj + assert torch.equal(proj.base_layer.weight.to_local(), saved_weight(component).float()) + assert torch.all(proj.lora_A.default.weight.to_local() == 0.15 + 0.1 * index) + assert torch.all(proj.lora_B.default.weight.to_local() == 0.25 + 0.1 * index) + assert not any(parameter.requires_grad for parameter in model.parameters()) + assert model.base_model.model.forward_count.item() == 0 + + +@pytest.mark.parametrize("lora_init", ["gaussian", "kaiming-uniform"]) +def test_a_new_adapter_gets_the_values_and_leaves_the_generator_as_rank_0_does_with_weights( + tmp_path, monkeypatch, lora_init +): save_checkpoint(tmp_path) - monkeypatch.setattr(model_loader, "load_lora_adapter", lambda model, path, *, trainable: model) - agree = lambda flag: pytest.fail("LoRA loads are never read from the files") # noqa: E731 - _, materialize_requests, broadcasts = load(monkeypatch, tmp_path, agree=agree, lora_adapter_paths=["a", "b"]) + torch.manual_seed(0) + models, materialize_requests, broadcasts = load(monkeypatch, tmp_path, lora_init=lora_init, trainable=True) + generator = torch.get_rng_state() + assert materialize_requests == [False, False] and broadcasts == [] + + torch.manual_seed(0) + _, materialize_requests, with_weights = load( + monkeypatch, tmp_path, lora_init=lora_init, trainable=True, agree=agree_on_the_files_only() + ) + assert materialize_requests == [False, True, False, True] and torch.equal(torch.get_rng_state(), generator) + for (component, model), state in zip(models.items(), with_weights, strict=True): + adapter = lora_weights({name: parameter.to_local() for name, parameter in model.named_parameters()}) + assert len(adapter) == 2 and adapter.keys() == lora_weights(state).keys() + assert all(torch.equal(adapter[name], state[name]) and adapter[name].requires_grad for name in adapter) + assert adapter["base_model.model.block.proj.lora_A.default.weight"].abs().sum() > 0 + base = model.base_model.model.block.proj.base_layer.weight + assert torch.equal(base.to_local(), saved_weight(component).float()) and not base.requires_grad + + +def test_an_adapter_initialized_from_the_base_weights_is_built_by_rank_0_and_broadcast(tmp_path, monkeypatch): + class NeverAsked(FileBackend): + def safetensors_files(self, component, *, checkpoint_path): + pytest.fail("PiSSA decomposes the base weights, which only rank 0 holds") + + save_checkpoint(tmp_path) + agree = lambda flag: pytest.fail("no rank reads the files") # noqa: E731 + _, materialize_requests, broadcasts = load( + monkeypatch, tmp_path, lora_init="pissa", trainable=True, agree=agree, backend_cls=NeverAsked + ) assert materialize_requests == [True, True] and len(broadcasts) == 2 + assert all(len(lora_weights(state)) == 2 for state in broadcasts) if __name__ == "__main__": From 0e6ba5450e05ee81def46d7466d9868661344a4a Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:26:42 +0000 Subject: [PATCH 05/31] fix(fsdp): a component built without weights gives the state dict's buffers the dtype a load gives them, as it does the parameters --- miles/backends/fsdp_utils/model_backend.py | 28 +++++-- .../backends/fsdp_utils/test_model_backend.py | 82 +++++++++++++++++++ 2 files changed, 102 insertions(+), 8 deletions(-) diff --git a/miles/backends/fsdp_utils/model_backend.py b/miles/backends/fsdp_utils/model_backend.py index bd8a392a5..ca737e2e0 100644 --- a/miles/backends/fsdp_utils/model_backend.py +++ b/miles/backends/fsdp_utils/model_backend.py @@ -24,6 +24,7 @@ import logging import os from dataclasses import replace +from itertools import chain from pathlib import Path import torch @@ -204,10 +205,9 @@ 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 @@ -216,12 +216,24 @@ def load_component( 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 and keep_in_fp32 is not None: - for name, param in model.named_parameters(): - if any(module in name.split(".") for module in keep_in_fp32): - param.data = param.data.to(torch.float32) + 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: """The files ``from_pretrained`` reads with no variant: the ones the index lists, else the single file.""" stem = SAFETENSORS_WEIGHTS_NAME.removesuffix(".safetensors") diff --git a/tests/fast/backends/fsdp_utils/test_model_backend.py b/tests/fast/backends/fsdp_utils/test_model_backend.py index 0a567b049..445b5616e 100644 --- a/tests/fast/backends/fsdp_utils/test_model_backend.py +++ b/tests/fast/backends/fsdp_utils/test_model_backend.py @@ -9,10 +9,15 @@ register_cpu_ci(est_time=15, suite="stage-a-cpu", labels=[]) import json +from itertools import chain +import pytest import torch +from diffusers import ConfigMixin, ModelMixin, SD3Transformer2DModel, WanTransformer3DModel +from diffusers.configuration_utils import register_to_config 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 @@ -53,6 +58,83 @@ def from_pretrained(cls, checkpoint_path, *, torch_dtype, **kwargs): return cls().to(torch_dtype) +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) + + +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.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] + + class TestBackendHierarchy: def test_concrete_backends_are_sibling_implementations(self): assert issubclass(MilesModelBackend, BaseModelBackend) From 31ca0c41d33dea88a38b5e9441b6f27d945b9667 Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:27:06 +0000 Subject: [PATCH 06/31] fix(fsdp): a single weights file at the root of a local checkpoint leaves the load to rank 0, since from_pretrained reads it before the component's --- miles/backends/fsdp_utils/model_backend.py | 14 +++++++++++--- .../fast/backends/fsdp_utils/test_model_backend.py | 13 +++++++++++++ 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/miles/backends/fsdp_utils/model_backend.py b/miles/backends/fsdp_utils/model_backend.py index ca737e2e0..108f06eef 100644 --- a/miles/backends/fsdp_utils/model_backend.py +++ b/miles/backends/fsdp_utils/model_backend.py @@ -60,7 +60,10 @@ def load_component( 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.""" + """Local safetensors files every rank can read its shards of the component from; None: rank 0 loads it. + + They hold what ``load_component`` loads: a backend that loads other weights names its own files or none. + """ return None @abc.abstractmethod @@ -237,16 +240,21 @@ def _cast_state_as_a_load_does(model: torch.nn.Module, master_dtype: torch.dtype def safetensors_files(self, component: str, *, checkpoint_path: str) -> list[Path] | None: """The files ``from_pretrained`` reads with no variant: the ones the index lists, else the single file.""" stem = SAFETENSORS_WEIGHTS_NAME.removesuffix(".safetensors") - if not os.path.isdir(checkpoint_path): + is_local = os.path.isdir(checkpoint_path) + if not is_local: from huggingface_hub import snapshot_download patterns = [f"{component}/{SAFETENSORS_WEIGHTS_NAME}*", f"{component}/{stem}-*.safetensors"] checkpoint_path = snapshot_download(checkpoint_path, allow_patterns=patterns) folder = Path(checkpoint_path) / component index = folder / SAFE_WEIGHTS_INDEX_NAME - names = {SAFETENSORS_WEIGHTS_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 diff --git a/tests/fast/backends/fsdp_utils/test_model_backend.py b/tests/fast/backends/fsdp_utils/test_model_backend.py index 445b5616e..0ed6ce5ae 100644 --- a/tests/fast/backends/fsdp_utils/test_model_backend.py +++ b/tests/fast/backends/fsdp_utils/test_model_backend.py @@ -223,3 +223,16 @@ def snapshot_download(repo_id, *, allow_patterns): ], ) ] + + 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 From d3fbbc2f470ab5a3fa04586dbb0564bf7a5731fb Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:27:07 +0000 Subject: [PATCH 07/31] fix(fsdp): a checkpoint that is neither a folder nor a repo id names no files, so load_component reports it as before --- miles/backends/fsdp_utils/model_backend.py | 7 ++++++- tests/fast/backends/fsdp_utils/test_model_backend.py | 5 +++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/miles/backends/fsdp_utils/model_backend.py b/miles/backends/fsdp_utils/model_backend.py index 108f06eef..321a83354 100644 --- a/miles/backends/fsdp_utils/model_backend.py +++ b/miles/backends/fsdp_utils/model_backend.py @@ -243,9 +243,14 @@ def safetensors_files(self, component: str, *, checkpoint_path: str) -> list[Pat is_local = os.path.isdir(checkpoint_path) if not is_local: from huggingface_hub import snapshot_download + from huggingface_hub.errors import HFValidationError patterns = [f"{component}/{SAFETENSORS_WEIGHTS_NAME}*", f"{component}/{stem}-*.safetensors"] - checkpoint_path = snapshot_download(checkpoint_path, allow_patterns=patterns) + try: + checkpoint_path = snapshot_download(checkpoint_path, allow_patterns=patterns) + except HFValidationError: + # Neither a folder nor a repo id: load_component says so. + return None folder = Path(checkpoint_path) / component index = folder / SAFE_WEIGHTS_INDEX_NAME if index.is_file(): diff --git a/tests/fast/backends/fsdp_utils/test_model_backend.py b/tests/fast/backends/fsdp_utils/test_model_backend.py index 0ed6ce5ae..e42a7bb59 100644 --- a/tests/fast/backends/fsdp_utils/test_model_backend.py +++ b/tests/fast/backends/fsdp_utils/test_model_backend.py @@ -236,3 +236,8 @@ def test_a_weights_file_at_the_root_of_a_local_checkpoint_leaves_the_load_to_ran (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 From 8398f283f784a11ac10147b44c20fe2d86bdfa59 Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:27:53 +0000 Subject: [PATCH 08/31] fix(fsdp): a buffer on meta that no file holds sends the component to the broadcast; one the files hold is read; one two modules share keeps its value on both --- miles/backends/fsdp_utils/checkpoint.py | 20 +++-- .../fsdp_utils/test_safetensors_load.py | 79 ++++++++++++++++++- 2 files changed, 91 insertions(+), 8 deletions(-) diff --git a/miles/backends/fsdp_utils/checkpoint.py b/miles/backends/fsdp_utils/checkpoint.py index 5b8d1a9e0..57977d9ad 100644 --- a/miles/backends/fsdp_utils/checkpoint.py +++ b/miles/backends/fsdp_utils/checkpoint.py @@ -68,14 +68,20 @@ def broadcast_full_state_to_fsdp( def safetensors_hold_state(model: torch.nn.Module, files: list[Path]) -> bool: - """Whether the files hold the model's state dict: the same names, each with the same shape.""" + """Whether the files hold the model's state dict: the same names, each with the same shape. + + A buffer outside the state dict is in no file, so it must hold the value its constructor computed. + """ from safetensors import safe_open + state = model.state_dict() + if any(buffer.is_meta for name, buffer in model.named_buffers() if name not in state): + return False 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()}) - return saved == {name: tuple(tensor.shape) for name, tensor in model.state_dict().items()} + return saved == {name: tuple(tensor.shape) for name, tensor in state.items()} def all_ranks_agree(flag: bool) -> bool: @@ -88,11 +94,13 @@ def all_ranks_agree(flag: bool) -> bool: 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.""" device = torch.cuda.current_device() - # Buffers were computed for real on every rank; to_empty would wipe them. - buffers = dict(model.named_buffers()) + # 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(): - buffer.copy_(buffers[name]) + 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: diff --git a/tests/fast/backends/fsdp_utils/test_safetensors_load.py b/tests/fast/backends/fsdp_utils/test_safetensors_load.py index 145e49c56..f46f427a9 100644 --- a/tests/fast/backends/fsdp_utils/test_safetensors_load.py +++ b/tests/fast/backends/fsdp_utils/test_safetensors_load.py @@ -21,6 +21,7 @@ from safetensors.torch import save_file from tests.fast.backends.fsdp_utils.test_reference_models import ( TinyBackend, + TinyComponent, TinyPipelineConfig, make_model_loader_args, ) @@ -68,7 +69,7 @@ def save_checkpoint(path, *, name="block.proj.weight", shape=(4, 3), sharded=Tru ) -def load(monkeypatch, path, *, agree=lambda flag: flag, **kwargs): +def load(monkeypatch, path, *, agree=lambda flag: flag, backend_cls=None, **kwargs): broadcasts = [] monkeypatch.setattr(model_loader.checkpoint, "all_ranks_agree", agree) monkeypatch.setattr(model_loader.checkpoint, "sync_model_dtypes", lambda model: None) @@ -80,7 +81,7 @@ def load(monkeypatch, path, *, agree=lambda flag: flag, **kwargs): 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(), FileBackend() + args, backend = make_model_loader_args(), (backend_cls or FileBackend)() args.use_lora = False models = model_loader.load_fsdp_models( args, backend, TinyPipelineConfig(), parallel, checkpoint_path=str(path), **kwargs @@ -172,6 +173,80 @@ def drawing_load_component(self, component, **kwargs): assert torch.equal(states["renamed"][1], states["no files"][1]) +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): + for component in make_model_loader_args().update_weight_target_modules: + file = path / component / "diffusion_pytorch_model.safetensors" + folder_state = {"block.proj.weight": saved_weight(component), "row_sums": saved_weight(component).sum(dim=1)} + file.parent.mkdir(parents=True) + save_file(folder_state, file) + + +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_sends_every_rank_to_the_broadcast(tmp_path, monkeypatch): + save_checkpoint(tmp_path) + _, materialize_requests, broadcasts = load( + monkeypatch, tmp_path, backend_cls=backend_of(TransientDerivedBufferComponent) + ) + assert materialize_requests == [False, True, False, True] and len(broadcasts) == 2 + + +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)) + + def test_one_rank_that_cannot_read_the_files_sends_every_rank_to_the_broadcast(tmp_path, monkeypatch): save_checkpoint(tmp_path) flags = [] From 13ccdea8adc465cc7648e3a5e5fb351713fb0f89 Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:28:33 +0000 Subject: [PATCH 09/31] refactor(fsdp): holds_on_every_rank(condition) and safetensors_files name what they hold --- miles/backends/fsdp_utils/checkpoint.py | 8 +++---- miles/backends/fsdp_utils/model_loader.py | 24 +++++++++++-------- .../fsdp_utils/test_reference_models.py | 2 +- .../fsdp_utils/test_safetensors_load.py | 16 +++++++------ 4 files changed, 28 insertions(+), 22 deletions(-) diff --git a/miles/backends/fsdp_utils/checkpoint.py b/miles/backends/fsdp_utils/checkpoint.py index 57977d9ad..0628ac070 100644 --- a/miles/backends/fsdp_utils/checkpoint.py +++ b/miles/backends/fsdp_utils/checkpoint.py @@ -84,10 +84,10 @@ def safetensors_hold_state(model: torch.nn.Module, files: list[Path]) -> bool: return saved == {name: tuple(tensor.shape) for name, tensor in state.items()} -def all_ranks_agree(flag: bool) -> bool: - flags = [None] * dist.get_world_size() - dist.all_gather_object(flags, flag) - return all(flags) +def holds_on_every_rank(condition: bool) -> bool: + conditions = [None] * dist.get_world_size() + dist.all_gather_object(conditions, condition) + return all(conditions) @torch.no_grad() diff --git a/miles/backends/fsdp_utils/model_loader.py b/miles/backends/fsdp_utils/model_loader.py index e166ce553..b265981b4 100644 --- a/miles/backends/fsdp_utils/model_loader.py +++ b/miles/backends/fsdp_utils/model_loader.py @@ -42,23 +42,27 @@ def load_fsdp_models( ) # 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 = None if use_lora else model_backend.safetensors_files(component, checkpoint_path=checkpoint_path) - materialize_weights = safetensors is None and dist.get_rank() == 0 + safetensors_files = ( + None if use_lora else model_backend.safetensors_files(component, checkpoint_path=checkpoint_path) + ) + materialize_weights = safetensors_files is None and dist.get_rank() == 0 rng_state = torch.get_rng_state() model = build(materialize_weights=materialize_weights) - if not use_lora and not checkpoint.all_ranks_agree( - safetensors is not None and checkpoint.safetensors_hold_state(model, safetensors) + if not use_lora and not checkpoint.holds_on_every_rank( + safetensors_files is not None and checkpoint.safetensors_hold_state(model, safetensors_files) ): - if safetensors is not None and dist.get_rank() == 0: + if safetensors_files is not None and dist.get_rank() == 0: # A constructor may draw random numbers: the second build draws what the first one did. torch.set_rng_state(rng_state) materialize_weights = True model = build(materialize_weights=True) - safetensors = None + safetensors_files = None if dist.get_rank() == 0: source = "rank 0 loads and broadcasts" - if safetensors is not None: - source = f"every rank reads {len(safetensors)} safetensors files of {safetensors[0].parent}" + 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 {} @@ -69,8 +73,8 @@ def load_fsdp_models( cpu_offload=cpu_offload, args=args, ) - if safetensors is not None: - checkpoint.load_safetensors_to_fsdp(model, safetensors, 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 diff --git a/tests/fast/backends/fsdp_utils/test_reference_models.py b/tests/fast/backends/fsdp_utils/test_reference_models.py index 72e1ce42a..9181e5018 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, "all_ranks_agree", lambda flag: flag) + 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 index f46f427a9..7cab2e213 100644 --- a/tests/fast/backends/fsdp_utils/test_safetensors_load.py +++ b/tests/fast/backends/fsdp_utils/test_safetensors_load.py @@ -69,9 +69,9 @@ def save_checkpoint(path, *, name="block.proj.weight", shape=(4, 3), sharded=Tru ) -def load(monkeypatch, path, *, agree=lambda flag: flag, backend_cls=None, **kwargs): +def load(monkeypatch, path, *, holds=lambda condition: condition, backend_cls=None, **kwargs): broadcasts = [] - monkeypatch.setattr(model_loader.checkpoint, "all_ranks_agree", agree) + 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) @@ -249,16 +249,18 @@ def test_a_buffer_two_modules_share_keeps_its_value_on_both(tmp_path, monkeypatc def test_one_rank_that_cannot_read_the_files_sends_every_rank_to_the_broadcast(tmp_path, monkeypatch): save_checkpoint(tmp_path) - flags = [] - _, materialize_requests, broadcasts = load(monkeypatch, tmp_path, agree=lambda flag: flags.append(flag) or False) - assert flags == [True, True] and materialize_requests == [False, True, False, True] and len(broadcasts) == 2 + conditions = [] + _, materialize_requests, broadcasts = load( + monkeypatch, tmp_path, holds=lambda condition: conditions.append(condition) or False + ) + assert conditions == [True, True] and materialize_requests == [False, True, False, True] and len(broadcasts) == 2 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) - agree = lambda flag: pytest.fail("LoRA loads are never read from the files") # noqa: E731 - _, materialize_requests, broadcasts = load(monkeypatch, tmp_path, agree=agree, lora_adapter_paths=["a", "b"]) + 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 From 34b5655b06d02874f29b488a6507284642db3b9f Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:31:49 +0000 Subject: [PATCH 10/31] fix(fsdp): only a model with an adapter takes the adapter step; one without no longer gets base storage and the generator broadcast --- miles/backends/fsdp_utils/model_loader.py | 10 +++++++--- .../backends/fsdp_utils/test_safetensors_load.py | 13 +++++++++++++ 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/miles/backends/fsdp_utils/model_loader.py b/miles/backends/fsdp_utils/model_loader.py index 84073d8c3..54dafe3b0 100644 --- a/miles/backends/fsdp_utils/model_loader.py +++ b/miles/backends/fsdp_utils/model_loader.py @@ -51,7 +51,8 @@ def load_fsdp_models( safetensors_files = None materialize_weights = safetensors_files is None and dist.get_rank() == 0 rng_state = torch.get_rng_state() - model = build(materialize_weights=materialize_weights, lora_on_every_rank=safetensors_files is not None) + lora_on_every_rank = has_lora and safetensors_files is not None + model = build(materialize_weights=materialize_weights, lora_on_every_rank=lora_on_every_rank) if safetensors_files is not None and not checkpoint.holds_on_every_rank( checkpoint.safetensors_hold_state(model, safetensors_files) ): @@ -122,7 +123,10 @@ def build_component( materialize_weights: bool, lora_on_every_rank: bool, ) -> torch.nn.Module: - """``lora_on_every_rank``: every rank builds the adapter's values as rank 0 does, on a base without weights.""" + """``lora_on_every_rank``: every rank builds the adapter's values as rank 0 does, on a base without weights. + + It is for a model that has an adapter, and for all ranks at once: the build then runs a collective. + """ with model_init_context(materialize_weights=materialize_weights): model = model_backend.load_component( component, @@ -135,7 +139,7 @@ def build_component( if trainable and args.gradient_checkpointing: model_backend.enable_gradient_checkpointing(model) materialize_lora = lora_on_every_rank or dist.get_rank() == 0 - with base_storage_for_lora(model, enabled=materialize_lora and not materialize_weights): + with base_storage_for_lora(model, enabled=lora_on_every_rank): if lora_adapter_path is not None: model = load_lora_adapter(model, lora_adapter_path, trainable=trainable, materialize=materialize_lora) elif trainable and args.use_lora: diff --git a/tests/fast/backends/fsdp_utils/test_safetensors_load.py b/tests/fast/backends/fsdp_utils/test_safetensors_load.py index 9d29adcc2..1c78623ae 100644 --- a/tests/fast/backends/fsdp_utils/test_safetensors_load.py +++ b/tests/fast/backends/fsdp_utils/test_safetensors_load.py @@ -275,6 +275,19 @@ def test_one_rank_whose_files_hold_another_state_sends_every_rank_to_the_broadca assert materialize_requests == [False, True, False, True] and len(broadcasts) == 2 +def test_a_model_without_an_adapter_skips_the_adapter_step(tmp_path, monkeypatch): + # The step gives every base parameter storage and runs a collective: neither is for a model with no adapter. + save_checkpoint(tmp_path) + monkeypatch.setattr( + model_loader.checkpoint, "rank0_rng_state", lambda: pytest.fail("no adapter is built on any rank") + ) + monkeypatch.setattr( + model_loader, "replace_base_parameters", lambda model, data_of: pytest.fail("no parameter gets storage") + ) + _, materialize_requests, broadcasts = load(monkeypatch, tmp_path) + assert materialize_requests == [False, False] and broadcasts == [] + + def lora_weights(state): return {name: tensor for name, tensor in state.items() if "lora_" in name} From a157d4ccd6a81c40f8e158cb1afa6772aeca7ac0 Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:32:18 +0000 Subject: [PATCH 11/31] fix(fsdp): every rank says whether it reads the files even when its adapter rules that out, so a rank's own adapter config cannot change the collectives it runs --- miles/backends/fsdp_utils/model_loader.py | 5 +++-- .../backends/fsdp_utils/test_safetensors_load.py | 12 +++++++++--- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/miles/backends/fsdp_utils/model_loader.py b/miles/backends/fsdp_utils/model_loader.py index 54dafe3b0..62a0e458e 100644 --- a/miles/backends/fsdp_utils/model_loader.py +++ b/miles/backends/fsdp_utils/model_loader.py @@ -47,8 +47,9 @@ def load_fsdp_models( safetensors_files = None if read_per_rank: safetensors_files = model_backend.safetensors_files(component, checkpoint_path=checkpoint_path) - if not checkpoint.holds_on_every_rank(safetensors_files is not None): - safetensors_files = None + # Each rank reads its own adapter config and files, and the collectives below depend on the answer. + if not checkpoint.holds_on_every_rank(safetensors_files is not None): + safetensors_files = None materialize_weights = safetensors_files is None and dist.get_rank() == 0 rng_state = torch.get_rng_state() lora_on_every_rank = has_lora and safetensors_files is not None diff --git a/tests/fast/backends/fsdp_utils/test_safetensors_load.py b/tests/fast/backends/fsdp_utils/test_safetensors_load.py index 1c78623ae..cf6d654a2 100644 --- a/tests/fast/backends/fsdp_utils/test_safetensors_load.py +++ b/tests/fast/backends/fsdp_utils/test_safetensors_load.py @@ -336,11 +336,17 @@ def safetensors_files(self, component, *, checkpoint_path): pytest.fail("PiSSA decomposes the base weights, which only rank 0 holds") save_checkpoint(tmp_path) - holds = lambda condition: pytest.fail("no rank reads the files") # noqa: E731 + conditions = [] _, materialize_requests, broadcasts = load( - monkeypatch, tmp_path, lora_init="pissa", trainable=True, holds=holds, backend_cls=NeverAsked + monkeypatch, + tmp_path, + lora_init="pissa", + trainable=True, + holds=lambda condition: conditions.append(condition) or condition, + backend_cls=NeverAsked, ) - assert materialize_requests == [True, True] and len(broadcasts) == 2 + # Every rank still says that it reads no files, so no rank waits in a collective the others skip. + assert conditions == [False, False] and materialize_requests == [True, True] and len(broadcasts) == 2 assert all(len(lora_weights(state)) == 2 for state in broadcasts) From 46cdf84faf6b46bc9789d2fac0716206df3a6e34 Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:33:14 +0000 Subject: [PATCH 12/31] fix(fsdp): the base stands in as one expanded element while the adapter is built, so --deterministic-mode's NaN fill no longer writes a copy of the model on every rank --- miles/backends/fsdp_utils/model_loader.py | 12 +++++++----- .../backends/fsdp_utils/test_safetensors_load.py | 13 +++++++++++++ 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/miles/backends/fsdp_utils/model_loader.py b/miles/backends/fsdp_utils/model_loader.py index 62a0e458e..6eaee601e 100644 --- a/miles/backends/fsdp_utils/model_loader.py +++ b/miles/backends/fsdp_utils/model_loader.py @@ -159,18 +159,20 @@ def build_component( @contextmanager def base_storage_for_lora(model: torch.nn.Module, *, enabled: bool): - """Give a meta base uninitialized CPU storage while PEFT builds an adapter on it, from rank 0's generator. + """Give a meta base a CPU stand-in while PEFT builds an adapter on it, from rank 0's generator state. - PEFT moves a new adapter to its base layer's device, and meta would drop the adapter's values. Its - initialization draws, and only rank 0 has run it so far: the other ranks draw the same values from rank 0's - generator state and keep their own. + PEFT moves a new adapter to its base layer's device, and meta would drop the adapter's values. It reads the + base layer's device and dtype only, so each base parameter stands in as one uninitialized element expanded to + its shape: a full ``torch.empty`` is written through under ``--deterministic-mode`` (the NaN fill), a copy of + the model on every rank. PEFT's initialization draws, and only rank 0 has run it so far: the other ranks draw + the same values from rank 0's generator state and keep their own. """ if not enabled: yield return rng_state = torch.get_rng_state() torch.set_rng_state(checkpoint.rank0_rng_state()) - replace_base_parameters(model, lambda parameter: torch.empty(parameter.shape, dtype=parameter.dtype)) + replace_base_parameters(model, lambda parameter: torch.empty((), dtype=parameter.dtype).expand(parameter.shape)) try: yield finally: diff --git a/tests/fast/backends/fsdp_utils/test_safetensors_load.py b/tests/fast/backends/fsdp_utils/test_safetensors_load.py index cf6d654a2..c845e06ba 100644 --- a/tests/fast/backends/fsdp_utils/test_safetensors_load.py +++ b/tests/fast/backends/fsdp_utils/test_safetensors_load.py @@ -288,6 +288,19 @@ def test_a_model_without_an_adapter_skips_the_adapter_step(tmp_path, monkeypatch assert materialize_requests == [False, False] and broadcasts == [] +def test_the_base_takes_no_memory_while_the_adapter_is_built(monkeypatch): + # A full torch.empty is written through under --deterministic-mode: a copy of the model on every rank. + monkeypatch.setattr(model_loader.checkpoint, "rank0_rng_state", torch.get_rng_state) + monkeypatch.setattr(model_loader.dist, "get_rank", lambda: 0) + with model_loader.model_init_context(materialize_weights=False): + model = TinyComponent() + with model_loader.base_storage_for_lora(model, enabled=True): + weight = model.block.proj.weight + assert weight.device.type == "cpu" and weight.shape == (4, 3) + assert weight.untyped_storage().nbytes() == weight.element_size() + assert model.block.proj.weight.is_meta + + def lora_weights(state): return {name: tensor for name, tensor in state.items() if "lora_" in name} From 20ea86eaad291ed50b554e5c50cb74f1cfa01849 Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:34:23 +0000 Subject: [PATCH 13/31] fix(fsdp): a saved adapter is built on every rank only when it is a LoRA whose file holds adapter tensors alone; one with a bias or a saved module, or another PEFT type, leaves the load to rank 0 --- miles/backends/fsdp_utils/model_loader.py | 36 ++++++++++++++----- .../fsdp_utils/test_safetensors_load.py | 36 +++++++++++++++++++ 2 files changed, 63 insertions(+), 9 deletions(-) diff --git a/miles/backends/fsdp_utils/model_loader.py b/miles/backends/fsdp_utils/model_loader.py index 6eaee601e..32cee806a 100644 --- a/miles/backends/fsdp_utils/model_loader.py +++ b/miles/backends/fsdp_utils/model_loader.py @@ -5,6 +5,7 @@ from argparse import Namespace from contextlib import contextmanager from functools import partial +from pathlib import Path import torch import torch.distributed as dist @@ -100,16 +101,36 @@ def load_fsdp_models( return models -LORA_INITS_WITHOUT_BASE_WEIGHTS = ("gaussian", "kaiming-uniform") +# PEFT's LoraConfig.init_lora_weights values that never read the base weights; PiSSA, OLoRA, LoftQ... decompose them. +PEFT_INITS_WITHOUT_BASE_WEIGHTS = (True, False, "gaussian") + + +def peft_init_lora_weights(args: Namespace) -> bool | str: + """``--lora-init-weights`` as PEFT's ``LoraConfig.init_lora_weights``.""" + return True if args.lora_init_weights == "kaiming-uniform" else args.lora_init_weights def lora_needs_no_base_weights(args: Namespace, lora_adapter_path: str | None) -> bool: - """Whether PEFT builds the adapter without reading the base weights (PiSSA, OLoRA, LoftQ... decompose them).""" + """Whether every rank can build the adapter on a base that has no weights. + + PEFT's initialization must not read them. A saved adapter must also be a LoRA whose file holds adapter + tensors only: PEFT loads any other tensor it saved (a bias, a module to save) into the base, where the read + of the base checkpoint would replace it. + """ if lora_adapter_path is None: - return args.lora_init_weights in LORA_INITS_WITHOUT_BASE_WEIGHTS - from peft import PeftConfig + return peft_init_lora_weights(args) in PEFT_INITS_WITHOUT_BASE_WEIGHTS + from peft import LoraConfig, PeftConfig + from peft.utils import SAFETENSORS_WEIGHTS_NAME + from safetensors import safe_open - return PeftConfig.from_pretrained(lora_adapter_path).init_lora_weights in (True, False, "gaussian") + config = PeftConfig.from_pretrained(lora_adapter_path) + file = Path(lora_adapter_path) / SAFETENSORS_WEIGHTS_NAME + if not isinstance(config, LoraConfig) or config.init_lora_weights not in PEFT_INITS_WITHOUT_BASE_WEIGHTS: + return False + if not file.is_file(): + return False + with safe_open(file, framework="pt") as tensors: + return all(checkpoint.is_lora_param_name(name) for name in tensors.keys()) def build_component( @@ -234,16 +255,13 @@ def apply_lora( # Per-model fallback when --lora-target-modules is unset (runtime inference: depends on loaded pipeline). targets = args.lora_target_modules or train_pipeline_config.lora_target_modules - init_lora_weight = args.lora_init_weights - if init_lora_weight == "kaiming-uniform": - init_lora_weight = True # namely kaiming-uniform model = get_peft_model( model, LoraConfig( r=args.lora_rank, lora_alpha=args.lora_alpha, target_modules=targets, - init_lora_weights=init_lora_weight if materialize else False, + init_lora_weights=peft_init_lora_weights(args) if materialize else False, ), low_cpu_mem_usage=not materialize, ) diff --git a/tests/fast/backends/fsdp_utils/test_safetensors_load.py b/tests/fast/backends/fsdp_utils/test_safetensors_load.py index c845e06ba..6f4075a6d 100644 --- a/tests/fast/backends/fsdp_utils/test_safetensors_load.py +++ b/tests/fast/backends/fsdp_utils/test_safetensors_load.py @@ -20,6 +20,7 @@ import pytest import torch import torch.distributed as dist +from peft import LoHaConfig, LoraConfig, get_peft_model from safetensors.torch import save_file from tests.fast.backends.fsdp_utils.test_reference_models import ( TinyBackend, @@ -301,6 +302,41 @@ def test_the_base_takes_no_memory_while_the_adapter_is_built(monkeypatch): assert model.block.proj.weight.is_meta +class BiasedBlock(torch.nn.Module): + def __init__(self): + super().__init__() + self.proj = torch.nn.Linear(3, 4) + self.norm = torch.nn.LayerNorm(4) + + +def save_adapter(path, config, *, init_lora_weights=None): + get_peft_model(BiasedBlock(), config).save_pretrained(path) + if init_lora_weights is not None: + adapter_config = json.loads((path / "adapter_config.json").read_text()) + (path / "adapter_config.json").write_text( + json.dumps(adapter_config | {"init_lora_weights": init_lora_weights}) + ) + return str(path) + + +@pytest.mark.parametrize( + "config, init_lora_weights, builds_on_every_rank", + [ + pytest.param(LoraConfig(r=2, target_modules=["proj"]), None, True, id="adapter tensors only"), + pytest.param(LoraConfig(r=2, target_modules=["proj"], bias="all"), None, False, id="a bias of the base"), + pytest.param(LoraConfig(r=2, target_modules=["proj"], modules_to_save=["norm"]), None, False, id="a module"), + pytest.param(LoraConfig(r=2, target_modules=["proj"]), "pissa", False, id="an init from the base weights"), + pytest.param(LoHaConfig(r=2, target_modules=["proj"]), None, False, id="not a LoRA"), + ], +) +def test_a_saved_adapter_is_built_on_every_rank_only_when_it_holds_lora_tensors_alone( + tmp_path, config, init_lora_weights, builds_on_every_rank +): + # PEFT loads a bias or a saved module into the base, and the read of the base checkpoint would replace it. + adapter_path = save_adapter(tmp_path, config, init_lora_weights=init_lora_weights) + assert model_loader.lora_needs_no_base_weights(make_model_loader_args(), adapter_path) is builds_on_every_rank + + def lora_weights(state): return {name: tensor for name, tensor in state.items() if "lora_" in name} From 04176f9aa3990e105a77f6ee21078373959d726f Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:35:37 +0000 Subject: [PATCH 14/31] refactor(fsdp): base_state takes the checkpoint's names from to_hf_name, the helper weight sync already uses --- miles/backends/fsdp_utils/checkpoint.py | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/miles/backends/fsdp_utils/checkpoint.py b/miles/backends/fsdp_utils/checkpoint.py index b0c316bff..9bf7ddffe 100644 --- a/miles/backends/fsdp_utils/checkpoint.py +++ b/miles/backends/fsdp_utils/checkpoint.py @@ -15,6 +15,8 @@ from torch.distributed.checkpoint.state_dict import StateDictOptions, get_state_dict, set_state_dict from torch.distributed.checkpoint.stateful import Stateful +from .hf_weight_iterator import to_hf_name + logger = logging.getLogger(__name__) @@ -69,11 +71,7 @@ def broadcast_full_state_to_fsdp( def base_state(model: torch.nn.Module) -> dict[str, torch.Tensor]: """The state dict without LoRA adapters, under the names the base checkpoint gives its tensors.""" - return { - name.removeprefix("base_model.model.").replace(".base_layer.", "."): tensor - for name, tensor in model.state_dict().items() - if not is_lora_param_name(name) - } + return {to_hf_name(name): tensor for name, tensor in model.state_dict().items() if not is_lora_param_name(name)} def safetensors_hold_state(model: torch.nn.Module, files: list[Path]) -> bool: From 2ea73ffeb0e098c5a777807f7869e12be43a36d6 Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:59:14 +0000 Subject: [PATCH 15/31] fix(fsdp): a saved DoRA adapter leaves the load to rank 0: PEFT takes the norm of the base weights for any magnitude the file lacks --- miles/backends/fsdp_utils/model_loader.py | 17 +++++++++-------- .../fsdp_utils/test_safetensors_load.py | 4 +++- 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/miles/backends/fsdp_utils/model_loader.py b/miles/backends/fsdp_utils/model_loader.py index 32cee806a..4c7745f49 100644 --- a/miles/backends/fsdp_utils/model_loader.py +++ b/miles/backends/fsdp_utils/model_loader.py @@ -113,9 +113,10 @@ def peft_init_lora_weights(args: Namespace) -> bool | str: def lora_needs_no_base_weights(args: Namespace, lora_adapter_path: str | None) -> bool: """Whether every rank can build the adapter on a base that has no weights. - PEFT's initialization must not read them. A saved adapter must also be a LoRA whose file holds adapter - tensors only: PEFT loads any other tensor it saved (a bias, a module to save) into the base, where the read - of the base checkpoint would replace it. + PEFT must not read the base weights' values while it builds the adapter: PiSSA, OLoRA, LoftQ... decompose + them, and DoRA takes their norm. A saved adapter must also be a LoRA whose file holds adapter tensors only: + PEFT loads any other tensor it saved (a bias, a module to save) into the base, where the read of the base + checkpoint would replace it. """ if lora_adapter_path is None: return peft_init_lora_weights(args) in PEFT_INITS_WITHOUT_BASE_WEIGHTS @@ -125,9 +126,9 @@ def lora_needs_no_base_weights(args: Namespace, lora_adapter_path: str | None) - config = PeftConfig.from_pretrained(lora_adapter_path) file = Path(lora_adapter_path) / SAFETENSORS_WEIGHTS_NAME - if not isinstance(config, LoraConfig) or config.init_lora_weights not in PEFT_INITS_WITHOUT_BASE_WEIGHTS: + if not isinstance(config, LoraConfig) or config.use_dora: return False - if not file.is_file(): + if config.init_lora_weights not in PEFT_INITS_WITHOUT_BASE_WEIGHTS or not file.is_file(): return False with safe_open(file, framework="pt") as tensors: return all(checkpoint.is_lora_param_name(name) for name in tensors.keys()) @@ -182,9 +183,9 @@ def build_component( def base_storage_for_lora(model: torch.nn.Module, *, enabled: bool): """Give a meta base a CPU stand-in while PEFT builds an adapter on it, from rank 0's generator state. - PEFT moves a new adapter to its base layer's device, and meta would drop the adapter's values. It reads the - base layer's device and dtype only, so each base parameter stands in as one uninitialized element expanded to - its shape: a full ``torch.empty`` is written through under ``--deterministic-mode`` (the NaN fill), a copy of + PEFT moves a new adapter to its base layer's device, and meta would drop the adapter's values. For the + adapters ``lora_needs_no_base_weights`` lets through it reads the base layer's device and dtype only, so each + base parameter stands in as one uninitialized element expanded to its shape: a full ``torch.empty`` is written through under ``--deterministic-mode`` (the NaN fill), a copy of the model on every rank. PEFT's initialization draws, and only rank 0 has run it so far: the other ranks draw the same values from rank 0's generator state and keep their own. """ diff --git a/tests/fast/backends/fsdp_utils/test_safetensors_load.py b/tests/fast/backends/fsdp_utils/test_safetensors_load.py index 6f4075a6d..f8a7fce4d 100644 --- a/tests/fast/backends/fsdp_utils/test_safetensors_load.py +++ b/tests/fast/backends/fsdp_utils/test_safetensors_load.py @@ -326,13 +326,15 @@ def save_adapter(path, config, *, init_lora_weights=None): pytest.param(LoraConfig(r=2, target_modules=["proj"], bias="all"), None, False, id="a bias of the base"), pytest.param(LoraConfig(r=2, target_modules=["proj"], modules_to_save=["norm"]), None, False, id="a module"), pytest.param(LoraConfig(r=2, target_modules=["proj"]), "pissa", False, id="an init from the base weights"), + pytest.param(LoraConfig(r=2, target_modules=["proj"], use_dora=True), None, False, id="DoRA"), pytest.param(LoHaConfig(r=2, target_modules=["proj"]), None, False, id="not a LoRA"), ], ) def test_a_saved_adapter_is_built_on_every_rank_only_when_it_holds_lora_tensors_alone( tmp_path, config, init_lora_weights, builds_on_every_rank ): - # PEFT loads a bias or a saved module into the base, and the read of the base checkpoint would replace it. + # PEFT loads a bias or a saved module into the base, and the read of the base checkpoint would replace it; + # DoRA's magnitude is the norm of the base weights, which no rank holds while it builds the adapter. adapter_path = save_adapter(tmp_path, config, init_lora_weights=init_lora_weights) assert model_loader.lora_needs_no_base_weights(make_model_loader_args(), adapter_path) is builds_on_every_rank From 6cf4870a40e52d33d46311492194d92cff736153 Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Tue, 17 Nov 2026 02:00:30 +0000 Subject: [PATCH 16/31] fix(fsdp): a buffer no file holds takes rank 0's value on every rank after the read, as the broadcast leaves it --- miles/backends/fsdp_utils/checkpoint.py | 10 +++++++++- .../backends/fsdp_utils/_safetensors_load_worker.py | 13 ++++++++++++- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/miles/backends/fsdp_utils/checkpoint.py b/miles/backends/fsdp_utils/checkpoint.py index 0628ac070..da5bcc36e 100644 --- a/miles/backends/fsdp_utils/checkpoint.py +++ b/miles/backends/fsdp_utils/checkpoint.py @@ -92,7 +92,10 @@ def holds_on_every_rank(condition: bool) -> bool: @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.""" + """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: every rank ends with the value rank 0's constructor computed. + """ 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. @@ -110,6 +113,11 @@ def load_safetensors_to_fsdp(model: torch.nn.Module, files: list[Path], *, cpu_o # CPUOffloadPolicy manages params only; buffers must live on GPU for forward. for buffer in model.buffers(): buffer.data = buffer.data.to(device) + # As the broadcast leaves them: rank 0's values, should a constructor not compute the same on every rank. + state = model.state_dict() + for name, buffer in model.named_buffers(remove_duplicate=False): + if name not in state: + dist.broadcast(buffer, src=0) def _is_lora_param_name(name: str) -> bool: diff --git a/tests/fast-gpu/backends/fsdp_utils/_safetensors_load_worker.py b/tests/fast-gpu/backends/fsdp_utils/_safetensors_load_worker.py index 88b366cfe..15950c03b 100644 --- a/tests/fast-gpu/backends/fsdp_utils/_safetensors_load_worker.py +++ b/tests/fast-gpu/backends/fsdp_utils/_safetensors_load_worker.py @@ -1,6 +1,7 @@ """Two ranks read their own halves of a safetensors checkpoint, or fall back to rank 0's broadcast together. 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 --> rank 0's value on both ranks another name in the files --> rank 0 builds again with weights --> the broadcast value on both ranks """ @@ -23,9 +24,18 @@ 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.""" + + 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(), FileBackend() + 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 @@ -35,6 +45,7 @@ def load(mesh, path, cpu_offload): 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() == 0 return models, backend.materialize_requests From 9ca202cb4e73ea5441cfc87dd23e636745b325dc Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Tue, 17 Nov 2026 02:01:02 +0000 Subject: [PATCH 17/31] fix(fsdp): a DiffusersModelBackend subclass that overrides load_component names no files, so the files cannot replace the weights it loads --- docs/user-guide/customization.md | 4 ++ miles/backends/fsdp_utils/model_backend.py | 56 +++++++++++-------- .../backends/fsdp_utils/test_model_backend.py | 14 +++++ .../fsdp_utils/test_safetensors_load.py | 5 +- 4 files changed, 54 insertions(+), 25 deletions(-) diff --git a/docs/user-guide/customization.md b/docs/user-guide/customization.md index d4eed2185..ee6d1d867 100644 --- a/docs/user-guide/customization.md +++ b/docs/user-guide/customization.md @@ -381,6 +381,10 @@ 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 that overrides `load_component` loads on rank 0 and broadcasts, as before, +unless it also overrides `safetensors_files` to name the files that hold what it loads. + *** ## Worked example diff --git a/miles/backends/fsdp_utils/model_backend.py b/miles/backends/fsdp_utils/model_backend.py index 321a83354..e68e082e4 100644 --- a/miles/backends/fsdp_utils/model_backend.py +++ b/miles/backends/fsdp_utils/model_backend.py @@ -38,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 + + patterns = [f"{component}/{SAFETENSORS_WEIGHTS_NAME}*", f"{component}/{stem}-*.safetensors"] + try: + checkpoint_path = snapshot_download(checkpoint_path, allow_patterns=patterns) + except HFValidationError: + # Neither a folder nor a repo id: 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.""" @@ -238,30 +268,10 @@ def _cast_state_as_a_load_does(model: torch.nn.Module, master_dtype: torch.dtype tensor.data = tensor.data.to(torch.float32 if pinned else master_dtype) def safetensors_files(self, component: str, *, checkpoint_path: str) -> list[Path] | None: - """The files ``from_pretrained`` reads with no variant: the ones the index lists, else the single file.""" - 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 - - patterns = [f"{component}/{SAFETENSORS_WEIGHTS_NAME}*", f"{component}/{stem}-*.safetensors"] - try: - checkpoint_path = snapshot_download(checkpoint_path, allow_patterns=patterns) - except HFValidationError: - # Neither a folder nor a repo id: 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. + # The files hold what this class's load_component loads; a subclass that loads other weights names its own. + if type(self).load_component is not DiffusersModelBackend.load_component: 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 + 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 e42a7bb59..b4ce24d90 100644 --- a/tests/fast/backends/fsdp_utils/test_model_backend.py +++ b/tests/fast/backends/fsdp_utils/test_model_backend.py @@ -241,3 +241,17 @@ def test_a_checkpoint_that_is_neither_a_folder_nor_a_repo_id_names_no_files(self # 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 + + def test_a_backend_that_loads_other_weights_names_no_files(self, tmp_path): + # Rank 0's load_component result was broadcast; the files must not replace what a subclass loads. + class OtherWeightsBackend(DiffusersModelBackend): + def load_component(self, component, **kwargs): + raise NotImplementedError + + (tmp_path / "transformer").mkdir() + (tmp_path / "transformer" / "diffusion_pytorch_model.safetensors").touch() + + assert DiffusersModelBackend(None).safetensors_files("transformer", checkpoint_path=str(tmp_path)) == [ + tmp_path / "transformer" / "diffusion_pytorch_model.safetensors" + ] + assert OtherWeightsBackend(None).safetensors_files("transformer", checkpoint_path=str(tmp_path)) is None diff --git a/tests/fast/backends/fsdp_utils/test_safetensors_load.py b/tests/fast/backends/fsdp_utils/test_safetensors_load.py index 7cab2e213..0e78d7d52 100644 --- a/tests/fast/backends/fsdp_utils/test_safetensors_load.py +++ b/tests/fast/backends/fsdp_utils/test_safetensors_load.py @@ -28,13 +28,14 @@ from torch.distributed.device_mesh import init_device_mesh from miles.backends.fsdp_utils import model_loader -from miles.backends.fsdp_utils.model_backend import DiffusersModelBackend +from miles.backends.fsdp_utils.model_backend import diffusers_weight_files BROADCAST_VALUE = 0.75 class FileBackend(TinyBackend): - safetensors_files = DiffusersModelBackend.safetensors_files + def safetensors_files(self, component, *, checkpoint_path): + return diffusers_weight_files(checkpoint_path, component) def __init__(self): super().__init__() From 51c40a3c97365098568a8d6d7087a0947a8fb3b2 Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Tue, 17 Nov 2026 02:01:28 +0000 Subject: [PATCH 18/31] fix(fsdp): a repo id the Hub or the offline cache cannot resolve names no files, so load_component reports a mistyped folder as before --- miles/backends/fsdp_utils/model_backend.py | 6 ++--- .../backends/fsdp_utils/test_model_backend.py | 23 +++++++++++++++++++ 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/miles/backends/fsdp_utils/model_backend.py b/miles/backends/fsdp_utils/model_backend.py index e68e082e4..1e300fa58 100644 --- a/miles/backends/fsdp_utils/model_backend.py +++ b/miles/backends/fsdp_utils/model_backend.py @@ -47,13 +47,13 @@ def diffusers_weight_files(checkpoint_path: str, component: str) -> list[Path] | is_local = os.path.isdir(checkpoint_path) if not is_local: from huggingface_hub import snapshot_download - from huggingface_hub.errors import HFValidationError + 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: - # Neither a folder nor a repo id: load_component says so. + 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 diff --git a/tests/fast/backends/fsdp_utils/test_model_backend.py b/tests/fast/backends/fsdp_utils/test_model_backend.py index b4ce24d90..eabf2b98b 100644 --- a/tests/fast/backends/fsdp_utils/test_model_backend.py +++ b/tests/fast/backends/fsdp_utils/test_model_backend.py @@ -11,10 +11,12 @@ 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 miles.backends.fsdp_utils.model_backend import BaseModelBackend, DiffusersModelBackend, MilesModelBackend from miles.backends.fsdp_utils.model_loader import model_init_context @@ -242,6 +244,27 @@ def test_a_checkpoint_that_is_neither_a_folder_nor_a_repo_id_names_no_files(self 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 + def test_a_backend_that_loads_other_weights_names_no_files(self, tmp_path): # Rank 0's load_component result was broadcast; the files must not replace what a subclass loads. class OtherWeightsBackend(DiffusersModelBackend): From 24f3e1b48b68e7c190809fff7b2988d568acb09f Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Tue, 17 Nov 2026 02:04:05 +0000 Subject: [PATCH 19/31] test(fsdp): two ranks whose files differ on one rank only both take the broadcast, through the real rank agreement --- .../backends/fsdp_utils/_safetensors_load_worker.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/tests/fast-gpu/backends/fsdp_utils/_safetensors_load_worker.py b/tests/fast-gpu/backends/fsdp_utils/_safetensors_load_worker.py index 15950c03b..839e192f1 100644 --- a/tests/fast-gpu/backends/fsdp_utils/_safetensors_load_worker.py +++ b/tests/fast-gpu/backends/fsdp_utils/_safetensors_load_worker.py @@ -3,6 +3,7 @@ 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 --> rank 0's value on both ranks another name in the files --> rank 0 builds again with weights --> the broadcast value on both ranks + another name on rank 1 only --> the same: the ranks agree before either reads """ import os @@ -72,6 +73,12 @@ def main(): assert materialize_requests == ([False, True, False, True] if rank == 0 else [False, False]) for model in models.values(): assert torch.all(model.block.proj.weight.to_local() == BROADCAST_VALUE) + + # Only rank 1's copy holds another name: rank 0 must not read its shards while rank 1 waits for a broadcast. + models, materialize_requests = load(mesh, root / ("renamed" if rank == 1 else "state"), cpu_offload) + assert materialize_requests == ([False, True, False, True] if rank == 0 else [False, False]) + for model in models.values(): + assert torch.all(model.block.proj.weight.to_local() == BROADCAST_VALUE) dist.barrier() if rank == 0: print("OK") From 5af5cc8d7ab4cc7ab057d618725a3c27dbdf1521 Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Tue, 17 Nov 2026 02:04:49 +0000 Subject: [PATCH 20/31] test(fsdp): the variant beside the read files has another shape, so reading it fails whatever order the folder lists --- tests/fast/backends/fsdp_utils/test_safetensors_load.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/fast/backends/fsdp_utils/test_safetensors_load.py b/tests/fast/backends/fsdp_utils/test_safetensors_load.py index 0e78d7d52..0048db6f6 100644 --- a/tests/fast/backends/fsdp_utils/test_safetensors_load.py +++ b/tests/fast/backends/fsdp_utils/test_safetensors_load.py @@ -106,8 +106,9 @@ def build(args, model_backend, *rest, **kwargs): 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(4, 3)}, path / component / "diffusion_pytorch_model.fp16.safetensors" + {"block.proj.weight": torch.zeros(8, 3)}, path / component / "diffusion_pytorch_model.fp16.safetensors" ) From e901c3df43531a1b9f668aa4c273405ce57b18f5 Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Tue, 17 Nov 2026 02:04:49 +0000 Subject: [PATCH 21/31] test(fsdp): the files safetensors_files names hold the state a real diffusers load gives, alone and beside a variant; a root-level file is the one diffusers reads --- .../backends/fsdp_utils/test_model_backend.py | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/tests/fast/backends/fsdp_utils/test_model_backend.py b/tests/fast/backends/fsdp_utils/test_model_backend.py index eabf2b98b..eb75a44b0 100644 --- a/tests/fast/backends/fsdp_utils/test_model_backend.py +++ b/tests/fast/backends/fsdp_utils/test_model_backend.py @@ -17,6 +17,7 @@ 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 @@ -60,6 +61,9 @@ def from_pretrained(cls, checkpoint_path, *, torch_dtype, **kwargs): 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.""" @@ -137,6 +141,46 @@ def test_a_component_built_without_weights_has_the_dtypes_a_load_with_weights_gi 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) From c292594e4b39dcc30c9addd2991c61c5af20019b Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Tue, 17 Nov 2026 02:07:53 +0000 Subject: [PATCH 22/31] fix(fsdp): the base is checked for meta before the adapter step, which would leave it on meta whatever the backend built --- miles/backends/fsdp_utils/model_loader.py | 11 ++++++----- .../backends/fsdp_utils/test_safetensors_load.py | 13 +++++++++++++ 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/miles/backends/fsdp_utils/model_loader.py b/miles/backends/fsdp_utils/model_loader.py index 4c7745f49..b164f9dc5 100644 --- a/miles/backends/fsdp_utils/model_loader.py +++ b/miles/backends/fsdp_utils/model_loader.py @@ -157,6 +157,9 @@ def build_component( master_dtype=parse_dtype_from_str(args.fsdp_master_dtype), materialize_weights=materialize_weights, ) + # Before the adapter step, which leaves every base parameter on meta whatever the backend built. + 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 args.fsdp_attention_backend is not None: model_backend.set_attention_backend(model, args.fsdp_attention_backend) if trainable and args.gradient_checkpointing: @@ -170,12 +173,10 @@ def build_component( model.train(trainable) if not trainable: model.requires_grad_(False) - if not materialize_weights and any( - not parameter.is_meta - for name, parameter in model.named_parameters() - if not (lora_on_every_rank and checkpoint.is_lora_param_name(name)) + if not materialize_lora and any( + not parameter.is_meta for name, parameter in model.named_parameters() if checkpoint.is_lora_param_name(name) ): - raise RuntimeError(f"{component} did not honor meta initialization") + raise RuntimeError(f"the adapter of {component} did not honor meta initialization") return model diff --git a/tests/fast/backends/fsdp_utils/test_safetensors_load.py b/tests/fast/backends/fsdp_utils/test_safetensors_load.py index cf56be5d0..a9fc77c3f 100644 --- a/tests/fast/backends/fsdp_utils/test_safetensors_load.py +++ b/tests/fast/backends/fsdp_utils/test_safetensors_load.py @@ -341,6 +341,19 @@ def test_a_saved_adapter_is_built_on_every_rank_only_when_it_holds_lora_tensors_ assert model_loader.lora_needs_no_base_weights(make_model_loader_args(), adapter_path) is builds_on_every_rank +def test_a_base_built_with_weights_is_refused_before_the_adapter_step_would_hide_it(tmp_path, monkeypatch): + class RealBaseBackend(FileBackend): + def load_component(self, component, **kwargs): + model = super().load_component(component, **kwargs) + # Past the ambient init_empty_weights, which would put a parameter registered here on meta. + model.block.proj._parameters["weight"] = torch.nn.Parameter(torch.zeros(4, 3)) + return model + + save_checkpoint(tmp_path) + with pytest.raises(RuntimeError, match="did not honor meta initialization"): + load(monkeypatch, tmp_path, lora_init="gaussian", trainable=True, backend_cls=RealBaseBackend) + + def lora_weights(state): return {name: tensor for name, tensor in state.items() if "lora_" in name} From 9d4a508ce49c37f5632c31b50f33b3fae84ae43a Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Tue, 17 Nov 2026 02:07:53 +0000 Subject: [PATCH 23/31] test(fsdp): the two-rank LoRA case runs a forward on the model read per rank --- .../fsdp_utils/_safetensors_load_worker.py | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/tests/fast-gpu/backends/fsdp_utils/_safetensors_load_worker.py b/tests/fast-gpu/backends/fsdp_utils/_safetensors_load_worker.py index 1f91e6ba2..507122d09 100644 --- a/tests/fast-gpu/backends/fsdp_utils/_safetensors_load_worker.py +++ b/tests/fast-gpu/backends/fsdp_utils/_safetensors_load_worker.py @@ -67,14 +67,27 @@ def adapter_shards(models): } +def adapter_delta(inputs, index, *, saved): + """What the adapter adds to the projection: lora_alpha / r = 2 times B A, and a new adapter's B is zero.""" + if not saved: + return torch.zeros(2, 4) + lora_a, lora_b = torch.full((2, 3), 0.15 + 0.1 * index), torch.full((4, 2), 0.25 + 0.1 * index) + return 2 * (inputs @ lora_a.T) @ lora_b.T + + def check_lora(mesh, root, rank, cpu_offload, **kwargs): # read per rank torch.manual_seed(0) models, materialize_requests = load(mesh, root / "state", cpu_offload, **kwargs) assert materialize_requests == [False, False] - for component, model in models.items(): + inputs = torch.ones(2, 3) + for index, (component, model) in enumerate(models.items()): base = model.base_model.model.block.proj.base_layer.weight.to_local().cpu() assert torch.equal(base, saved_weight(component).float()[2 * rank : 2 * rank + 2]) + delta = adapter_delta(inputs, index, saved="lora_adapter_paths" in kwargs) + with torch.no_grad(): + output = model(inputs.cuda()).cpu() + torch.testing.assert_close(output, (inputs @ saved_weight(component).float().T + delta).tanh()) adapters, generator = adapter_shards(models), torch.get_rng_state() assert len(adapters) == 4 and any(shard.abs().sum() > 0 for shard in adapters.values()) # rank 0 builds with weights, then the real broadcast From 74e33689dd4b7eb3e1b6b95d54cc1c1b4e0f970a Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Tue, 17 Nov 2026 02:08:02 +0000 Subject: [PATCH 24/31] docs(fsdp): base_storage_for_lora states its two boundaries: an Embedding adapter's draws on meta, and rank-local adapter files --- miles/backends/fsdp_utils/model_loader.py | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/miles/backends/fsdp_utils/model_loader.py b/miles/backends/fsdp_utils/model_loader.py index b164f9dc5..390612682 100644 --- a/miles/backends/fsdp_utils/model_loader.py +++ b/miles/backends/fsdp_utils/model_loader.py @@ -186,9 +186,14 @@ def base_storage_for_lora(model: torch.nn.Module, *, enabled: bool): PEFT moves a new adapter to its base layer's device, and meta would drop the adapter's values. For the adapters ``lora_needs_no_base_weights`` lets through it reads the base layer's device and dtype only, so each - base parameter stands in as one uninitialized element expanded to its shape: a full ``torch.empty`` is written through under ``--deterministic-mode`` (the NaN fill), a copy of - the model on every rank. PEFT's initialization draws, and only rank 0 has run it so far: the other ranks draw - the same values from rank 0's generator state and keep their own. + base parameter stands in as one uninitialized element expanded to its shape: a full ``torch.empty`` is written + through under ``--deterministic-mode`` (the NaN fill), a copy of the model on every rank. + + PEFT's initialization draws, and only rank 0 has run it so far: the other ranks draw the same values from + rank 0's generator state and keep their own. An adapter on an ``nn.Embedding`` is the one case where they do + not end as before: PEFT draws for it even on meta, in the build these ranks no longer run. + + Each rank builds from its own copy of the adapter's files, as it reads its own copy of the base's. """ if not enabled: yield From 7d79915b33f93e03ceb5a4c78d33ecabe58206a8 Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Tue, 17 Nov 2026 02:24:39 +0000 Subject: [PATCH 25/31] fix(fsdp): the gate asks a saved adapter's PEFT type, so AdaLoRA, whose config is a LoraConfig too, leaves the load to rank 0 without a first build on every rank --- miles/backends/fsdp_utils/model_loader.py | 5 +++-- tests/fast/backends/fsdp_utils/test_safetensors_load.py | 5 ++++- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/miles/backends/fsdp_utils/model_loader.py b/miles/backends/fsdp_utils/model_loader.py index 390612682..d5da15ff3 100644 --- a/miles/backends/fsdp_utils/model_loader.py +++ b/miles/backends/fsdp_utils/model_loader.py @@ -120,13 +120,14 @@ def lora_needs_no_base_weights(args: Namespace, lora_adapter_path: str | None) - """ if lora_adapter_path is None: return peft_init_lora_weights(args) in PEFT_INITS_WITHOUT_BASE_WEIGHTS - from peft import LoraConfig, PeftConfig + from peft import PeftConfig, PeftType from peft.utils import SAFETENSORS_WEIGHTS_NAME from safetensors import safe_open config = PeftConfig.from_pretrained(lora_adapter_path) file = Path(lora_adapter_path) / SAFETENSORS_WEIGHTS_NAME - if not isinstance(config, LoraConfig) or config.use_dora: + # AdaLoRA's config is a LoraConfig too, with tensors of its own: the type says which adapter this is. + if config.peft_type != PeftType.LORA or config.use_dora: return False if config.init_lora_weights not in PEFT_INITS_WITHOUT_BASE_WEIGHTS or not file.is_file(): return False diff --git a/tests/fast/backends/fsdp_utils/test_safetensors_load.py b/tests/fast/backends/fsdp_utils/test_safetensors_load.py index a9fc77c3f..a049c8aa3 100644 --- a/tests/fast/backends/fsdp_utils/test_safetensors_load.py +++ b/tests/fast/backends/fsdp_utils/test_safetensors_load.py @@ -20,7 +20,7 @@ import pytest import torch import torch.distributed as dist -from peft import LoHaConfig, LoraConfig, get_peft_model +from peft import AdaLoraConfig, LoHaConfig, LoraConfig, get_peft_model from safetensors.torch import save_file from tests.fast.backends.fsdp_utils.test_reference_models import ( TinyBackend, @@ -330,6 +330,9 @@ def save_adapter(path, config, *, init_lora_weights=None): pytest.param(LoraConfig(r=2, target_modules=["proj"]), "pissa", False, id="an init from the base weights"), pytest.param(LoraConfig(r=2, target_modules=["proj"], use_dora=True), None, False, id="DoRA"), pytest.param(LoHaConfig(r=2, target_modules=["proj"]), None, False, id="not a LoRA"), + pytest.param( + AdaLoraConfig(init_r=2, target_r=1, total_step=10, target_modules=["proj"]), None, False, id="AdaLoRA" + ), ], ) def test_a_saved_adapter_is_built_on_every_rank_only_when_it_holds_lora_tensors_alone( From baacad07f48b894fd5f5ae7bfc12b32364068b03 Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Tue, 17 Nov 2026 02:24:50 +0000 Subject: [PATCH 26/31] test(fsdp): an adapter saved as .bin is not built on every rank; a frozen model without an adapter reads per rank whatever the actor's LoRA flags --- .../backends/fsdp_utils/test_safetensors_load.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/tests/fast/backends/fsdp_utils/test_safetensors_load.py b/tests/fast/backends/fsdp_utils/test_safetensors_load.py index a049c8aa3..3a37d2c13 100644 --- a/tests/fast/backends/fsdp_utils/test_safetensors_load.py +++ b/tests/fast/backends/fsdp_utils/test_safetensors_load.py @@ -357,6 +357,22 @@ def load_component(self, component, **kwargs): load(monkeypatch, tmp_path, lora_init="gaussian", trainable=True, backend_cls=RealBaseBackend) +def test_a_saved_adapter_in_another_file_format_is_not_built_on_every_rank(tmp_path): + adapter_path = save_adapter(tmp_path, LoraConfig(r=2, target_modules=["proj"])) + (tmp_path / "adapter_model.safetensors").rename(tmp_path / "adapter_model.bin") + assert model_loader.lora_needs_no_base_weights(make_model_loader_args(), adapter_path) is False + + +def test_a_frozen_model_without_an_adapter_reads_per_rank_whatever_the_actor_s_lora_flags(tmp_path, monkeypatch): + # --use-lora and --lora-init-weights describe the trainable model's new adapter, not a frozen role's base. + save_checkpoint(tmp_path) + monkeypatch.setattr( + model_loader.checkpoint, "rank0_rng_state", lambda: pytest.fail("no adapter is built on any rank") + ) + _, materialize_requests, broadcasts = load(monkeypatch, tmp_path, lora_init="pissa", trainable=False) + assert materialize_requests == [False, False] and broadcasts == [] + + def lora_weights(state): return {name: tensor for name, tensor in state.items() if "lora_" in name} From 795d1e2f12b9cfa8111eda27beae991983495ace Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Tue, 17 Nov 2026 02:32:30 +0000 Subject: [PATCH 27/31] refactor(fsdp): rank 0 alone builds the adapter, on a stand-in for its base, and broadcasts it after the per-rank read of the base Every rank building the adapter needed rank 0's generator state on every rank, an agreement before the build, a rebuild on every rank in the fallback, and left two boundaries (an Embedding adapter's draws on meta, rank-local adapter files). The adapter is small: rank 0 builds it as on main, the other ranks stay on meta as on main, and after each rank has read its shards of the base, torch's set_model_state_dict broadcasts the adapter from rank 0. A model without an adapter loads exactly as in the PR below. --- miles/backends/fsdp_utils/checkpoint.py | 37 ++++--- miles/backends/fsdp_utils/model_loader.py | 89 +++++++---------- .../fsdp_utils/_safetensors_load_worker.py | 4 +- .../fsdp_utils/test_safetensors_load.py | 2 +- .../fsdp_utils/test_safetensors_load.py | 98 ++++++++----------- 5 files changed, 101 insertions(+), 129 deletions(-) diff --git a/miles/backends/fsdp_utils/checkpoint.py b/miles/backends/fsdp_utils/checkpoint.py index 1326f5c9d..be4c1039b 100644 --- a/miles/backends/fsdp_utils/checkpoint.py +++ b/miles/backends/fsdp_utils/checkpoint.py @@ -74,6 +74,11 @@ def base_state(model: torch.nn.Module) -> dict[str, torch.Tensor]: return {to_hf_name(name): tensor for name, tensor in model.state_dict().items() if not is_lora_param_name(name)} +def adapter_state(model: torch.nn.Module) -> dict[str, torch.Tensor]: + """The LoRA adapters' part of the state dict; empty for a model without one.""" + return {name: tensor for name, tensor in model.state_dict().items() if is_lora_param_name(name)} + + def safetensors_hold_state(model: torch.nn.Module, files: list[Path]) -> bool: """Whether the files hold the model's state dict without its LoRA adapters: the same names and shapes. @@ -97,37 +102,37 @@ def holds_on_every_rank(condition: bool) -> bool: return all(conditions) -def rank0_rng_state() -> torch.Tensor: - """The state of rank 0's default generator, on every rank.""" - states = [torch.get_rng_state() if dist.get_rank() == 0 else None] - dist.broadcast_object_list(states, src=0) - return states[0] - - @torch.no_grad() -def load_safetensors_to_fsdp(model: torch.nn.Module, files: list[Path], *, cpu_offload: bool) -> None: +def load_safetensors_to_fsdp( + model: torch.nn.Module, files: list[Path], rank0_adapter_state: dict[str, torch.Tensor], *, cpu_offload: bool +) -> None: """Materialize FSDP2 shards by reading each rank's own slice of every base parameter from the files. - A buffer outside the state dict is in no file: every rank ends with the value rank 0's constructor computed. + A LoRA adapter is in none of them: every rank takes its shards of the one rank 0 built + (``rank0_adapter_state``, empty on the other ranks). A buffer outside the state dict is in no file either: + every rank ends with the value rank 0's constructor computed. """ + from torch.distributed.checkpoint.state_dict import set_model_state_dict + device = torch.cuda.current_device() - # Buffers and LoRA adapters were computed for real on every rank; to_empty would wipe them. A buffer 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 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)) - adapters = {name: p.to_local().clone() for name, p in model.named_parameters() if is_lora_param_name(name)} 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]) - for name, parameter in model.named_parameters(): - if name in adapters: - parameter.to_local().copy_(adapters[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(base_state(model), storage_reader=dcp.HuggingFaceStorageReader(folder, thread_count=4)) + if adapter_state(model): + # Before the buffers move below: the broadcast wants every tensor of the model on one device. + options = StateDictOptions( + full_state_dict=True, broadcast_from_rank0=True, strict=False, cpu_offload=cpu_offload + ) + set_model_state_dict(model, rank0_adapter_state, options=options) if cpu_offload: # CPUOffloadPolicy manages params only; buffers must live on GPU for forward. for buffer in model.buffers(): diff --git a/miles/backends/fsdp_utils/model_loader.py b/miles/backends/fsdp_utils/model_loader.py index d5da15ff3..79be5c5e8 100644 --- a/miles/backends/fsdp_utils/model_loader.py +++ b/miles/backends/fsdp_utils/model_loader.py @@ -32,6 +32,7 @@ def load_fsdp_models( models = {} for component_index, component in enumerate(args.update_weight_target_modules): lora_adapter_path = None if lora_adapter_paths is None else lora_adapter_paths[component_index] + has_lora = lora_adapter_path is not None or (trainable and args.use_lora) build = partial( build_component, args, @@ -40,29 +41,25 @@ def load_fsdp_models( component, checkpoint_path=checkpoint_path, lora_adapter_path=lora_adapter_path, + has_lora=has_lora, trainable=trainable, ) - # Every rank reads its own shards from the safetensors files; else rank 0 loads and broadcasts. - has_lora = lora_adapter_path is not None or (trainable and args.use_lora) - read_per_rank = not has_lora or lora_needs_no_base_weights(args, lora_adapter_path) + # Every rank reads its own shards of the base from the safetensors files; else rank 0 loads and broadcasts. safetensors_files = None - if read_per_rank: + if not has_lora or lora_needs_no_base_weights(args, lora_adapter_path): safetensors_files = model_backend.safetensors_files(component, checkpoint_path=checkpoint_path) - # Each rank reads its own adapter config and files, and the collectives below depend on the answer. - if not checkpoint.holds_on_every_rank(safetensors_files is not None): - safetensors_files = None materialize_weights = safetensors_files is None and dist.get_rank() == 0 rng_state = torch.get_rng_state() - lora_on_every_rank = has_lora and safetensors_files is not None - model = build(materialize_weights=materialize_weights, lora_on_every_rank=lora_on_every_rank) - if safetensors_files is not None and not checkpoint.holds_on_every_rank( - checkpoint.safetensors_hold_state(model, safetensors_files) + model = build(materialize_weights=materialize_weights) + # Every rank answers, with files or without: each one read its own adapter config to get here. + if not checkpoint.holds_on_every_rank( + safetensors_files is not None and checkpoint.safetensors_hold_state(model, safetensors_files) ): - if has_lora or dist.get_rank() == 0: + if safetensors_files is not None and dist.get_rank() == 0: # A constructor may draw random numbers: the second build draws what the first one did. torch.set_rng_state(rng_state) - materialize_weights = dist.get_rank() == 0 - model = build(materialize_weights=materialize_weights, lora_on_every_rank=False) + materialize_weights = True + model = build(materialize_weights=True) safetensors_files = None if dist.get_rank() == 0: source = "rank 0 loads and broadcasts" @@ -73,6 +70,8 @@ def load_fsdp_models( logger.info(f"FSDP: {component} weights of {checkpoint_path}: {source}") checkpoint.sync_model_dtypes(model) full_state = model.state_dict() if materialize_weights else {} + # With the base read from the files, the adapter rank 0 built is what is left to broadcast. + adapter_state = checkpoint.adapter_state(model) if dist.get_rank() == 0 else {} model = apply_fsdp2( model, model_backend.fsdp_parallel_plan(model), @@ -81,10 +80,10 @@ def load_fsdp_models( args=args, ) if safetensors_files is not None: - checkpoint.load_safetensors_to_fsdp(model, safetensors_files, cpu_offload=cpu_offload) + checkpoint.load_safetensors_to_fsdp(model, safetensors_files, adapter_state, cpu_offload=cpu_offload) else: checkpoint.broadcast_full_state_to_fsdp(model, full_state, cpu_offload=cpu_offload) - del full_state + del full_state, adapter_state train_pipeline_config.postprocess_model_after_materialize(model) if parallel_state.get_optional_mesh("sp") is not None: apply_sequence_parallel( @@ -111,7 +110,7 @@ def peft_init_lora_weights(args: Namespace) -> bool | str: def lora_needs_no_base_weights(args: Namespace, lora_adapter_path: str | None) -> bool: - """Whether every rank can build the adapter on a base that has no weights. + """Whether rank 0 can build the adapter on a base that has no weights, the base being read from the files. PEFT must not read the base weights' values while it builds the adapter: PiSSA, OLoRA, LoftQ... decompose them, and DoRA takes their norm. A saved adapter must also be a LoRA whose file holds adapter tensors only: @@ -143,14 +142,10 @@ def build_component( *, checkpoint_path: str, lora_adapter_path: str | None, + has_lora: bool, trainable: bool, materialize_weights: bool, - lora_on_every_rank: bool, ) -> torch.nn.Module: - """``lora_on_every_rank``: every rank builds the adapter's values as rank 0 does, on a base without weights. - - It is for a model that has an adapter, and for all ranks at once: the build then runs a collective. - """ with model_init_context(materialize_weights=materialize_weights): model = model_backend.load_component( component, @@ -158,56 +153,45 @@ def build_component( master_dtype=parse_dtype_from_str(args.fsdp_master_dtype), materialize_weights=materialize_weights, ) - # Before the adapter step, which leaves every base parameter on meta whatever the backend built. + # Before the adapter step, which leaves rank 0's base on meta whatever the backend built. 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 args.fsdp_attention_backend is not None: model_backend.set_attention_backend(model, args.fsdp_attention_backend) if trainable and args.gradient_checkpointing: model_backend.enable_gradient_checkpointing(model) - materialize_lora = lora_on_every_rank or dist.get_rank() == 0 - with base_storage_for_lora(model, enabled=lora_on_every_rank): - if lora_adapter_path is not None: - model = load_lora_adapter(model, lora_adapter_path, trainable=trainable, materialize=materialize_lora) - elif trainable and args.use_lora: - model = apply_lora(model, args, train_pipeline_config, materialize=materialize_lora) + if has_lora: + # Rank 0 builds the adapter's values, as before, also when its base has no weights. + with base_stand_in_for_lora(model, enabled=dist.get_rank() == 0 and not materialize_weights): + if lora_adapter_path is not None: + model = load_lora_adapter(model, lora_adapter_path, trainable=trainable) + else: + model = apply_lora(model, args, train_pipeline_config) model.train(trainable) if not trainable: model.requires_grad_(False) - if not materialize_lora and any( - not parameter.is_meta for name, parameter in model.named_parameters() if checkpoint.is_lora_param_name(name) - ): + if dist.get_rank() != 0 and any(not parameter.is_meta for parameter in model.parameters()): raise RuntimeError(f"the adapter of {component} did not honor meta initialization") return model @contextmanager -def base_storage_for_lora(model: torch.nn.Module, *, enabled: bool): - """Give a meta base a CPU stand-in while PEFT builds an adapter on it, from rank 0's generator state. +def base_stand_in_for_lora(model: torch.nn.Module, *, enabled: bool): + """Give a meta base a CPU stand-in while PEFT builds an adapter on it. PEFT moves a new adapter to its base layer's device, and meta would drop the adapter's values. For the adapters ``lora_needs_no_base_weights`` lets through it reads the base layer's device and dtype only, so each base parameter stands in as one uninitialized element expanded to its shape: a full ``torch.empty`` is written - through under ``--deterministic-mode`` (the NaN fill), a copy of the model on every rank. - - PEFT's initialization draws, and only rank 0 has run it so far: the other ranks draw the same values from - rank 0's generator state and keep their own. An adapter on an ``nn.Embedding`` is the one case where they do - not end as before: PEFT draws for it even on meta, in the build these ranks no longer run. - - Each rank builds from its own copy of the adapter's files, as it reads its own copy of the base's. + through under ``--deterministic-mode`` (the NaN fill), a copy of the model in host memory. """ if not enabled: yield return - rng_state = torch.get_rng_state() - torch.set_rng_state(checkpoint.rank0_rng_state()) replace_base_parameters(model, lambda parameter: torch.empty((), dtype=parameter.dtype).expand(parameter.shape)) try: yield finally: replace_base_parameters(model, lambda parameter: parameter.data.to("meta")) - if dist.get_rank() != 0: - torch.set_rng_state(rng_state) def replace_base_parameters(model: torch.nn.Module, data_of) -> None: @@ -245,22 +229,21 @@ def model_init_context(*, materialize_weights: bool): yield -def load_lora_adapter(model, adapter_path: str, *, trainable: bool, materialize: bool): +def load_lora_adapter(model, adapter_path: str, *, trainable: bool): from peft import PeftConfig, PeftModel, get_peft_model - if materialize: + if dist.get_rank() == 0: return PeftModel.from_pretrained(model, adapter_path, is_trainable=trainable, autocast_adapter_dtype=False) config = PeftConfig.from_pretrained(adapter_path) config.inference_mode = not trainable return get_peft_model(model, config, low_cpu_mem_usage=True, autocast_adapter_dtype=False) -def apply_lora( - model: torch.nn.Module, args: Namespace, train_pipeline_config, *, materialize: bool -) -> torch.nn.Module: - """Apply PEFT LoRA; without ``materialize`` the adapters stay uninitialized on meta.""" +def apply_lora(model: torch.nn.Module, args: Namespace, train_pipeline_config) -> torch.nn.Module: + """Apply PEFT LoRA, leaving non-rank0 adapters uninitialized on meta.""" from peft import LoraConfig, get_peft_model + on_meta = dist.get_rank() != 0 # Per-model fallback when --lora-target-modules is unset (runtime inference: depends on loaded pipeline). targets = args.lora_target_modules or train_pipeline_config.lora_target_modules model = get_peft_model( @@ -269,9 +252,9 @@ def apply_lora( r=args.lora_rank, lora_alpha=args.lora_alpha, target_modules=targets, - init_lora_weights=peft_init_lora_weights(args) if materialize else False, + init_lora_weights=False if on_meta else peft_init_lora_weights(args), ), - low_cpu_mem_usage=not materialize, + low_cpu_mem_usage=on_meta, ) if dist.get_rank() == 0: model.print_trainable_parameters() diff --git a/tests/fast-gpu/backends/fsdp_utils/_safetensors_load_worker.py b/tests/fast-gpu/backends/fsdp_utils/_safetensors_load_worker.py index 507122d09..8c1fc4a2f 100644 --- a/tests/fast-gpu/backends/fsdp_utils/_safetensors_load_worker.py +++ b/tests/fast-gpu/backends/fsdp_utils/_safetensors_load_worker.py @@ -4,7 +4,7 @@ a buffer no file holds --> rank 0's value on both ranks another name in the files --> rank 0 builds again with weights --> the broadcast value on both ranks another name on rank 1 only --> the same: the ranks agree before either reads - LoRA, saved or new --> the adapter shards and the generator the broadcast leaves, on both ranks + LoRA, saved or new --> rank 0's adapter on both ranks: the shards and the generator the broadcast leaves """ import os @@ -93,7 +93,7 @@ def check_lora(mesh, root, rank, cpu_offload, **kwargs): # rank 0 builds with weights, then the real broadcast torch.manual_seed(0) models, materialize_requests = load(mesh, root / "renamed", cpu_offload, **kwargs) - assert materialize_requests == ([False, True, False, True] if rank == 0 else [False, False, False, False]) + assert materialize_requests == ([False, True, False, True] if rank == 0 else [False, False]) broadcast = adapter_shards(models) assert adapters.keys() == broadcast.keys() and all(torch.equal(adapters[key], broadcast[key]) for key in adapters) assert torch.equal(torch.get_rng_state(), generator) diff --git a/tests/fast-gpu/backends/fsdp_utils/test_safetensors_load.py b/tests/fast-gpu/backends/fsdp_utils/test_safetensors_load.py index a91ad479f..d7cd535de 100644 --- a/tests/fast-gpu/backends/fsdp_utils/test_safetensors_load.py +++ b/tests/fast-gpu/backends/fsdp_utils/test_safetensors_load.py @@ -2,7 +2,7 @@ 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 --> the value rank 0 loaded, on both ranks - LoRA, saved or new --> the adapter shards and the generator the broadcast leaves, on both ranks + LoRA, saved or new --> rank 0's adapter on both ranks: the shards and the generator the broadcast leaves """ from tests.ci.ci_register import register_cuda_ci diff --git a/tests/fast/backends/fsdp_utils/test_safetensors_load.py b/tests/fast/backends/fsdp_utils/test_safetensors_load.py index 3a37d2c13..2b78581bf 100644 --- a/tests/fast/backends/fsdp_utils/test_safetensors_load.py +++ b/tests/fast/backends/fsdp_utils/test_safetensors_load.py @@ -3,8 +3,8 @@ the index's files, or the single file, hold the state dict's names and shapes --> every rank on meta --> dcp.load a variant file beside them --> not read listed file missing / other name / other shape / a rank that disagrees --> rank 0 loads and broadcasts - LoRA, saved or new --> every rank builds the adapter as rank 0 does, on a base without weights, and reads the base - LoRA whose initialization decomposes the base weights (PiSSA) --> rank 0 loads and broadcasts + LoRA, saved or new --> rank 0 builds the adapter on a base without weights and broadcasts it; the base is read + LoRA that reads the base weights (PiSSA, DoRA) or saves more than adapter tensors --> rank 0 loads and broadcasts FSDP2 is real on a one-rank CPU mesh and the broadcast is recorded; the CUDA worker splits the shards over two ranks. """ @@ -257,53 +257,58 @@ def test_a_buffer_two_modules_share_keeps_its_value_on_both(tmp_path, monkeypatc assert torch.equal(model.table, torch.arange(3.0)) and torch.equal(model.block.table, torch.arange(3.0)) -def test_one_rank_that_cannot_see_the_files_sends_every_rank_to_the_broadcast(tmp_path, monkeypatch): +def test_one_rank_that_cannot_read_the_files_sends_every_rank_to_the_broadcast(tmp_path, monkeypatch): save_checkpoint(tmp_path) conditions = [] _, materialize_requests, broadcasts = load( monkeypatch, tmp_path, holds=lambda condition: conditions.append(condition) or False ) - assert conditions == [True, True] and materialize_requests == [True, True] and len(broadcasts) == 2 - - -def holds_for_the_files_only(): - """Every rank sees the files; then one of them finds another state dict in its copy.""" - answers = [] - return lambda condition: answers.append(condition) or len(answers) % 2 == 1 - - -def test_one_rank_whose_files_hold_another_state_sends_every_rank_to_the_broadcast(tmp_path, monkeypatch): - save_checkpoint(tmp_path) - _, materialize_requests, broadcasts = load(monkeypatch, tmp_path, holds=holds_for_the_files_only()) - assert materialize_requests == [False, True, False, True] and len(broadcasts) == 2 + assert conditions == [True, True] and materialize_requests == [False, True, False, True] and len(broadcasts) == 2 def test_a_model_without_an_adapter_skips_the_adapter_step(tmp_path, monkeypatch): - # The step gives every base parameter storage and runs a collective: neither is for a model with no adapter. save_checkpoint(tmp_path) monkeypatch.setattr( - model_loader.checkpoint, "rank0_rng_state", lambda: pytest.fail("no adapter is built on any rank") + model_loader, "replace_base_parameters", lambda model, data_of: pytest.fail("no base gets a stand-in") ) + _, materialize_requests, broadcasts = load(monkeypatch, tmp_path) + assert materialize_requests == [False, False] and broadcasts == [] + + +def test_a_frozen_model_without_an_adapter_reads_per_rank_whatever_the_actor_s_lora_flags(tmp_path, monkeypatch): + # --use-lora and --lora-init-weights describe the trainable model's new adapter, not a frozen role's base. + save_checkpoint(tmp_path) monkeypatch.setattr( - model_loader, "replace_base_parameters", lambda model, data_of: pytest.fail("no parameter gets storage") + model_loader, "replace_base_parameters", lambda model, data_of: pytest.fail("no base gets a stand-in") ) - _, materialize_requests, broadcasts = load(monkeypatch, tmp_path) + _, materialize_requests, broadcasts = load(monkeypatch, tmp_path, lora_init="pissa", trainable=False) assert materialize_requests == [False, False] and broadcasts == [] -def test_the_base_takes_no_memory_while_the_adapter_is_built(monkeypatch): - # A full torch.empty is written through under --deterministic-mode: a copy of the model on every rank. - monkeypatch.setattr(model_loader.checkpoint, "rank0_rng_state", torch.get_rng_state) - monkeypatch.setattr(model_loader.dist, "get_rank", lambda: 0) +def test_the_base_takes_no_memory_while_the_adapter_is_built(): + # A full torch.empty is written through under --deterministic-mode: a copy of the model in host memory. with model_loader.model_init_context(materialize_weights=False): model = TinyComponent() - with model_loader.base_storage_for_lora(model, enabled=True): + with model_loader.base_stand_in_for_lora(model, enabled=True): weight = model.block.proj.weight assert weight.device.type == "cpu" and weight.shape == (4, 3) assert weight.untyped_storage().nbytes() == weight.element_size() assert model.block.proj.weight.is_meta +def test_a_base_built_with_weights_is_refused_before_the_adapter_step_would_hide_it(tmp_path, monkeypatch): + class RealBaseBackend(FileBackend): + def load_component(self, component, **kwargs): + model = super().load_component(component, **kwargs) + # Past the ambient init_empty_weights, which would put a parameter registered here on meta. + model.block.proj._parameters["weight"] = torch.nn.Parameter(torch.zeros(4, 3)) + return model + + save_checkpoint(tmp_path) + with pytest.raises(RuntimeError, match="did not honor meta initialization"): + load(monkeypatch, tmp_path, lora_init="gaussian", trainable=True, backend_cls=RealBaseBackend) + + class BiasedBlock(torch.nn.Module): def __init__(self): super().__init__() @@ -322,7 +327,7 @@ def save_adapter(path, config, *, init_lora_weights=None): @pytest.mark.parametrize( - "config, init_lora_weights, builds_on_every_rank", + "config, init_lora_weights, built_without_base_weights", [ pytest.param(LoraConfig(r=2, target_modules=["proj"]), None, True, id="adapter tensors only"), pytest.param(LoraConfig(r=2, target_modules=["proj"], bias="all"), None, False, id="a bias of the base"), @@ -335,49 +340,28 @@ def save_adapter(path, config, *, init_lora_weights=None): ), ], ) -def test_a_saved_adapter_is_built_on_every_rank_only_when_it_holds_lora_tensors_alone( - tmp_path, config, init_lora_weights, builds_on_every_rank +def test_a_saved_adapter_is_built_without_base_weights_only_when_it_holds_lora_tensors_alone( + tmp_path, config, init_lora_weights, built_without_base_weights ): # PEFT loads a bias or a saved module into the base, and the read of the base checkpoint would replace it; - # DoRA's magnitude is the norm of the base weights, which no rank holds while it builds the adapter. + # DoRA's magnitude is the norm of the base weights, which rank 0 does not hold while it builds the adapter. adapter_path = save_adapter(tmp_path, config, init_lora_weights=init_lora_weights) - assert model_loader.lora_needs_no_base_weights(make_model_loader_args(), adapter_path) is builds_on_every_rank - - -def test_a_base_built_with_weights_is_refused_before_the_adapter_step_would_hide_it(tmp_path, monkeypatch): - class RealBaseBackend(FileBackend): - def load_component(self, component, **kwargs): - model = super().load_component(component, **kwargs) - # Past the ambient init_empty_weights, which would put a parameter registered here on meta. - model.block.proj._parameters["weight"] = torch.nn.Parameter(torch.zeros(4, 3)) - return model - - save_checkpoint(tmp_path) - with pytest.raises(RuntimeError, match="did not honor meta initialization"): - load(monkeypatch, tmp_path, lora_init="gaussian", trainable=True, backend_cls=RealBaseBackend) + assert ( + model_loader.lora_needs_no_base_weights(make_model_loader_args(), adapter_path) is built_without_base_weights + ) -def test_a_saved_adapter_in_another_file_format_is_not_built_on_every_rank(tmp_path): +def test_a_saved_adapter_in_another_file_format_is_not_built_without_base_weights(tmp_path): adapter_path = save_adapter(tmp_path, LoraConfig(r=2, target_modules=["proj"])) (tmp_path / "adapter_model.safetensors").rename(tmp_path / "adapter_model.bin") assert model_loader.lora_needs_no_base_weights(make_model_loader_args(), adapter_path) is False -def test_a_frozen_model_without_an_adapter_reads_per_rank_whatever_the_actor_s_lora_flags(tmp_path, monkeypatch): - # --use-lora and --lora-init-weights describe the trainable model's new adapter, not a frozen role's base. - save_checkpoint(tmp_path) - monkeypatch.setattr( - model_loader.checkpoint, "rank0_rng_state", lambda: pytest.fail("no adapter is built on any rank") - ) - _, materialize_requests, broadcasts = load(monkeypatch, tmp_path, lora_init="pissa", trainable=False) - assert materialize_requests == [False, False] and broadcasts == [] - - def lora_weights(state): return {name: tensor for name, tensor in state.items() if "lora_" in name} -def test_saved_adapters_are_built_on_every_rank_and_the_base_is_read_from_the_files(tmp_path, monkeypatch): +def test_saved_adapters_are_built_by_rank_0_alone_and_the_base_is_read_from_the_files(tmp_path, monkeypatch): save_checkpoint(tmp_path) adapter_paths = save_component_lora_adapters(tmp_path / "adapters") models, materialize_requests, broadcasts = load(monkeypatch, tmp_path, lora_adapter_paths=adapter_paths) @@ -403,7 +387,7 @@ def test_a_new_adapter_gets_the_values_and_leaves_the_generator_as_rank_0_does_w torch.manual_seed(0) _, materialize_requests, with_weights = load( - monkeypatch, tmp_path, lora_init=lora_init, trainable=True, holds=holds_for_the_files_only() + monkeypatch, tmp_path, lora_init=lora_init, trainable=True, holds=lambda condition: False ) assert materialize_requests == [False, True, False, True] and torch.equal(torch.get_rng_state(), generator) for (component, model), state in zip(models.items(), with_weights, strict=True): @@ -430,7 +414,7 @@ def safetensors_files(self, component, *, checkpoint_path): holds=lambda condition: conditions.append(condition) or condition, backend_cls=NeverAsked, ) - # Every rank still says that it reads no files, so no rank waits in a collective the others skip. + # Every rank still answers that it reads no files, so no rank waits in a collective the others skip. assert conditions == [False, False] and materialize_requests == [True, True] and len(broadcasts) == 2 assert all(len(lora_weights(state)) == 2 for state in broadcasts) From c687ff0d0a08e190066b7820514b0ef2a20309ea Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Tue, 17 Nov 2026 02:49:17 +0000 Subject: [PATCH 28/31] test(fsdp): a checkpoint in two files, a frozen model in a run that trains a LoRA, and a buffer no load casts: three changes of the loader that passed every test now fail one --- .../backends/fsdp_utils/test_model_backend.py | 11 ++++++++ .../fsdp_utils/test_safetensors_load.py | 25 ++++++++++++++----- 2 files changed, 30 insertions(+), 6 deletions(-) diff --git a/tests/fast/backends/fsdp_utils/test_model_backend.py b/tests/fast/backends/fsdp_utils/test_model_backend.py index eb75a44b0..00f76eecc 100644 --- a/tests/fast/backends/fsdp_utils/test_model_backend.py +++ b/tests/fast/backends/fsdp_utils/test_model_backend.py @@ -76,6 +76,16 @@ def __init__(self): 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( @@ -116,6 +126,7 @@ def _tiny_wan(): 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]) diff --git a/tests/fast/backends/fsdp_utils/test_safetensors_load.py b/tests/fast/backends/fsdp_utils/test_safetensors_load.py index 0048db6f6..18f56c917 100644 --- a/tests/fast/backends/fsdp_utils/test_safetensors_load.py +++ b/tests/fast/backends/fsdp_utils/test_safetensors_load.py @@ -70,7 +70,7 @@ def save_checkpoint(path, *, name="block.proj.weight", shape=(4, 3), sharded=Tru ) -def load(monkeypatch, path, *, holds=lambda condition: condition, backend_cls=None, **kwargs): +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) @@ -83,7 +83,7 @@ def load(monkeypatch, path, *, holds=lambda condition: condition, backend_cls=No 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 = False + args.use_lora = use_lora models = model_loader.load_fsdp_models( args, backend, TinyPipelineConfig(), parallel, checkpoint_path=str(path), **kwargs ) @@ -213,11 +213,17 @@ def load_component(self, component, *, checkpoint_path, master_dtype, materializ 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: - file = path / component / "diffusion_pytorch_model.safetensors" - folder_state = {"block.proj.weight": saved_weight(component), "row_sums": saved_weight(component).sum(dim=1)} - file.parent.mkdir(parents=True) - save_file(folder_state, file) + 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): @@ -258,6 +264,13 @@ def test_one_rank_that_cannot_read_the_files_sends_every_rank_to_the_broadcast(t assert conditions == [True, True] and materialize_requests == [False, True, False, True] and len(broadcasts) == 2 +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) From d833ec34af45afe9cf3cd03a2058bffe6a5b7594 Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Tue, 17 Nov 2026 02:49:17 +0000 Subject: [PATCH 29/31] docs(fsdp): a backend that names files gives every tensor its final dtype when it builds without weights --- docs/user-guide/customization.md | 4 +++- miles/backends/fsdp_utils/model_backend.py | 2 ++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/docs/user-guide/customization.md b/docs/user-guide/customization.md index ee6d1d867..f481afe63 100644 --- a/docs/user-guide/customization.md +++ b/docs/user-guide/customization.md @@ -383,7 +383,9 @@ 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 that overrides `load_component` loads on rank 0 and broadcasts, as before, -unless it also overrides `safetensors_files` to name the files that hold what it loads. +unless it also overrides `safetensors_files` to name the files that hold what it loads. It must then give 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. *** diff --git a/miles/backends/fsdp_utils/model_backend.py b/miles/backends/fsdp_utils/model_backend.py index 1e300fa58..e48ba0f26 100644 --- a/miles/backends/fsdp_utils/model_backend.py +++ b/miles/backends/fsdp_utils/model_backend.py @@ -93,6 +93,8 @@ def safetensors_files(self, component: str, *, checkpoint_path: str) -> list[Pat """Local safetensors files every rank can read its shards of the component from; None: rank 0 loads it. They hold what ``load_component`` loads: a backend that loads other weights names its own files or none. + A backend that names files gives every tensor its final dtype when it builds without weights: the file + values are cast into those dtypes, and no rank loads a model the others could copy them from. """ return None From b8337f879c1e9b4a669cd0cbf02ba54ae1d7e803 Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Tue, 17 Nov 2026 03:10:03 +0000 Subject: [PATCH 30/31] fix(fsdp): the ranks agree on the adapter's tensor names and shapes before rank 0 broadcasts them; a rank whose own adapter config gave other tensors takes the full broadcast, which names the missing keys as before --- miles/backends/fsdp_utils/checkpoint.py | 16 ++++-- miles/backends/fsdp_utils/model_loader.py | 6 ++- .../fsdp_utils/test_reference_models.py | 2 +- .../fsdp_utils/test_safetensors_load.py | 52 +++++++++++++++++-- 4 files changed, 64 insertions(+), 12 deletions(-) diff --git a/miles/backends/fsdp_utils/checkpoint.py b/miles/backends/fsdp_utils/checkpoint.py index be4c1039b..bbad7b6c0 100644 --- a/miles/backends/fsdp_utils/checkpoint.py +++ b/miles/backends/fsdp_utils/checkpoint.py @@ -79,6 +79,10 @@ def adapter_state(model: torch.nn.Module) -> dict[str, torch.Tensor]: return {name: tensor for name, tensor in model.state_dict().items() if is_lora_param_name(name)} +def adapter_shapes(model: torch.nn.Module) -> dict[str, tuple[int, ...]]: + return {name: tuple(tensor.shape) for name, tensor in adapter_state(model).items()} + + def safetensors_hold_state(model: torch.nn.Module, files: list[Path]) -> bool: """Whether the files hold the model's state dict without its LoRA adapters: the same names and shapes. @@ -96,10 +100,11 @@ def safetensors_hold_state(model: torch.nn.Module, files: list[Path]) -> bool: return saved == {name: tuple(tensor.shape) for name, tensor in base_state(model).items()} -def holds_on_every_rank(condition: bool) -> bool: - conditions = [None] * dist.get_world_size() - dist.all_gather_object(conditions, condition) - return all(conditions) +def holds_on_every_rank(condition: bool, *, same: object = None) -> bool: + """Whether ``condition`` holds on every rank and every rank passes an equal ``same``.""" + answers = [None] * dist.get_world_size() + dist.all_gather_object(answers, (condition, same)) + return all(answer == (True, same) for answer in answers) @torch.no_grad() @@ -128,7 +133,8 @@ def load_safetensors_to_fsdp( os.symlink(file.resolve(), Path(folder) / file.name) dcp.load(base_state(model), storage_reader=dcp.HuggingFaceStorageReader(folder, thread_count=4)) if adapter_state(model): - # Before the buffers move below: the broadcast wants every tensor of the model on one device. + # Before the buffers move below: the broadcast wants every tensor of the model on one device. It fills the + # names rank 0 sends and reports nothing about the others: the ranks agreed on the adapter's names before. options = StateDictOptions( full_state_dict=True, broadcast_from_rank0=True, strict=False, cpu_offload=cpu_offload ) diff --git a/miles/backends/fsdp_utils/model_loader.py b/miles/backends/fsdp_utils/model_loader.py index 79be5c5e8..e5be8b2fe 100644 --- a/miles/backends/fsdp_utils/model_loader.py +++ b/miles/backends/fsdp_utils/model_loader.py @@ -51,9 +51,11 @@ def load_fsdp_models( materialize_weights = safetensors_files is None and dist.get_rank() == 0 rng_state = torch.get_rng_state() model = build(materialize_weights=materialize_weights) - # Every rank answers, with files or without: each one read its own adapter config to get here. + # Every rank answers, with files or without: each one read its own adapter config to get here, and built + # from it the adapter tensors that rank 0's broadcast has to fill one for one. if not checkpoint.holds_on_every_rank( - safetensors_files is not None and checkpoint.safetensors_hold_state(model, safetensors_files) + safetensors_files is not None and checkpoint.safetensors_hold_state(model, safetensors_files), + same=checkpoint.adapter_shapes(model), ): if safetensors_files is not None and dist.get_rank() == 0: # A constructor may draw random numbers: the second build draws what the first one did. diff --git a/tests/fast/backends/fsdp_utils/test_reference_models.py b/tests/fast/backends/fsdp_utils/test_reference_models.py index 9181e5018..fd1dd34ea 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, same=None: 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 index d6a6814ec..8c2235a9b 100644 --- a/tests/fast/backends/fsdp_utils/test_safetensors_load.py +++ b/tests/fast/backends/fsdp_utils/test_safetensors_load.py @@ -77,7 +77,9 @@ def save_checkpoint(path, *, name="block.proj.weight", shape=(4, 3), sharded=Tru ) -def load(monkeypatch, path, *, holds=lambda condition: condition, lora_init=None, backend_cls=None, **kwargs): +def load( + monkeypatch, path, *, holds=lambda condition, same=None: condition, lora_init=None, backend_cls=None, **kwargs +): broadcasts = [] monkeypatch.setattr(model_loader.checkpoint, "holds_on_every_rank", holds) monkeypatch.setattr(model_loader.checkpoint, "sync_model_dtypes", lambda model: None) @@ -267,7 +269,7 @@ def test_one_rank_that_cannot_read_the_files_sends_every_rank_to_the_broadcast(t save_checkpoint(tmp_path) conditions = [] _, materialize_requests, broadcasts = load( - monkeypatch, tmp_path, holds=lambda condition: conditions.append(condition) or False + monkeypatch, tmp_path, holds=lambda condition, same=None: conditions.append(condition) or False ) assert conditions == [True, True] and materialize_requests == [False, True, False, True] and len(broadcasts) == 2 @@ -363,6 +365,48 @@ def test_a_saved_adapter_in_another_file_format_is_not_built_without_base_weight assert model_loader.lora_needs_no_base_weights(make_model_loader_args(), adapter_path) is False +def test_the_ranks_agree_on_the_adapter_s_tensors_before_rank_0_broadcasts_them(tmp_path, monkeypatch): + # The broadcast fills the names rank 0 sends; a rank whose own adapter config gave other tensors would keep + # them uninitialized. Such ranks go to the full broadcast instead, which names the missing keys. + save_checkpoint(tmp_path) + adapter_paths = save_component_lora_adapters(tmp_path / "adapters") + compared = [] + load( + monkeypatch, + tmp_path, + lora_adapter_paths=adapter_paths, + holds=lambda condition, same=None: compared.append(same) or condition, + ) + assert compared == [ADAPTER_SHAPES, ADAPTER_SHAPES] + + +ADAPTER_SHAPES = { + "base_model.model.block.proj.lora_A.default.weight": (2, 3), + "base_model.model.block.proj.lora_B.default.weight": (4, 2), +} + + +@pytest.mark.parametrize( + "condition, other_rank, holds", + [ + pytest.param(True, (True, ADAPTER_SHAPES), True, id="the same on both ranks"), + pytest.param(True, (False, ADAPTER_SHAPES), False, id="the other rank's condition fails"), + pytest.param(False, (False, ADAPTER_SHAPES), False, id="no rank's condition holds"), + pytest.param( + True, (True, {"base_model.model.other.lora_A.default.weight": (2, 3)}), False, id="other tensors" + ), + pytest.param(True, (True, ADAPTER_SHAPES | {"extra.lora_A.default.weight": (2, 3)}), False, id="one more"), + ], +) +def test_a_condition_holds_on_every_rank_only_with_the_same_value_beside_it(monkeypatch, condition, other_rank, holds): + def answers_of_two_ranks(answers, answer): + answers[:] = [answer, other_rank] + + monkeypatch.setattr(dist, "get_world_size", lambda: 2) + monkeypatch.setattr(dist, "all_gather_object", answers_of_two_ranks) + assert model_loader.checkpoint.holds_on_every_rank(condition, same=ADAPTER_SHAPES) is holds + + def lora_weights(state): return {name: tensor for name, tensor in state.items() if "lora_" in name} @@ -393,7 +437,7 @@ def test_a_new_adapter_gets_the_values_and_leaves_the_generator_as_rank_0_does_w torch.manual_seed(0) _, materialize_requests, with_weights = load( - monkeypatch, tmp_path, lora_init=lora_init, trainable=True, holds=lambda condition: False + monkeypatch, tmp_path, lora_init=lora_init, trainable=True, holds=lambda condition, same=None: False ) assert materialize_requests == [False, True, False, True] and torch.equal(torch.get_rng_state(), generator) for (component, model), state in zip(models.items(), with_weights, strict=True): @@ -417,7 +461,7 @@ def safetensors_files(self, component, *, checkpoint_path): tmp_path, lora_init="pissa", trainable=True, - holds=lambda condition: conditions.append(condition) or condition, + holds=lambda condition, same=None: conditions.append(condition) or condition, backend_cls=NeverAsked, ) # Every rank still answers that it reads no files, so no rank waits in a collective the others skip. From 48f0ab83ab80afff4fca2a276f9ec204a261cb7c Mon Sep 17 00:00:00 2001 From: Andy Ye <89891424+zhihengy@users.noreply.github.com> Date: Tue, 17 Nov 2026 03:10:38 +0000 Subject: [PATCH 31/31] test(fsdp): the two-rank LoRA case loads a model with a persistent buffer, which the adapter broadcast needs on the parameters' device under CPU offload --- .../fsdp_utils/_safetensors_load_worker.py | 25 ++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/tests/fast-gpu/backends/fsdp_utils/_safetensors_load_worker.py b/tests/fast-gpu/backends/fsdp_utils/_safetensors_load_worker.py index 8c1fc4a2f..09197eca4 100644 --- a/tests/fast-gpu/backends/fsdp_utils/_safetensors_load_worker.py +++ b/tests/fast-gpu/backends/fsdp_utils/_safetensors_load_worker.py @@ -21,8 +21,11 @@ ) from tests.fast.backends.fsdp_utils.test_safetensors_load import ( BROADCAST_VALUE, + DerivedBufferComponent, FileBackend, + backend_of, save_checkpoint, + save_row_sums, saved_weight, ) from torch.distributed.device_mesh import init_device_mesh @@ -39,9 +42,9 @@ def load_component(self, component, **kwargs): return model -def load(mesh, path, cpu_offload, *, lora_init=None, **kwargs): +def load(mesh, path, cpu_offload, *, lora_init=None, backend_cls=RankTaggedBackend, **kwargs): parallel = SimpleNamespace(get_mesh=lambda name: mesh, get_optional_mesh=lambda name: None) - args, backend = make_model_loader_args(), RankTaggedBackend() + args, backend = make_model_loader_args(), backend_cls() args.use_lora = lora_init is not None args.lora_rank, args.lora_alpha, args.lora_target_modules, args.lora_init_weights = 2, 4, ["proj"], lora_init models = load_fsdp_models( @@ -54,7 +57,8 @@ def load(mesh, path, cpu_offload, *, lora_init=None, **kwargs): assert shard.shape == (2, 3) and shard.dtype == torch.float32 assert shard.device.type == ("cpu" if cpu_offload else "cuda") assert base.forward_count.device.type == "cuda" and base.forward_count.item() == 0 - assert base.built_on_rank.device.type == "cuda" and base.built_on_rank.item() == 0 + if backend_cls is RankTaggedBackend: + assert base.built_on_rank.device.type == "cuda" and base.built_on_rank.item() == 0 return models, backend.materialize_requests @@ -108,6 +112,7 @@ def main(): save_checkpoint(root / "state") save_checkpoint(root / "renamed", name="block.proj.kernel") save_component_lora_adapters(root / "adapters") + save_row_sums(root / "row_sums") dist.barrier() inputs = torch.ones(2, 3, device="cuda") for cpu_offload in (False, True): @@ -133,6 +138,20 @@ def main(): adapter_paths = [str(root / "adapters" / component) for component in ("transformer", "transformer_2")] check_lora(mesh, root, rank, cpu_offload, lora_adapter_paths=adapter_paths) check_lora(mesh, root, rank, cpu_offload, lora_init="gaussian", trainable=True) + + # A buffer of the state dict with a dimension: the adapter broadcast wants it on the parameters' device, + # so under CPU offload it runs before the buffers move to the GPU. + models, _ = load( + mesh, + root / "row_sums", + cpu_offload, + backend_cls=backend_of(DerivedBufferComponent), + lora_adapter_paths=adapter_paths, + ) + for component, model in models.items(): + row_sums = model.base_model.model.row_sums + assert row_sums.device.type == "cuda" + assert torch.equal(row_sums.cpu(), saved_weight(component).sum(dim=1).float()) dist.barrier() if rank == 0: print("OK")