Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions docs/user-guide/customization.md
Original file line number Diff line number Diff line change
Expand Up @@ -381,6 +381,14 @@ resolves to `qwen_image21`. `--diffusion-task` (e.g. `t2i`) must be one of the
**Class** for loading components / FSDP. Default comes from the
family config (usually a `DiffusersModelBackend`).

`DiffusersModelBackend` lets every rank read its own shards of a component from the checkpoint's safetensors
files (`safetensors_files`). A subclass whose `load_component` loads other weights overrides `safetensors_files`
too, naming the files that hold what it loads or `None` for "rank 0 loads and broadcasts". A backend that names
files gives every tensor its final dtype when `load_component` builds without weights (`materialize_weights=False`):
the file values are cast into those dtypes, and no rank loads a model the others could copy them from. Files that
exist but do not hold the model's state dict, or that only some ranks see, are an error, not a fallback; a file may
hold tensors the model does not have.

***

## Worked example
Expand Down
62 changes: 62 additions & 0 deletions miles/backends/fsdp_utils/checkpoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

import json
import logging
import os
import tempfile
import time
from itertools import chain
from pathlib import Path
Expand Down Expand Up @@ -65,6 +67,66 @@ def broadcast_full_state_to_fsdp(
buffer.data = buffer.data.to(torch.cuda.current_device())


def holds_on_every_rank(condition: bool, *, what: str) -> bool:
"""Whether ``condition`` holds on every rank; ranks that answer differently all raise, naming ``what`` holds where."""
conditions = [None] * dist.get_world_size()
dist.all_gather_object(conditions, condition)
if any(conditions) and not all(conditions):
raise ValueError(f"{what} on ranks {[rank for rank, held in enumerate(conditions) if held]} only")
return all(conditions)


def _state_mismatch(model: torch.nn.Module, files: list[Path]) -> str | None:
"""Why the files cannot hold the model's state dict: a tensor of it missing from the files or saved with another
shape, or a buffer outside the state dict that the constructor left on meta (no file holds it). The files may
hold tensors the model does not have."""
from safetensors import safe_open

state = model.state_dict()
on_meta = [name for name, buffer in model.named_buffers() if name not in state and buffer.is_meta]
if on_meta:
return f"buffers outside the state dict are on meta and in no file: {on_meta}"
saved = {}
for file in files:
with safe_open(file, framework="pt") as tensors:
saved.update({name: tuple(tensors.get_slice(name).get_shape()) for name in tensors.keys()})
differing = sorted(name for name, tensor in state.items() if saved.get(name) != tuple(tensor.shape))
if differing:
return f"{len(differing)} tensors of the model are missing from the files or saved with another shape, e.g. {differing[:5]}"
return None


@torch.no_grad()
def load_safetensors_to_fsdp(model: torch.nn.Module, files: list[Path], *, cpu_offload: bool) -> None:
"""Materialize FSDP2 shards by reading each rank's own slice of every parameter from the files.

A buffer outside the state dict is in no file: it keeps the value the constructor computed on this rank.
"""
# Every rank raises or none does: a rank raising alone would leave the others in the collective read.
mismatches = [None] * dist.get_world_size()
dist.all_gather_object(mismatches, _state_mismatch(model, files))
if any(mismatches):
found = "; ".join(f"rank {rank}: {why}" for rank, why in enumerate(mismatches) if why)
raise ValueError(f"{[str(file) for file in files]} do not hold the model's state dict ({found})")
device = torch.cuda.current_device()
# Buffers were computed for real on every rank; to_empty would wipe them. One still on meta is in the state
# dict, and the read fills it. to_empty splits a tensor two modules share, so each name keeps its own entry.
buffers = dict(model.named_buffers(remove_duplicate=False))
model.to_empty(device="cpu" if cpu_offload else device)
for name, buffer in model.named_buffers(remove_duplicate=False):
if not buffers[name].is_meta:
buffer.copy_(buffers[name])
# The reader takes every safetensors file of one folder, and the files' own folder may hold others (a variant).
with tempfile.TemporaryDirectory() as folder:
for file in files:
os.symlink(file.resolve(), Path(folder) / file.name)
dcp.load(model.state_dict(), storage_reader=dcp.HuggingFaceStorageReader(folder, thread_count=4))
if cpu_offload:
# CPUOffloadPolicy manages params only; buffers must live on GPU for forward.
for buffer in model.buffers():
buffer.data = buffer.data.to(device)


def _is_lora_param_name(name: str) -> bool:
return "lora_" in name

Expand Down
72 changes: 67 additions & 5 deletions miles/backends/fsdp_utils/model_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,16 @@
import abc
import functools
import importlib
import json
import logging
import os
from dataclasses import replace
from itertools import chain
from pathlib import Path

import torch
from diffusers import DiffusionPipeline
from diffusers.utils import SAFE_WEIGHTS_INDEX_NAME, SAFETENSORS_WEIGHTS_NAME

from .models.parallel_plan import FSDPParallelPlan
from .sequence_parallel.diffusers_dispatch import install_diffusers_usp_patch
Expand All @@ -33,6 +38,36 @@
logger = logging.getLogger(__name__)


def diffusers_weight_files(checkpoint_path: str, component: str) -> list[Path] | None:
"""The safetensors files ``from_pretrained`` reads a component from with no variant, or None for other weights.

The ones the component's index lists, else its single file; a Hub id is resolved to its snapshot first.
"""
stem = SAFETENSORS_WEIGHTS_NAME.removesuffix(".safetensors")
is_local = os.path.isdir(checkpoint_path)
if not is_local:
from huggingface_hub import snapshot_download
from huggingface_hub.errors import HFValidationError, LocalEntryNotFoundError, RepositoryNotFoundError

patterns = [f"{component}/{SAFETENSORS_WEIGHTS_NAME}*", f"{component}/{stem}-*.safetensors"]
try:
checkpoint_path = snapshot_download(checkpoint_path, allow_patterns=patterns)
except (HFValidationError, LocalEntryNotFoundError, RepositoryNotFoundError):
# Not a folder, and no repo the Hub or the offline cache resolves: load_component says so.
return None
folder = Path(checkpoint_path) / component
index = folder / SAFE_WEIGHTS_INDEX_NAME
if index.is_file():
names = set(json.loads(index.read_text())["weight_map"].values())
elif is_local and (Path(checkpoint_path) / SAFETENSORS_WEIGHTS_NAME).is_file():
# In a local folder from_pretrained takes a single weights file at the root before the component's.
return None
else:
names = {SAFETENSORS_WEIGHTS_NAME}
files = [folder / name for name in sorted(names)]
return files if all(file.is_file() for file in files) else None


class BaseModelBackend(abc.ABC):
"""Contract consumed by the FSDP actor for model-family integration."""

Expand All @@ -54,6 +89,14 @@ def load_component(
) -> torch.nn.Module:
raise NotImplementedError

def safetensors_files(self, component: str, *, checkpoint_path: str) -> list[Path] | None:
"""Local safetensors files every rank can read its shards of the component from; None: rank 0 loads it.

They hold exactly what ``load_component`` loads, and such a backend gives every tensor its final dtype when
it builds without weights: the file values are cast into those dtypes, no rank loads a model to copy from.
"""
return None

@abc.abstractmethod
def enable_gradient_checkpointing(self, model: torch.nn.Module) -> None:
raise NotImplementedError
Expand Down Expand Up @@ -196,18 +239,37 @@ def load_component(
"low_cpu_mem_usage": materialize_weights,
}

# Non-rank0 loads with low_cpu_mem_usage=False so the ambient meta-device
# context keeps params on meta; diffusers forbids that combination when the
# class pins modules to fp32, so disable the pin for the duration (dtypes are
# re-synced from rank0 afterwards, see ``sync_model_dtypes``).
# A build without weights loads with low_cpu_mem_usage=False so the ambient meta-device context keeps
# the parameters on meta; diffusers forbids that combination when the class pins modules to fp32, so the
# pin is off for the call and applied afterwards.
keep_in_fp32 = getattr(model_cls, "_keep_in_fp32_modules", None)
if not materialize_weights and keep_in_fp32 is not None:
model_cls._keep_in_fp32_modules = None
try:
return model_cls.from_pretrained(checkpoint_path, **kwargs)
model = model_cls.from_pretrained(checkpoint_path, **kwargs)
finally:
if not materialize_weights and keep_in_fp32 is not None:
model_cls._keep_in_fp32_modules = keep_in_fp32
if not materialize_weights:
self._cast_state_as_a_load_does(model, master_dtype, keep_in_fp32 or [])
return model

@staticmethod
def _cast_state_as_a_load_does(model: torch.nn.Module, master_dtype: torch.dtype, keep_in_fp32: list[str]) -> None:
"""Give every floating tensor of the state dict the dtype a load with weights gives it.

diffusers casts each one to the master dtype, or to fp32 under the class's pin
(``load_model_dict_into_meta``). A build without weights has the constructor's dtypes, and every rank may
be built that way, so no rank's loaded model is there to copy them from.
"""
saved = set(model.state_dict())
for name, tensor in chain(model.named_parameters(), model.named_buffers()):
if name in saved and tensor.is_floating_point():
pinned = any(module in name.split(".") for module in keep_in_fp32)
tensor.data = tensor.data.to(torch.float32 if pinned else master_dtype)

def safetensors_files(self, component: str, *, checkpoint_path: str) -> list[Path] | None:
return diffusers_weight_files(checkpoint_path, component)

@classmethod
def _resolve_component_class(cls, checkpoint_path: str, component: str):
Expand Down
28 changes: 25 additions & 3 deletions miles/backends/fsdp_utils/model_loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,22 @@ def load_fsdp_models(
trainable: bool = False,
cpu_offload: bool = False,
) -> dict[str, torch.nn.Module]:
materialize_weights = dist.get_rank() == 0
master_dtype = parse_dtype_from_str(args.fsdp_master_dtype)
models = {}
for component_index, component in enumerate(args.update_weight_target_modules):
# Without LoRA every rank reads its own shards from the safetensors files; else rank 0 loads and broadcasts.
use_lora = lora_adapter_paths is not None or (trainable and args.use_lora)
safetensors_files = (
None if use_lora else model_backend.safetensors_files(component, checkpoint_path=checkpoint_path)
)
# Decided before building, on every rank alike: ranks that see the files while others do not raise together.
if not use_lora and not checkpoint.holds_on_every_rank(
safetensors_files is not None,
what=f"the safetensors files of {component} under {checkpoint_path} are seen",
):
safetensors_files = None
materialize_weights = safetensors_files is None and dist.get_rank() == 0
master_dtype = parse_dtype_from_str(args.fsdp_master_dtype)

with model_init_context(materialize_weights=materialize_weights):
model = model_backend.load_component(
component,
Expand All @@ -52,6 +64,13 @@ def load_fsdp_models(

if not materialize_weights and any(not parameter.is_meta for parameter in model.parameters()):
raise RuntimeError(f"{component} did not honor meta initialization")
if dist.get_rank() == 0:
source = "rank 0 loads and broadcasts"
if safetensors_files is not None:
source = (
f"every rank reads {len(safetensors_files)} safetensors files of {safetensors_files[0].parent}"
)
logger.info(f"FSDP: {component} weights of {checkpoint_path}: {source}")
checkpoint.sync_model_dtypes(model)
full_state = model.state_dict() if materialize_weights else {}
model = apply_fsdp2(
Expand All @@ -61,7 +80,10 @@ def load_fsdp_models(
cpu_offload=cpu_offload,
args=args,
)
checkpoint.broadcast_full_state_to_fsdp(model, full_state, cpu_offload=cpu_offload)
if safetensors_files is not None:
checkpoint.load_safetensors_to_fsdp(model, safetensors_files, cpu_offload=cpu_offload)
else:
checkpoint.broadcast_full_state_to_fsdp(model, full_state, cpu_offload=cpu_offload)
del full_state
train_pipeline_config.postprocess_model_after_materialize(model)
if parallel_state.get_optional_mesh("sp") is not None:
Expand Down
96 changes: 96 additions & 0 deletions tests/fast-gpu/backends/fsdp_utils/_safetensors_load_worker.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
"""Two ranks read their own halves of a safetensors checkpoint.

files hold the state dict --> both ranks on meta --> rows [0:2] on rank 0, rows [2:4] on rank 1, GPU or CPU offload
a buffer no file holds --> the value this rank's constructor computed
another name in the files --> ValueError on both ranks
another name on rank 1 only --> the same error on both ranks: the ranks agree before either reads
files seen by rank 1 only --> ValueError on both ranks before either builds
"""

import os
import sys
from pathlib import Path
from types import SimpleNamespace

import torch
import torch.distributed as dist
from tests.fast.backends.fsdp_utils.test_reference_models import TinyPipelineConfig, make_model_loader_args
from tests.fast.backends.fsdp_utils.test_safetensors_load import FileBackend, save_checkpoint, saved_weight
from torch.distributed.device_mesh import init_device_mesh

from miles.backends.fsdp_utils.model_loader import load_fsdp_models


class RankTaggedBackend(FileBackend):
"""A buffer outside the state dict whose constructor value differs between the ranks; rank 0 sees no files
under a checkpoint named `rank1-only`."""

def safetensors_files(self, component, *, checkpoint_path):
if Path(checkpoint_path).name == "rank1-only" and dist.get_rank() == 0:
return None
return super().safetensors_files(component, checkpoint_path=checkpoint_path)

def load_component(self, component, **kwargs):
model = super().load_component(component, **kwargs)
model.register_buffer("built_on_rank", torch.tensor(float(dist.get_rank())), persistent=False)
return model


def load(mesh, path, cpu_offload):
parallel = SimpleNamespace(get_mesh=lambda name: mesh, get_optional_mesh=lambda name: None)
args, backend = make_model_loader_args(), RankTaggedBackend()
args.use_lora = False
models = load_fsdp_models(
args, backend, TinyPipelineConfig(), parallel, checkpoint_path=str(path), cpu_offload=cpu_offload
)
for model in models.values():
shard = model.block.proj.weight.to_local()
assert shard.shape == (2, 3) and shard.dtype == torch.float32
assert shard.device.type == ("cpu" if cpu_offload else "cuda")
assert model.forward_count.device.type == "cuda" and model.forward_count.item() == 0
assert model.built_on_rank.device.type == "cuda" and model.built_on_rank.item() == dist.get_rank()
return models, backend.materialize_requests


def main():
torch.cuda.set_device(int(os.environ["LOCAL_RANK"]))
dist.init_process_group("nccl", device_id=torch.device("cuda", torch.cuda.current_device()))
mesh = init_device_mesh("cuda", (dist.get_world_size(),))
rank, root = dist.get_rank(), Path(sys.argv[1])
if rank == 0:
save_checkpoint(root / "state")
save_checkpoint(root / "renamed", name="block.proj.kernel")
save_checkpoint(root / "rank1-only")
dist.barrier()
inputs = torch.ones(2, 3, device="cuda")
for cpu_offload in (False, True):
models, materialize_requests = load(mesh, root / "state", cpu_offload)
assert materialize_requests == [False, False]
for component, model in models.items():
expected = saved_weight(component).float()
assert torch.equal(model.block.proj.weight.to_local().cpu(), expected[2 * rank : 2 * rank + 2])
with torch.no_grad():
torch.testing.assert_close(model(inputs).cpu(), (inputs.cpu() @ expected.T).tanh())

for path in ("renamed", "renamed" if rank == 1 else "state"):
# Both ranks raise, also when only rank 1's copy holds another name: rank 0 must not enter the read alone.
try:
load(mesh, root / path, cpu_offload)
except ValueError as error:
assert "do not hold the model's state dict" in str(error) and "rank 1" in str(error)
else:
raise AssertionError(f"{path}: expected a ValueError on every rank")
try:
load(mesh, root / "rank1-only", cpu_offload)
except ValueError as error:
assert "are seen on ranks [1] only" in str(error)
else:
raise AssertionError("rank1-only: expected a ValueError on every rank")
dist.barrier()
if rank == 0:
print("OK")
dist.destroy_process_group()


if __name__ == "__main__":
main()
Loading
Loading