Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / checkpoint / load_groups.py: 85%
275 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
1# Copyright 2026 Huawei Technologies Co., Ltd
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14# ============================================================================
15"""Hugging Face checkpoint names and layouts, mapped onto the tensors of a finalized model.
17Both pretrained loaders are built on what is here. :class:`HuggingFaceCheckpointer` reads whole checkpoint
18tensors and converts them in memory, while :class:`HFLoadPlanner` plans the same conversions as
19distributed checkpoint reads. Keys are renamed, converters are chosen and replacement conversions are
20routed the same way in both, so the two load the same values under the same names.
21"""
22import json
23import logging
24from collections import Counter, OrderedDict, defaultdict
25from collections.abc import Callable, Iterable, Sequence
26from copy import deepcopy
27from dataclasses import dataclass
28from pathlib import Path
29from typing import Any, Optional
31import torch
32from huggingface_hub import snapshot_download
33from safetensors import safe_open
34from torch import nn
36from hyper_parallel import DTensor, Partial, distribute_tensor
37from hyper_parallel.components.checkpoint.weight_conversion import (
38 WeightConverter,
39 WeightRenaming,
40 dot_natural_key,
41 rename_source_key,
42)
44logger = logging.getLogger(__name__)
46SAFE_WEIGHTS_NAME = "model.safetensors"
47SAFE_WEIGHTS_INDEX_NAME = "model.safetensors.index.json"
48DIFFUSERS_SAFE_WEIGHTS_NAME = "diffusion_pytorch_model.safetensors"
49DIFFUSERS_SAFE_WEIGHTS_INDEX_NAME = "diffusion_pytorch_model.safetensors.index.json"
50_SNAPSHOT_PATTERNS = ("*.safetensors", "*.safetensors.index.json", "engram_host_rows.json")
52# Picks the converter a checkpoint key matched by ``source pattern`` belongs to, for the model tensor
53# ``target name``, out of every converter with that source pattern. None when no single one fits.
54ConverterSelector = Callable[[str, str, Sequence[WeightConverter]], Optional[WeightConverter]]
57@dataclass(frozen=True)
58class LoadReport:
59 """Summary of one pretrained-weight load."""
61 loaded_keys: tuple[str, ...]
62 missing_keys: tuple[str, ...]
63 unexpected_keys: tuple[str, ...]
66@dataclass(frozen=True)
67class CheckpointIndex:
68 """Map checkpoint tensor names to their safetensors shard files."""
70 files_by_key: dict[str, Path]
72 def keys(self) -> tuple[str, ...]:
73 """Return checkpoint keys in deterministic natural order."""
74 return sorted_checkpoint_keys(self.files_by_key)
76 def load_tensor(self, key: str) -> torch.Tensor:
77 """Materialize one checkpoint tensor on CPU."""
78 file_path = self.files_by_key.get(key)
79 if file_path is None:
80 raise ValueError(f"Checkpoint key is not indexed: {key}")
81 with safe_open(str(file_path), framework="pt", device="cpu") as checkpoint:
82 return checkpoint.get_tensor(key)
85@dataclass
86class LoadGroup:
87 """Checkpoint tensors converted together, and the transform converting them."""
89 first_target_name: str
90 transform: WeightRenaming | WeightConverter
93@dataclass(frozen=True)
94class _TensorShape:
95 """Shape of a model tensor, as shape-aware conversion operations ask for it."""
97 shape: torch.Size
100class SourceModelView:
101 """Expose pre-replacement parameter shapes to Transformers conversion ops."""
103 def __init__(self, model: nn.Module, shapes: dict[str, tuple[int, ...]]) -> None:
104 """Build a lightweight model view from captured tensor shapes."""
105 self.config = getattr(model, "config", None)
106 self.base_model_prefix = getattr(model, "base_model_prefix", None)
107 self._targets = {
108 name: _TensorShape(torch.Size(shape)) for name, shape in shapes.items()
109 }
111 @property
112 def targets(self) -> dict[str, _TensorShape]:
113 """Shape of every pre-replacement tensor, by name."""
114 return self._targets
116 def get_parameter(self, name: str) -> _TensorShape:
117 """Return source parameter metadata used by shape-aware converters."""
118 try:
119 return self._targets[name]
120 except KeyError as exc:
121 raise AttributeError(f"source model has no parameter {name!r}") from exc
124@dataclass
125class ReplacementLoadGroup:
126 """A replacement conversion waiting for the normalized tensors it is routed."""
128 group: LoadGroup
129 expected: Counter[str]
130 received: Counter[str]
131 completed: bool = False
134def sorted_checkpoint_keys(keys: Iterable[str]) -> tuple[str, ...]:
135 """Checkpoint keys in natural order, experts 2 before 10, which is the order loads collect them in."""
136 return tuple(sorted(keys, key=dot_natural_key))
139def _index_single_file(file_path: Path) -> CheckpointIndex:
140 """Index every tensor of one safetensors file."""
141 with safe_open(str(file_path), framework="pt", device="cpu") as checkpoint:
142 files_by_key = {key: file_path for key in checkpoint.keys()}
143 return CheckpointIndex(files_by_key)
146def _index_sharded_checkpoint(directory: Path, index_path: Path) -> CheckpointIndex:
147 """Index tensors described by a sharded safetensors index file."""
148 try:
149 index_data = json.loads(index_path.read_text(encoding="utf-8"))
150 except (OSError, json.JSONDecodeError) as exc:
151 raise ValueError(f"Failed to read safetensors index {index_path}: {exc}") from exc
152 weight_map = index_data.get("weight_map")
153 if not isinstance(weight_map, dict) or not weight_map:
154 raise ValueError(f"Safetensors index has no non-empty weight_map: {index_path}")
156 files_by_key = {}
157 for key, relative_path in weight_map.items():
158 file_path = directory / relative_path
159 if not file_path.is_file():
160 raise ValueError(f"Safetensors shard for {key} does not exist: {file_path}")
161 files_by_key[key] = file_path
162 return CheckpointIndex(files_by_key)
165def resolve_checkpoint_location(pretrained_path: str) -> Path:
166 """
167 Resolve a pretrained path into a local safetensors file or checkpoint directory.
169 Args:
170 pretrained_path (str): A ``.safetensors`` file, a checkpoint directory, or a Hub repository id,
171 which is downloaded first.
173 Returns:
174 Path: The file or the directory.
176 Raises:
177 ValueError: If the path is a file of another kind.
178 """
179 path = Path(pretrained_path).expanduser()
180 if path.is_file():
181 if path.suffix != ".safetensors":
182 raise ValueError(f"MVP only supports safetensors checkpoints, got: {path}")
183 return path
184 if path.is_dir():
185 return path
186 return Path(
187 snapshot_download(
188 repo_id=pretrained_path,
189 allow_patterns=list(_SNAPSHOT_PATTERNS),
190 )
191 )
194def resolve_checkpoint_index(pretrained_path: str) -> CheckpointIndex:
195 """Resolve a local or Hub checkpoint into a tensor-to-file index."""
196 location = resolve_checkpoint_location(pretrained_path)
197 if location.is_file():
198 return _index_single_file(location)
200 for index_name in (SAFE_WEIGHTS_INDEX_NAME, DIFFUSERS_SAFE_WEIGHTS_INDEX_NAME):
201 index_path = location / index_name
202 if index_path.is_file():
203 return _index_sharded_checkpoint(location, index_path)
205 for weights_name in (SAFE_WEIGHTS_NAME, DIFFUSERS_SAFE_WEIGHTS_NAME):
206 single_file = location / weights_name
207 if single_file.is_file():
208 return _index_single_file(single_file)
209 raise ValueError(
210 "MVP requires model.safetensors, model.safetensors.index.json, "
211 "diffusion_pytorch_model.safetensors, or "
212 "diffusion_pytorch_model.safetensors.index.json under "
213 f"{location}"
214 )
217def join_fqn(module_name: str, tensor_name: str) -> str:
218 """Name of a tensor registered on the module named ``module_name``."""
219 return f"{module_name}.{tensor_name}" if module_name else tensor_name
222def build_load_targets(model: nn.Module) -> dict[str, torch.Tensor]:
223 """Collect persistent parameters and buffers owned by the model."""
224 targets = {}
225 # Direct module registries preserve tied aliases and let us exclude
226 # non-persistent buffers without materializing an FSDP state_dict.
227 for module_name, module in model.named_modules(remove_duplicate=False):
228 for tensor_name, parameter in module._parameters.items(): # pylint: disable=W0212
229 if parameter is not None:
230 targets[join_fqn(module_name, tensor_name)] = parameter
231 non_persistent = module._non_persistent_buffers_set # pylint: disable=W0212
232 for tensor_name, buffer in module._buffers.items(): # pylint: disable=W0212
233 if buffer is not None and tensor_name not in non_persistent:
234 targets[join_fqn(module_name, tensor_name)] = buffer
235 return targets
238def checkpoint_logical_shapes(model: nn.Module) -> dict[str, tuple[int, ...]]:
239 """Collect model-declared logical parameter shapes for trailing padding on any dimensions.
241 Modules may expose ``checkpoint_logical_shapes()`` returning logical shapes
242 keyed by parameter names relative to that module. Undeclared parameters keep
243 the normal strict checkpoint shape checks.
245 Args:
246 model: Model whose modules declare logical checkpoint shapes.
248 Returns:
249 Logical shapes keyed by fully qualified model parameter names.
250 """
251 shapes = {}
252 for module_name, module in model.named_modules():
253 provider = getattr(module, "checkpoint_logical_shapes", None)
254 if not callable(provider):
255 continue
256 declared = provider()
257 if not isinstance(declared, dict):
258 raise ValueError(f"Invalid checkpoint padding declaration on {module_name}")
259 for parameter_name, shape in declared.items():
260 parameter = module.get_parameter(parameter_name)
261 if (not isinstance(shape, tuple) or len(shape) != parameter.ndim
262 or any(not isinstance(size, int) or isinstance(size, bool) or size < 0 for size in shape)):
263 raise ValueError(f"Invalid logical checkpoint shape on {module_name}: {shape}")
264 name = join_fqn(module_name, parameter_name)
265 if name in shapes and shapes[name] != shape:
266 raise ValueError(f"Conflicting logical checkpoint shapes for {name}")
267 shapes[name] = shape
268 return shapes
271def checkpoint_padding_boxes(
272 logical_shape: tuple[int, ...], offsets: tuple[int, ...], sizes: tuple[int, ...],
273) -> list[tuple[tuple[int, ...], tuple[int, ...]]]:
274 """Partition a local shard's trailing padding into disjoint local boxes.
276 Args:
277 logical_shape: Unpadded global checkpoint dimensions.
278 offsets: Global origin of this rank's rectangular shard.
279 sizes: Dimensions of this rank's local shard.
281 Returns:
282 Local offsets and dimensions of non-overlapping padding boxes.
283 """
284 if len(logical_shape) != len(offsets) or len(offsets) != len(sizes):
285 raise ValueError("Logical shape and local shard must have the same number of dimensions")
286 valid = tuple(max(0, min(size, logical - offset))
287 for logical, offset, size in zip(logical_shape, offsets, sizes))
288 boxes = []
289 for axis, (length, size) in enumerate(zip(valid, sizes)):
290 lengths = valid[:axis] + (size - length,) + sizes[axis + 1:]
291 if all(lengths):
292 starts = (0,) * axis + (length,) + (0,) * (len(sizes) - axis - 1)
293 boxes.append((starts, lengths))
294 return boxes
297def make_tensor_loader(index: CheckpointIndex, source_key: str) -> Callable[[], torch.Tensor]:
298 """A loader reading one checkpoint tensor when a conversion asks for it."""
299 return lambda: index.load_tensor(source_key)
302def _scoped_candidates(candidates: Sequence[WeightConverter], target_name: str) -> list[WeightConverter]:
303 """The candidates scoped to a module that holds ``target_name``."""
304 return [
305 converter
306 for converter in candidates
307 if converter.scope_prefix is not None
308 and (
309 target_name == converter.scope_prefix
310 or target_name.startswith(f"{converter.scope_prefix}.")
311 )
312 ]
315def select_unique_converter(
316 source_pattern: str,
317 target_name: str,
318 candidates: Sequence[WeightConverter],
319) -> Optional[WeightConverter]:
320 """
321 Pick the converter a matched checkpoint key belongs to.
323 A converter scoped to a module holding the target wins when it is the only one. Otherwise the only
324 unscoped converter does.
326 Args:
327 source_pattern (str): The source pattern the key matched.
328 target_name (str): The model tensor the key was renamed to.
329 candidates (Sequence[WeightConverter]): Every converter with that source pattern.
331 Returns:
332 Optional[WeightConverter]: The converter, or None when neither rule picks exactly one.
333 """
334 del source_pattern
335 scoped_candidates = _scoped_candidates(candidates, target_name)
336 if len(scoped_candidates) == 1:
337 return scoped_candidates[0]
338 unscoped_candidates = [converter for converter in candidates if converter.scope_prefix is None]
339 return unscoped_candidates[0] if len(unscoped_candidates) == 1 else None
342def _split_transforms(
343 transforms: Sequence[Any],
344) -> tuple[list[WeightRenaming], list[WeightConverter], dict[str, list[WeightConverter]]]:
345 """Renamings, converters, and the converters by each of their source patterns."""
346 renamings = [transform for transform in transforms if isinstance(transform, WeightRenaming)]
347 converters = [transform for transform in transforms if isinstance(transform, WeightConverter)]
348 converters_by_pattern = defaultdict(list)
349 for converter in converters:
350 for pattern in converter.source_patterns:
351 converters_by_pattern[pattern].append(converter)
352 return renamings, converters, converters_by_pattern
355def build_load_groups(
356 model: Any,
357 source_keys: Iterable[str],
358 targets: dict[str, Any],
359 *,
360 weights_mapping: list[WeightRenaming | WeightConverter],
361 make_loader: Callable[[str], Any],
362 select_converter: ConverterSelector = select_unique_converter,
363) -> tuple[
364 tuple[LoadGroup, ...],
365 tuple[str, ...],
366 list[WeightRenaming | WeightConverter],
367]:
368 """
369 Build checkpoint conversion groups and report unmatched checkpoint keys.
371 Args:
372 model (Any): The model, or the view of it the keys are renamed against.
373 source_keys (Iterable[str]): Checkpoint keys, in the order their tensors are collected.
374 targets (dict[str, Any]): Model tensors by name.
375 weights_mapping (list[WeightRenaming | WeightConverter]): Rules renaming and converting keys.
376 make_loader (Callable[[str], Any]): Called with a key, returns what the group collects for it.
377 select_converter (ConverterSelector): Picks the converter of a matched key.
378 Default :func:`select_unique_converter`.
380 Returns:
381 tuple: The groups in order of their first key, the keys renamed to no target, and the mapping.
382 """
383 unsupported = [
384 transform
385 for transform in weights_mapping
386 if not isinstance(transform, (WeightRenaming, WeightConverter))
387 ]
388 if unsupported:
389 names = ", ".join(type(transform).__name__ for transform in unsupported)
390 raise ValueError(f"Unsupported Transformers weight transforms in MVP: {names}")
392 renamings, converters, converters_by_pattern = _split_transforms(weights_mapping)
393 groups: OrderedDict[str, LoadGroup] = OrderedDict()
394 unexpected_keys = []
395 base_model_prefix = getattr(model, "base_model_prefix", None)
397 for source_key in source_keys:
398 target_name, source_pattern = rename_source_key(
399 source_key,
400 renamings,
401 converters,
402 base_model_prefix=base_model_prefix,
403 meta_state_dict=targets,
404 )
405 if target_name not in targets and source_key in targets:
406 target_name, source_pattern = rename_source_key(
407 source_key,
408 [],
409 [],
410 base_model_prefix=base_model_prefix,
411 meta_state_dict=targets,
412 )
413 if target_name not in targets:
414 unexpected_keys.append(source_key)
415 continue
417 if source_pattern is None:
418 source_pattern = source_key
419 transform = WeightRenaming(source_patterns=source_key, target_patterns=target_name)
420 else:
421 converter = select_converter(
422 source_pattern, target_name, converters_by_pattern.get(source_pattern, [])
423 )
424 if converter is None:
425 raise ValueError(
426 "No unique WeightConverter found for matched source pattern "
427 f"{source_pattern!r} and target {target_name!r}"
428 )
429 transform = deepcopy(converter)
431 group = groups.setdefault(
432 target_name,
433 LoadGroup(first_target_name=target_name, transform=transform),
434 )
435 group.transform.add_tensor(target_name, source_key, source_pattern, make_loader(source_key))
437 return tuple(groups.values()), tuple(unexpected_keys), weights_mapping
440def build_replacement_routes(
441 model: nn.Module,
442 source_names: tuple[str, ...],
443 targets: dict[str, torch.Tensor],
444 transforms: list[WeightRenaming | WeightConverter],
445) -> dict[str, tuple[ReplacementLoadGroup, str, str]]:
446 """Route normalized Transformers parameters into replacement converters."""
447 renamings, converters, converters_by_pattern = _split_transforms(deepcopy(transforms))
448 groups: OrderedDict[str, ReplacementLoadGroup] = OrderedDict()
449 routes = {}
450 base_model_prefix = getattr(model, "base_model_prefix", None)
451 for source_name in source_names:
452 target_name, source_pattern = rename_source_key(
453 source_name,
454 renamings,
455 converters,
456 base_model_prefix=base_model_prefix,
457 meta_state_dict=targets,
458 )
459 if source_pattern is None and target_name == source_name:
460 continue
461 if target_name not in targets:
462 continue
464 if source_pattern is None:
465 collected_pattern = source_name
466 transform: WeightRenaming | WeightConverter = WeightRenaming(
467 source_patterns=source_name,
468 target_patterns=target_name,
469 )
470 else:
471 collected_pattern = source_pattern
472 scoped_candidates = _scoped_candidates(converters_by_pattern.get(source_pattern, []), target_name)
473 if len(scoped_candidates) != 1:
474 raise ValueError(
475 "No unique replacement WeightConverter found for source "
476 f"{source_name!r} and target {target_name!r}"
477 )
478 transform = deepcopy(scoped_candidates[0])
480 state = groups.get(target_name)
481 if state is None:
482 state = ReplacementLoadGroup(
483 group=LoadGroup(target_name, transform),
484 expected=Counter(),
485 received=Counter(),
486 )
487 groups[target_name] = state
488 state.expected[collected_pattern] += 1
489 routes[source_name] = (state, target_name, collected_pattern)
490 return routes
493def base_weights_mapping(
494 weights_mapping: list[WeightRenaming | WeightConverter],
495 replacement_mapping: list[WeightRenaming | WeightConverter],
496) -> list[WeightRenaming | WeightConverter]:
497 """The rules of ``weights_mapping`` that are not replacement conversions."""
498 replacement_ids = {id(transform) for transform in replacement_mapping}
499 return [transform for transform in weights_mapping if id(transform) not in replacement_ids]
502def first_tensor(value: Any) -> Any:
503 """The tensor a conversion returned under one name, which a renaming returns in a list."""
504 return value[0] if isinstance(value, list) else value
507def convert_group(group: LoadGroup, model: Any) -> dict[str, Any]:
508 """
509 Convert all checkpoint tensors belonging to one load group.
511 Args:
512 group (LoadGroup): The group, its tensors already collected.
513 model (Any): The model, or the view of it, handed to the conversion operations.
515 Returns:
516 dict[str, Any]: Converted tensors by model tensor name.
518 Raises:
519 RuntimeError: If the conversion fails, naming the group.
520 """
521 try:
522 return group.transform.convert(
523 group.first_target_name,
524 model=model,
525 config=getattr(model, "config", None),
526 hf_quantizer=None,
527 loading_info=None,
528 )
529 except Exception as exc:
530 raise RuntimeError(
531 f"Failed to convert checkpoint tensors for {group.first_target_name}: {exc}"
532 ) from exc
535def local_target_tensor(target: torch.Tensor) -> torch.Tensor:
536 """The part of a model tensor held on this rank."""
537 return target.to_local() if isinstance(target, DTensor) else target
540def target_layout(target: torch.Tensor) -> Any:
541 """The layout a model tensor is sharded with, or None for a whole tensor."""
542 if isinstance(target, DTensor) and target.layout is not None:
543 return target.layout
544 return getattr(target, "_sharding_spec", None)
547def reject_partial_layout(target_name: str, layout: Any) -> None:
548 """Refuse a layout with a Partial placement, which pretrained loads do not support."""
549 if any(isinstance(placement, Partial) for placement in layout.placements):
550 raise ValueError(f"Partial placement is not supported for pretrained loading: {target_name}")
553def shard_for_target(target_name: str, full_tensor: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
554 """Shard a full checkpoint tensor according to its target layout."""
555 layout = target_layout(target)
556 if layout is None:
557 return full_tensor
558 reject_partial_layout(target_name, layout)
560 local_dtensor = distribute_tensor(
561 full_tensor,
562 layout.mesh,
563 layout.alias_placements,
564 src_data_rank=None,
565 )
566 return local_dtensor.to_local()
569def copy_into_target(
570 target_name: str, full_tensor: torch.Tensor, target: torch.Tensor,
571 logical_shape: tuple[int, ...] | None = None,
572) -> None:
573 """Copy a checkpoint tensor into its materialized local target."""
574 layout = target_layout(target)
575 target_shape = tuple(getattr(layout, "tensor_shape", None) or target.shape)
576 if logical_shape is not None and tuple(full_tensor.shape) == logical_shape and target_shape != logical_shape:
577 if (len(logical_shape) != len(target_shape)
578 or any(logical > physical for logical, physical in zip(logical_shape, target_shape))):
579 raise ValueError(f"Invalid checkpoint padding shape for {target_name}")
580 padded = full_tensor.new_zeros(target_shape)
581 padded[tuple(slice(0, size) for size in logical_shape)].copy_(full_tensor)
582 full_tensor = padded
583 local_tensor = shard_for_target(target_name, full_tensor, target)
584 destination = local_target_tensor(target)
585 if destination.is_meta:
586 raise ValueError(f"Target must be materialized before loading: {target_name}")
587 if tuple(local_tensor.shape) != tuple(destination.shape):
588 raise ValueError(
589 f"Local shape mismatch for {target_name}: checkpoint shard "
590 f"{tuple(local_tensor.shape)} vs target {tuple(destination.shape)}"
591 )
592 local_tensor = local_tensor.to(device=destination.device, dtype=destination.dtype)
593 with torch.no_grad():
594 destination.copy_(local_tensor)
595 target._is_hf_initialized = True # pylint: disable=W0212
598def alias_names_by_target(targets: dict[str, torch.Tensor]) -> dict[int, set[str]]:
599 """Every name each model tensor is registered under, by the identity of the tensor."""
600 aliases = defaultdict(set)
601 for target_name, target in targets.items():
602 aliases[id(target)].add(target_name)
603 return aliases
606def validate_load_result(
607 missing_keys: tuple[str, ...],
608 unexpected_keys: tuple[str, ...],
609 strict: bool,
610) -> None:
611 """Validate missing keys and report ignored checkpoint tensors."""
612 if strict and missing_keys:
613 preview = ", ".join(missing_keys[:10])
614 raise RuntimeError(
615 f"Checkpoint did not load {len(missing_keys)} owned model tensors; "
616 f"first keys: {preview}"
617 )
618 if unexpected_keys:
619 logger.warning(
620 "Ignored %d checkpoint tensors not owned by this model/rank; first keys: %s",
621 len(unexpected_keys),
622 ", ".join(unexpected_keys[:10]),
623 )