diff --git a/docs/user-guide/customization.md b/docs/user-guide/customization.md index d4eed2185..f481afe63 100644 --- a/docs/user-guide/customization.md +++ b/docs/user-guide/customization.md @@ -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 diff --git a/miles/backends/fsdp_utils/checkpoint.py b/miles/backends/fsdp_utils/checkpoint.py index ff88c4d35..bbad7b6c0 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 @@ -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__) @@ -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 @@ -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): @@ -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, " diff --git a/miles/backends/fsdp_utils/model_backend.py b/miles/backends/fsdp_utils/model_backend.py index ff470e54c..e48ba0f26 100644 --- a/miles/backends/fsdp_utils/model_backend.py +++ b/miles/backends/fsdp_utils/model_backend.py @@ -20,11 +20,16 @@ import abc import functools import importlib +import json import logging +import os from dataclasses import replace +from itertools import chain +from pathlib import Path import torch from diffusers import DiffusionPipeline +from diffusers.utils import SAFE_WEIGHTS_INDEX_NAME, SAFETENSORS_WEIGHTS_NAME from .models.parallel_plan import FSDPParallelPlan from .sequence_parallel.diffusers_dispatch import install_diffusers_usp_patch @@ -33,6 +38,36 @@ logger = logging.getLogger(__name__) +def diffusers_weight_files(checkpoint_path: str, component: str) -> list[Path] | None: + """The safetensors files ``from_pretrained`` reads a component from with no variant, or None for other weights. + + The ones the component's index lists, else its single file; a Hub id is resolved to its snapshot first. + """ + stem = SAFETENSORS_WEIGHTS_NAME.removesuffix(".safetensors") + is_local = os.path.isdir(checkpoint_path) + if not is_local: + from huggingface_hub import snapshot_download + from huggingface_hub.errors import HFValidationError, LocalEntryNotFoundError, RepositoryNotFoundError + + patterns = [f"{component}/{SAFETENSORS_WEIGHTS_NAME}*", f"{component}/{stem}-*.safetensors"] + try: + checkpoint_path = snapshot_download(checkpoint_path, allow_patterns=patterns) + except (HFValidationError, LocalEntryNotFoundError, RepositoryNotFoundError): + # Not a folder, and no repo the Hub or the offline cache resolves: load_component says so. + return None + folder = Path(checkpoint_path) / component + index = folder / SAFE_WEIGHTS_INDEX_NAME + if index.is_file(): + names = set(json.loads(index.read_text())["weight_map"].values()) + elif is_local and (Path(checkpoint_path) / SAFETENSORS_WEIGHTS_NAME).is_file(): + # In a local folder from_pretrained takes a single weights file at the root before the component's. + return None + else: + names = {SAFETENSORS_WEIGHTS_NAME} + files = [folder / name for name in sorted(names)] + return files if all(file.is_file() for file in files) else None + + class BaseModelBackend(abc.ABC): """Contract consumed by the FSDP actor for model-family integration.""" @@ -54,6 +89,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 @@ -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): diff --git a/miles/backends/fsdp_utils/model_loader.py b/miles/backends/fsdp_utils/model_loader.py index ca61e39ec..e5be8b2fe 100644 --- a/miles/backends/fsdp_utils/model_loader.py +++ b/miles/backends/fsdp_utils/model_loader.py @@ -4,6 +4,8 @@ import warnings from argparse import Namespace from contextlib import contextmanager +from functools import partial +from pathlib import Path import torch import torch.distributed as dist @@ -27,33 +29,51 @@ 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") + 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, + model_backend, + train_pipeline_config, + component, + checkpoint_path=checkpoint_path, + lora_adapter_path=lora_adapter_path, + has_lora=has_lora, + trainable=trainable, + ) + # Every rank reads its own shards of the base from the safetensors files; else rank 0 loads and broadcasts. + safetensors_files = None + 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) + 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, 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), + 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. + torch.set_rng_state(rng_state) + materialize_weights = True + model = build(materialize_weights=True) + safetensors_files = None + 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 {} + # 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), @@ -61,8 +81,11 @@ def load_fsdp_models( cpu_offload=cpu_offload, args=args, ) - checkpoint.broadcast_full_state_to_fsdp(model, full_state, cpu_offload=cpu_offload) - del full_state + if safetensors_files is not None: + 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, adapter_state train_pipeline_config.postprocess_model_after_materialize(model) if parallel_state.get_optional_mesh("sp") is not None: apply_sequence_parallel( @@ -79,6 +102,109 @@ def load_fsdp_models( return models +# 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 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: + 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 + 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 + # 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 + with safe_open(file, framework="pt") as tensors: + return all(checkpoint.is_lora_param_name(name) for name in tensors.keys()) + + +def build_component( + args: Namespace, + model_backend, + train_pipeline_config, + component: str, + *, + checkpoint_path: str, + lora_adapter_path: str | None, + has_lora: bool, + 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, + ) + # 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) + 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 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_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 in host memory. + """ + if not enabled: + yield + return + 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")) + + +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. @@ -122,16 +248,13 @@ def apply_lora(model: torch.nn.Module, args: Namespace, train_pipeline_config) - 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 - 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=False if on_meta else init_lora_weight, + init_lora_weights=False if on_meta else peft_init_lora_weights(args), ), low_cpu_mem_usage=on_meta, ) 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..09197eca4 --- /dev/null +++ b/tests/fast-gpu/backends/fsdp_utils/_safetensors_load_worker.py @@ -0,0 +1,162 @@ +"""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 + another name on rank 1 only --> the same: the ranks agree before either reads + LoRA, saved or new --> rank 0's adapter on both ranks: the shards and the generator the broadcast leaves +""" + +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, + save_component_lora_adapters, +) +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 + +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, *, 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(), 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( + args, backend, TinyPipelineConfig(), parallel, checkpoint_path=str(path), cpu_offload=cpu_offload, **kwargs + ) + for model in models.values(): + 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 base.forward_count.device.type == "cuda" and base.forward_count.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 + + +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 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] + 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 + 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]) + 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())) + 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_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): + 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) + + # 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) + + 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") + 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..d7cd535de --- /dev/null +++ b/tests/fast-gpu/backends/fsdp_utils/test_safetensors_load.py @@ -0,0 +1,51 @@ +"""Two ranks read their own shards of a safetensors checkpoint, 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 + 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 + +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..00f76eecc 100644 --- a/tests/fast/backends/fsdp_utils/test_model_backend.py +++ b/tests/fast/backends/fsdp_utils/test_model_backend.py @@ -9,10 +9,18 @@ register_cpu_ci(est_time=15, suite="stage-a-cpu", labels=[]) import json +from itertools import chain +import httpx +import pytest import torch +from diffusers import ConfigMixin, ModelMixin, SD3Transformer2DModel, WanTransformer3DModel +from diffusers.configuration_utils import register_to_config +from huggingface_hub.errors import LocalEntryNotFoundError, RepositoryNotFoundError +from safetensors.torch import load_file, save_file from miles.backends.fsdp_utils.model_backend import BaseModelBackend, DiffusersModelBackend, MilesModelBackend +from miles.backends.fsdp_utils.model_loader import model_init_context from miles.backends.fsdp_utils.models.diffusers import load_fsdp_parallel_plan @@ -39,6 +47,151 @@ def from_pretrained(cls, checkpoint_path, **kwargs): return model +class _PinnedComponent(torch.nn.Module): + _keep_in_fp32_modules = ["norm"] + + def __init__(self): + super().__init__() + self.proj = torch.nn.Linear(2, 2) + self.norm = torch.nn.LayerNorm(2) + + @classmethod + def from_pretrained(cls, checkpoint_path, *, torch_dtype, **kwargs): + assert cls._keep_in_fp32_modules is None + return cls().to(torch_dtype) + + +WEIGHTS_FILE = "diffusion_pytorch_model.safetensors" + + +class _PinnedBufferModel(ModelMixin, ConfigMixin): + """Persistent buffers (BatchNorm's running statistics) under a module the class pins to fp32.""" + + _keep_in_fp32_modules = ["norm"] + + @register_to_config + def __init__(self): + super().__init__() + self.proj = torch.nn.Linear(2, 2) + self.norm = torch.nn.BatchNorm1d(2) + + +class _TransientBufferModel(ModelMixin, ConfigMixin): + """A buffer outside the state dict, made in fp32 whatever the default dtype (H3's and Cosmos3's inv_freq).""" + + @register_to_config + def __init__(self): + super().__init__() + self.proj = torch.nn.Linear(2, 2) + self.register_buffer("inv_freq", torch.arange(4, dtype=torch.float32) / 10, persistent=False) + + +def _tiny_sd3(): + # Its pos_embed is a persistent buffer the constructor makes in fp32 whatever the default dtype. + return SD3Transformer2DModel( + sample_size=8, + patch_size=2, + in_channels=4, + num_layers=1, + attention_head_dim=8, + num_attention_heads=2, + joint_attention_dim=16, + caption_projection_dim=16, + pooled_projection_dim=16, + out_channels=4, + pos_embed_max_size=8, + ) + + +def _tiny_wan(): + # Pins modules to fp32 and has buffers outside the state dict (the rope tables). + return WanTransformer3DModel( + patch_size=(1, 2, 2), + num_attention_heads=2, + attention_head_dim=12, + in_channels=4, + out_channels=4, + text_dim=16, + freq_dim=16, + ffn_dim=32, + num_layers=1, + cross_attn_norm=True, + rope_max_seq_len=32, + ) + + +@pytest.mark.parametrize( + "make, class_spec", + [ + pytest.param(_tiny_sd3, ["diffusers", "SD3Transformer2DModel"], id="a persistent buffer made in fp32"), + pytest.param(_tiny_wan, ["diffusers", "WanTransformer3DModel"], id="modules pinned to fp32"), + pytest.param(_PinnedBufferModel, [__name__, "_PinnedBufferModel"], id="a persistent buffer under the pin"), + pytest.param(_TransientBufferModel, [__name__, "_TransientBufferModel"], id="a buffer no load casts"), + ], +) +@pytest.mark.parametrize("master_dtype", [torch.bfloat16, torch.float16, torch.float32]) +def test_a_component_built_without_weights_has_the_dtypes_a_load_with_weights_gives( + tmp_path, make, class_spec, master_dtype +): + # Every rank may build on meta and read its shards from the files, so no loaded model is there to copy from. + make().save_pretrained(tmp_path / "transformer") + (tmp_path / "model_index.json").write_text( + json.dumps({"_class_name": "DiffusionPipeline", "transformer": class_spec}) + ) + dtypes = {} + for materialize_weights in (True, False): + with model_init_context(materialize_weights=materialize_weights): + model = DiffusersModelBackend(None).load_component( + "transformer", + checkpoint_path=str(tmp_path), + master_dtype=master_dtype, + materialize_weights=materialize_weights, + ) + tensors = chain(model.named_parameters(), model.named_buffers()) + dtypes[materialize_weights] = {name: tensor.dtype for name, tensor in tensors} + assert dtypes[False] == dtypes[True] + + +def _save_as_pipeline(model, path, **kwargs): + model.save_pretrained(path / "transformer", **kwargs) + (path / "model_index.json").write_text( + json.dumps({"_class_name": "DiffusionPipeline", "transformer": ["diffusers", "SD3Transformer2DModel"]}) + ) + + +def _load_with_weights(path): + with model_init_context(materialize_weights=True): + return DiffusersModelBackend(None).load_component( + "transformer", checkpoint_path=str(path), master_dtype=torch.float32, materialize_weights=True + ) + + +@pytest.mark.parametrize("sharded", [False, True], ids=["the single file", "the files the index lists"]) +@pytest.mark.parametrize("variant", [False, True], ids=["alone", "beside a variant with other weights"]) +def test_the_named_files_hold_the_state_a_load_with_weights_gives(tmp_path, sharded, variant): + # safetensors_files mirrors which files diffusers' from_pretrained reads; this ties it to diffusers itself. + _save_as_pipeline(_tiny_sd3(), tmp_path, max_shard_size="20KB" if sharded else "10GB") + if variant: + _tiny_sd3().save_pretrained(tmp_path / "transformer", variant="fp16") + + files = DiffusersModelBackend(None).safetensors_files("transformer", checkpoint_path=str(tmp_path)) + + assert (len(files) > 1) is sharded + named = {name: tensor for file in files for name, tensor in load_file(file).items()} + loaded = _load_with_weights(tmp_path).state_dict() + assert named.keys() == loaded.keys() and all(torch.equal(named[name], loaded[name]) for name in named) + + +def test_a_load_with_weights_reads_the_weights_file_at_the_root_of_a_local_checkpoint(tmp_path): + # Why such a checkpoint names no files: diffusers reads the root's file, not the component's. + _save_as_pipeline(_tiny_sd3(), tmp_path) + component = load_file(tmp_path / "transformer" / "diffusion_pytorch_model.safetensors") + save_file({name: torch.zeros_like(tensor) for name, tensor in component.items()}, tmp_path / WEIGHTS_FILE) + + assert DiffusersModelBackend(None).safetensors_files("transformer", checkpoint_path=str(tmp_path)) is None + assert all(tensor.count_nonzero() == 0 for tensor in _load_with_weights(tmp_path).state_dict().values()) + + class TestBackendHierarchy: def test_concrete_backends_are_sibling_implementations(self): assert issubclass(MilesModelBackend, BaseModelBackend) @@ -83,3 +236,100 @@ def test_component_loads_from_its_own_role_checkpoint(self, tmp_path): "torch_dtype": torch.float32, "low_cpu_mem_usage": True, } + + def test_a_component_built_without_weights_keeps_its_fp32_modules(self, tmp_path): + # Every rank may build on meta, so rank 0's loaded dtypes are not there to copy the fp32 pin from. + (tmp_path / "model_index.json").write_text( + json.dumps({"_class_name": "DiffusionPipeline", "transformer": [__name__, "_PinnedComponent"]}) + ) + + model = DiffusersModelBackend(None).load_component( + "transformer", checkpoint_path=str(tmp_path), master_dtype=torch.bfloat16, materialize_weights=False + ) + + assert {name: parameter.dtype for name, parameter in model.named_parameters()} == { + "proj.weight": torch.bfloat16, + "proj.bias": torch.bfloat16, + "norm.weight": torch.float32, + "norm.bias": torch.float32, + } + assert _PinnedComponent._keep_in_fp32_modules == ["norm"] + + def test_a_hub_checkpoint_resolves_to_the_weight_files_of_its_snapshot(self, tmp_path, monkeypatch): + folder = tmp_path / "transformer" + folder.mkdir() + (folder / "diffusion_pytorch_model.safetensors").touch() + (folder / "diffusion_pytorch_model.fp16.safetensors").touch() + downloads = [] + + def snapshot_download(repo_id, *, allow_patterns): + downloads.append((repo_id, allow_patterns)) + return str(tmp_path) + + monkeypatch.setattr("huggingface_hub.snapshot_download", snapshot_download) + + files = DiffusersModelBackend(None).safetensors_files("transformer", checkpoint_path="org/model") + + assert files == [folder / "diffusion_pytorch_model.safetensors"] + assert downloads == [ + ( + "org/model", + [ + "transformer/diffusion_pytorch_model.safetensors*", + "transformer/diffusion_pytorch_model-*.safetensors", + ], + ) + ] + + def test_a_weights_file_at_the_root_of_a_local_checkpoint_leaves_the_load_to_rank_0(self, tmp_path): + # from_pretrained reads /diffusion_pytorch_model.safetensors before the component's own file. + (tmp_path / "transformer").mkdir() + (tmp_path / "transformer" / "diffusion_pytorch_model.safetensors").touch() + backend = DiffusersModelBackend(None) + assert backend.safetensors_files("transformer", checkpoint_path=str(tmp_path)) == [ + tmp_path / "transformer" / "diffusion_pytorch_model.safetensors" + ] + + (tmp_path / "diffusion_pytorch_model.safetensors").touch() + + assert backend.safetensors_files("transformer", checkpoint_path=str(tmp_path)) is None + + def test_a_checkpoint_that_is_neither_a_folder_nor_a_repo_id_names_no_files(self, tmp_path): + # load_component then reports the path, as it does without this hook. + backend = DiffusersModelBackend(None) + assert backend.safetensors_files("transformer", checkpoint_path=str(tmp_path / "missing")) is None + + @pytest.mark.parametrize( + "error", + [ + pytest.param(LocalEntryNotFoundError("no cached snapshot"), id="offline and not in the cache"), + pytest.param( + RepositoryNotFoundError( + "404", response=httpx.Response(404, request=httpx.Request("GET", "https://huggingface.co")) + ), + id="no such repo", + ), + ], + ) + def test_a_repo_id_that_does_not_resolve_names_no_files(self, monkeypatch, error): + # A mistyped relative folder such as ckpts/h3 parses as a repo id; load_component names it in its error. + def snapshot_download(repo_id, *, allow_patterns): + raise error + + monkeypatch.setattr("huggingface_hub.snapshot_download", snapshot_download) + + assert DiffusersModelBackend(None).safetensors_files("transformer", checkpoint_path="ckpts/h3") is None + + 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_reference_models.py b/tests/fast/backends/fsdp_utils/test_reference_models.py index e90e271a2..fd1dd34ea 100644 --- a/tests/fast/backends/fsdp_utils/test_reference_models.py +++ b/tests/fast/backends/fsdp_utils/test_reference_models.py @@ -78,6 +78,9 @@ def load_component(self, component, *, checkpoint_path, master_dtype, materializ model.block.proj.weight.fill_(value) return model + def safetensors_files(self, component, *, checkpoint_path): + return None + def fsdp_parallel_plan(self, model): return FSDPParallelPlan(no_split_modules=("TinyBlock",)) @@ -204,6 +207,7 @@ def unsharded_model_loader(monkeypatch): calls = [] monkeypatch.setattr(model_loader.dist, "get_rank", lambda: 0) monkeypatch.setattr(model_loader.checkpoint, "sync_model_dtypes", lambda model: None) + monkeypatch.setattr(model_loader.checkpoint, "holds_on_every_rank", lambda condition, 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 new file mode 100644 index 000000000..8c2235a9b --- /dev/null +++ b/tests/fast/backends/fsdp_utils/test_safetensors_load.py @@ -0,0 +1,473 @@ +"""Every rank reads its own shards of a diffusers safetensors checkpoint. + + 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 --> 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. +""" + +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 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, + TinyComponent, + TinyPipelineConfig, + make_model_loader_args, + save_component_lora_adapters, +) +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 diffusers_weight_files + +BROADCAST_VALUE = 0.75 + + +class FileBackend(TinyBackend): + def safetensors_files(self, component, *, checkpoint_path): + return diffusers_weight_files(checkpoint_path, component) + + def __init__(self): + super().__init__() + self.materialize_requests = [] + + def load_component(self, component, *, checkpoint_path, master_dtype, materialize_weights): + self.materialize_requests.append(materialize_weights) + # 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 + + +def saved_weight(component): + return torch.arange(12, dtype=torch.bfloat16).reshape(4, 3) + (100 if component == "transformer_2" else 0) + + +def save_checkpoint(path, *, name="block.proj.weight", shape=(4, 3), sharded=True): + 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( + json.dumps({"weight_map": {name: file}}) + ) + + +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) + monkeypatch.setattr( + model_loader.checkpoint, "broadcast_full_state_to_fsdp", lambda model, state, **_: broadcasts.append(state) + ) + monkeypatch.setattr(torch.cuda, "current_device", lambda: torch.device("cpu")) + dist.init_process_group("gloo", store=dist.HashStore(), rank=0, world_size=1) + try: + mesh = init_device_mesh("cpu", (1,)) + parallel = SimpleNamespace(get_mesh=lambda name: mesh, get_optional_mesh=lambda name: None) + args, backend = make_model_loader_args(), (backend_cls or FileBackend)() + args.use_lora = 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 + ) + return models, backend.materialize_requests, broadcasts + finally: + 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: + # Another shape: a reader that took the variant fails whichever file its folder lists last. + save_file( + {"block.proj.weight": torch.zeros(8, 3)}, path / component / "diffusion_pytorch_model.fp16.safetensors" + ) + + +@pytest.mark.parametrize( + "save", + [ + pytest.param(save_checkpoint, id="the files the index lists"), + pytest.param(lambda path: save_checkpoint(path, sharded=False), id="the single file"), + pytest.param(lambda path: add_variant_file(path, sharded=True), id="a variant beside the listed files"), + pytest.param(lambda path: add_variant_file(path, sharded=False), id="a variant beside the single file"), + ], +) +def test_every_rank_reads_its_shards_from_the_files(tmp_path, monkeypatch, save): + save(tmp_path) + models, materialize_requests, broadcasts = load(monkeypatch, tmp_path) + assert materialize_requests == [False, False] and broadcasts == [] + for component, model in models.items(): + weight = model.block.proj.weight + assert weight.dtype == torch.float32 + assert torch.equal(weight.to_local(), saved_weight(component).float()) + assert model.forward_count.item() == 0 + torch.testing.assert_close( + model(torch.ones(2, 3)), (torch.ones(2, 3) @ saved_weight(component).float().T).tanh() + ) + assert model.forward_count.item() == 1 + + +def remove_a_listed_file(path): + save_checkpoint(path) + (path / "transformer" / "diffusion_pytorch_model-00001-of-00001.safetensors").unlink() + + +@pytest.mark.parametrize( + "save, rebuilt", + [ + 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"), + ], +) +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_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]) + + +class DerivedBufferComponent(TinyComponent): + """A buffer the constructor derives from a parameter: on meta when the component is built without weights.""" + + persistent = True + + def __init__(self): + super().__init__() + self.register_buffer("row_sums", self.block.proj.weight.sum(dim=1), persistent=self.persistent) + + +class TransientDerivedBufferComponent(DerivedBufferComponent): + persistent = False + + +class SharedBufferComponent(TinyComponent): + """One tensor registered as a buffer of two modules.""" + + def __init__(self): + super().__init__() + table = torch.arange(3.0) + self.block.register_buffer("table", table, persistent=False) + self.register_buffer("table", table, persistent=False) + + +def backend_of(component_cls): + class Backend(FileBackend): + def load_component(self, component, *, checkpoint_path, master_dtype, materialize_weights): + self.materialize_requests.append(materialize_weights) + model = component_cls().to(dtype=master_dtype) + if materialize_weights: + with torch.no_grad(): + model.block.proj.weight.fill_(BROADCAST_VALUE) + return model + + return Backend + + +def save_row_sums(path): + """The weight in one file and the buffer in another: the state dict is the union of what the index lists.""" + for component in make_model_loader_args().update_weight_target_modules: + folder = path / component + folder.mkdir(parents=True) + files = { + "block.proj.weight": "diffusion_pytorch_model-00001-of-00002.safetensors", + "row_sums": "diffusion_pytorch_model-00002-of-00002.safetensors", + } + save_file({"block.proj.weight": saved_weight(component)}, folder / files["block.proj.weight"]) + save_file({"row_sums": saved_weight(component).sum(dim=1)}, folder / files["row_sums"]) + (folder / "diffusion_pytorch_model.safetensors.index.json").write_text(json.dumps({"weight_map": files})) + + +def test_a_state_dict_buffer_the_constructor_left_on_meta_is_read_from_the_files(tmp_path, monkeypatch): + save_row_sums(tmp_path) + models, materialize_requests, broadcasts = load( + monkeypatch, tmp_path, backend_cls=backend_of(DerivedBufferComponent) + ) + assert materialize_requests == [False, False] and broadcasts == [] + for component, model in models.items(): + assert torch.equal(model.row_sums, saved_weight(component).sum(dim=1).float()) + assert model.forward_count.item() == 0 + + +def test_a_buffer_on_meta_that_no_file_holds_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) + conditions = [] + _, materialize_requests, broadcasts = load( + 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 + + +def test_a_model_without_an_adapter_skips_the_adapter_step(tmp_path, monkeypatch): + save_checkpoint(tmp_path) + monkeypatch.setattr( + 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 base gets a stand-in") + ) + _, 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(): + # 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_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__() + 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, 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"), + 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"), + 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_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 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 built_without_base_weights + ) + + +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_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} + + +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) + 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) + 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, 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): + 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) + conditions = [] + _, materialize_requests, broadcasts = load( + monkeypatch, + tmp_path, + lora_init="pissa", + trainable=True, + 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. + assert conditions == [False, False] and materialize_requests == [True, True] and len(broadcasts) == 2 + assert all(len(lora_weights(state)) == 2 for state in broadcasts) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v"]))