Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
f2500c8
perf(fsdp): every rank reads its own shards from the checkpoint's saf…
zhihengy Nov 16, 2026
0414fef
perf(fsdp): the backend names the safetensors files every rank reads,…
zhihengy Nov 17, 2026
2b525d4
fix(fsdp): rank 0's second build starts from the generator state of i…
zhihengy Nov 17, 2026
db154d2
perf(fsdp): a model with LoRA reads its base shards from the safetens…
zhihengy Nov 17, 2026
0e6ba54
fix(fsdp): a component built without weights gives the state dict's b…
zhihengy Nov 17, 2026
31ca0c4
fix(fsdp): a single weights file at the root of a local checkpoint le…
zhihengy Nov 17, 2026
d3fbbc2
fix(fsdp): a checkpoint that is neither a folder nor a repo id names …
zhihengy Nov 17, 2026
8398f28
fix(fsdp): a buffer on meta that no file holds sends the component to…
zhihengy Nov 17, 2026
13ccdea
refactor(fsdp): holds_on_every_rank(condition) and safetensors_files …
zhihengy Nov 17, 2026
ff497b3
Merge fsdp/read-shards-from-safetensors into fsdp/read-lora-shards-fr…
zhihengy Nov 17, 2026
34b5655
fix(fsdp): only a model with an adapter takes the adapter step; one w…
zhihengy Nov 17, 2026
a157d4c
fix(fsdp): every rank says whether it reads the files even when its a…
zhihengy Nov 17, 2026
46cdf84
fix(fsdp): the base stands in as one expanded element while the adapt…
zhihengy Nov 17, 2026
20ea86e
fix(fsdp): a saved adapter is built on every rank only when it is a L…
zhihengy Nov 17, 2026
04176f9
refactor(fsdp): base_state takes the checkpoint's names from to_hf_na…
zhihengy Nov 17, 2026
2ea73ff
fix(fsdp): a saved DoRA adapter leaves the load to rank 0: PEFT takes…
zhihengy Nov 17, 2026
6cf4870
fix(fsdp): a buffer no file holds takes rank 0's value on every rank …
zhihengy Nov 17, 2026
9ca202c
fix(fsdp): a DiffusersModelBackend subclass that overrides load_compo…
zhihengy Nov 17, 2026
51c40a3
fix(fsdp): a repo id the Hub or the offline cache cannot resolve name…
zhihengy Nov 17, 2026
24f3e1b
test(fsdp): two ranks whose files differ on one rank only both take t…
zhihengy Nov 17, 2026
5af5cc8
test(fsdp): the variant beside the read files has another shape, so r…
zhihengy Nov 17, 2026
e901c3d
test(fsdp): the files safetensors_files names hold the state a real d…
zhihengy Nov 17, 2026
c1e7cf2
Merge fsdp/read-shards-from-safetensors into fsdp/read-lora-shards-fr…
zhihengy Nov 17, 2026
c292594
fix(fsdp): the base is checked for meta before the adapter step, whic…
zhihengy Nov 17, 2026
9d4a508
test(fsdp): the two-rank LoRA case runs a forward on the model read p…
zhihengy Nov 17, 2026
74e3368
docs(fsdp): base_storage_for_lora states its two boundaries: an Embed…
zhihengy Nov 17, 2026
7d79915
fix(fsdp): the gate asks a saved adapter's PEFT type, so AdaLoRA, who…
zhihengy Nov 17, 2026
baacad0
test(fsdp): an adapter saved as .bin is not built on every rank; a fr…
zhihengy Nov 17, 2026
795d1e2
refactor(fsdp): rank 0 alone builds the adapter, on a stand-in for it…
zhihengy Nov 17, 2026
c687ff0
test(fsdp): a checkpoint in two files, a frozen model in a run that t…
zhihengy Nov 17, 2026
d833ec3
docs(fsdp): a backend that names files gives every tensor its final d…
zhihengy Nov 17, 2026
0314dd6
Merge fsdp/read-shards-from-safetensors into fsdp/read-lora-shards-fr…
zhihengy Nov 17, 2026
b8337f8
fix(fsdp): the ranks agree on the adapter's tensor names and shapes b…
zhihengy Nov 17, 2026
48f0ab8
test(fsdp): the two-rank LoRA case loads a model with a persistent bu…
zhihengy Nov 17, 2026
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
6 changes: 6 additions & 0 deletions docs/user-guide/customization.md
Original file line number Diff line number Diff line change
Expand Up @@ -381,6 +381,12 @@ 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. 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.

***

## Worked example
Expand Down
91 changes: 88 additions & 3 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 All @@ -13,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__)


Expand Down Expand Up @@ -65,7 +69,88 @@ def broadcast_full_state_to_fsdp(
buffer.data = buffer.data.to(torch.cuda.current_device())


def _is_lora_param_name(name: str) -> bool:
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 {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 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.

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 base_state(model).items()}


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()
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 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 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(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. 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
)
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():
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:
return "lora_" in name


Expand All @@ -80,7 +165,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):
Expand All @@ -94,7 +179,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, "
Expand Down
76 changes: 71 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,15 @@ 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 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

@abc.abstractmethod
def enable_gradient_checkpointing(self, model: torch.nn.Module) -> None:
raise NotImplementedError
Expand Down Expand Up @@ -196,18 +240,40 @@ 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:
# 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
return diffusers_weight_files(checkpoint_path, component)

@classmethod
def _resolve_component_class(cls, checkpoint_path: str, component: str):
Expand Down
Loading
Loading