Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / compile / checkpoint_metadata.py: 89%
186 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"""Build and copy graph-mode shard metadata for checkpoint consumers.
17Graph sharding replaces ``param.data`` without creating a ``DTensor``, so the
18checkpoint and HF-export consumers need the final layout copied onto the
19tensors they read. This module owns both halves of that bridge:
21- ``attach_*_shard_metadata`` describe the live parameters (final FSDP storage,
22 or source TP/EP storage before the lazy compile) as one rectangular chunk.
23- ``annotate_*_state_dict`` copy that metadata onto the tensors a checkpoint or
24 HF export actually reads.
26The helpers stay inactive unless a graph compiler is attached to the trainer.
27"""
29from typing import Any, Dict, Optional, Tuple
31import torch
32import torch.distributed as dist
33from torch._prims_common import make_contiguous_strides_for
35from hyper_parallel.core.distributed_checkpoint.metadata import (
36 CHUNK_INFO,
37 ChunkInfo,
38 ChunkStorageMetadata,
39)
40from hyper_parallel.core.dtensor.layout import infer_slice_area_by_layout
41from hyper_parallel.core.dtensor.placement_types import StridedShard
44def _compiler_layouts(
45 trainer: Any, *, strict_strided: bool = True
46) -> Optional[Dict[Any, Any]]:
47 """Attach the applicable metadata and return the live parameter layouts.
49 A compiled compiler owns the final FSDP layouts. Before compilation the
50 model is still source-local (for example TP/EP), so annotate it with the
51 source layouts instead; checkpoint consumers then see the true global shape
52 even when the checkpoint is written or read before the first forward.
54 Args:
55 trainer: Trainer owning the graph compiler (if any).
56 strict_strided: Raise on a strided shard when describing final layouts.
57 Model export keeps it on because such a weight cannot be written
58 correctly; the optimizer path relaxes it so an unrelated strided
59 parameter does not block saving state that maps cleanly.
61 Returns:
62 The applicable parameter -> layout mapping, or None when the trainer has
63 no graph compiler or the compiler reports no layouts.
64 """
65 compiler = getattr(trainer, "graph_compiler", None)
66 if compiler is None:
67 return None
68 if compiler.is_compiled:
69 attach = getattr(compiler, "attach_shard_metadata", None)
70 layouts = getattr(compiler, "parameter_layouts", None)
71 else:
72 attach = getattr(compiler, "attach_source_shard_metadata", None)
73 layouts = getattr(compiler, "source_parameter_layouts", None)
74 if callable(attach):
75 if compiler.is_compiled:
76 attach(strict_strided=strict_strided)
77 else:
78 attach()
79 return layouts or None
82def _layouts_by_name(
83 layouts: Dict[Any, Any], model: torch.nn.Module
84) -> Dict[str, Tuple[Any, Any]]:
85 """Return graph layouts keyed by model parameter FQN.
87 Aliases are kept (``remove_duplicate=False``) so a tied parameter's other
88 state-dict keys map to the same layout as its canonical name; deduplicating
89 here would leave those keys unannotated and exported as local shards.
90 """
91 return {
92 name: (parameter, layouts[parameter])
93 for name, parameter in model.named_parameters(remove_duplicate=False)
94 if parameter in layouts
95 }
98def _copy_shard_metadata(source: Any, target: Any) -> None:
99 """Copy the live parameter's final layout onto a checkpoint tensor."""
100 spec = getattr(source, "_sharding_spec", None)
101 if spec is None or not isinstance(target, torch.Tensor):
102 return
103 setattr(target, "_sharding_spec", spec)
104 setattr(target, "_layout", getattr(source, "_layout", spec))
105 placements = getattr(source, "_placements", None)
106 if placements is None:
107 placements = tuple(spec.placements or ())
108 setattr(target, "_placements", placements)
109 chunk_info = getattr(source, CHUNK_INFO, None)
110 if chunk_info is not None:
111 setattr(target, CHUNK_INFO, chunk_info)
114def _is_sharded_layout(layout: Any, parameter: Any) -> bool:
115 """Whether ``layout`` describes a tensor larger than the local parameter."""
116 tensor_shape = tuple(getattr(layout, "tensor_shape", None) or ())
117 return bool(tensor_shape) and tensor_shape != tuple(parameter.shape)
120def _reject_unmappable_optimizer_slot(
121 name: str, parameter: Any, layout: Any, slots: Any
122) -> None:
123 """Fail loudly when sharded state has no attachable rectangular metadata.
125 A strided/off-axis shard is skipped by ``attach_shard_metadata`` (no
126 ``_sharding_spec``) because it has no single rectangular chunk. If such a
127 parameter still owns dense state shaped like its local shard, silently
128 exporting it would write a corrupt checkpoint, so reject it explicitly.
129 """
130 if getattr(parameter, "_sharding_spec", None) is not None:
131 return
132 if not _is_sharded_layout(layout, parameter):
133 return
134 local_shape = tuple(parameter.shape)
135 if not any(
136 isinstance(value, torch.Tensor) and tuple(value.shape) == local_shape
137 for value in slots
138 ):
139 return
140 raise RuntimeError(
141 f"Cannot export optimizer state for {name!r}: its FSDP shard has no "
142 "single rectangular chunk (for example a strided or off-axis shard), "
143 "so the state cannot be written correctly. Save with a layout that "
144 "shards one contiguous dim-0 block, or exclude this optimizer state."
145 )
148def annotate_model_state_dict(trainer: Any, state_dict: Dict[str, Any]) -> None:
149 """Attach graph shard metadata so HF export and DCP see global tensors.
151 Args:
152 trainer: Trainer owning the graph compiler (if any).
153 state_dict: Model state dictionary to annotate in place.
154 """
155 layouts = _compiler_layouts(trainer, strict_strided=True)
156 if not layouts:
157 return
158 by_name = _layouts_by_name(layouts, trainer.model)
159 for name, value in state_dict.items():
160 entry = by_name.get(name)
161 if entry is not None:
162 _copy_shard_metadata(entry[0], value)
165def annotate_optimizer_state_dict(trainer: Any, payload: Any) -> Any:
166 """Attach graph shard metadata to dense optimizer-state tensors.
168 Unrelated strided parameters are skipped here instead of aborting the save:
169 only a strided parameter that actually owns dense state raises, because that
170 state cannot be mapped onto one rectangular chunk.
172 Args:
173 trainer: Trainer owning the graph compiler (if any).
174 payload: Nested optimizer state dictionary to annotate in place.
176 Returns:
177 The same ``payload`` object, annotated where a layout applies.
178 """
179 layouts = _compiler_layouts(trainer, strict_strided=False)
180 if not layouts:
181 return payload
182 by_name = _layouts_by_name(layouts, trainer.model)
184 def annotate_slot(slot: torch.Tensor, name: str, entry: Tuple[Any, Any]) -> None:
185 """Annotate one state tensor that is shaped like its local parameter.
187 Args:
188 slot: Optimizer-state tensor for one slot.
189 name: Canonical parameter FQN the slot belongs to.
190 entry: ``(parameter, layout)`` pair from the live model.
191 """
192 parameter, layout = entry
193 if tuple(slot.shape) != tuple(parameter.shape):
194 return
195 _reject_unmappable_optimizer_slot(name, parameter, layout, (slot,))
196 _copy_shard_metadata(parameter, slot)
198 def apply_state(state: Dict[Any, Any], name: str, entry: Tuple[Any, Any]) -> None:
199 """Copy metadata onto every slot shaped like the local parameter.
201 Args:
202 state: One parameter's optimizer-state slot mapping.
203 name: Canonical parameter FQN the slots belong to.
204 entry: ``(parameter, layout)`` pair from the live model.
205 """
206 parameter, layout = entry
207 _reject_unmappable_optimizer_slot(name, parameter, layout, state.values())
208 local_shape = tuple(parameter.shape)
209 for value in state.values():
210 if isinstance(value, torch.Tensor) and tuple(value.shape) == local_shape:
211 _copy_shard_metadata(parameter, value)
213 def visit(value: Any) -> None:
214 """Walk nested optimizer state and annotate matching entries.
216 Args:
217 value: Current node in the nested optimizer-state payload.
218 """
219 if isinstance(value, dict):
220 for key, item in value.items():
221 entry = by_name.get(key) if isinstance(key, str) else None
222 if entry is not None and isinstance(item, dict):
223 apply_state(item, key, entry)
224 continue
225 if isinstance(key, str) and key.startswith("state."):
226 # Flattened format is ``state.<FQN>.<slot>``; split on the
227 # last dot instead of scanning every parameter name.
228 fqn, sep, _ = key[len("state.") :].rpartition(".")
229 entry = by_name.get(fqn) if sep else None
230 if entry is not None and isinstance(item, torch.Tensor):
231 annotate_slot(item, fqn, entry)
232 continue
233 visit(item)
234 elif isinstance(value, (list, tuple)):
235 for item in value:
236 visit(item)
238 visit(payload)
239 return payload
242def canonical_parameter_names(model: torch.nn.Module) -> Dict[Any, str]:
243 """Map each live parameter to the canonical FQN used for shard metadata.
245 ``_parameter_shapes``, ``fsdp_padded_params`` and the tracer's state FQNs all
246 come from the deduplicated ``named_parameters()``, so a tied parameter
247 resolves to its first name. Resolving the same way here keeps tied
248 parameters aligned with the pass metadata instead of picking up a later
249 alias that has no recorded shape or padding entry.
250 """
251 return {parameter: name for name, parameter in model.named_parameters()}
254def has_strided_placement(layout: Any) -> bool:
255 """Whether any axis uses a strided shard (interleaved, not rectangular)."""
256 return any(
257 isinstance(placement, StridedShard) for placement in (layout.placements or ())
258 )
261def trim_padded_dim0(
262 global_shape: Tuple[int, ...], n: int, n_pad: int
263) -> Optional[Tuple[int, ...]]:
264 """Replace the padded FSDP dim 0 with the parameter's true global size."""
265 if n_pad <= 0 or not global_shape or global_shape[0] % n_pad:
266 return None
267 true_dim0 = n * (global_shape[0] // n_pad)
268 if true_dim0 == global_shape[0]:
269 return None
270 return (true_dim0, *global_shape[1:])
273def shard_chunk_metadata(
274 layout: Any,
275 rank_index: int,
276 global_shape: Tuple[int, ...],
277 padded_entry: Optional[Tuple[int, int]] = None,
278) -> Tuple[Tuple[int, ...], ChunkStorageMetadata]:
279 """Describe one rank's chunk, clipped to the parameter's true global extent.
281 The offsets follow the padded geometry the live parameter is physically
282 stored in. A pad-sharded parameter reports the true (unpadded) global shape
283 and clips its chunk to it, so the metadata never claims rows past the real
284 tensor while staying aligned with the local storage.
285 """
286 area = infer_slice_area_by_layout(layout, rank_index, global_shape)
287 offsets = tuple(begin for begin, _ in area)
288 sizes = tuple(end - begin for begin, end in area)
289 if padded_entry is not None:
290 trimmed = trim_padded_dim0(global_shape, *padded_entry)
291 if trimmed is not None:
292 global_shape = trimmed
293 clamped_offsets = []
294 clamped_sizes = []
295 for size, extent, offset in zip(sizes, global_shape, offsets):
296 # Keep the padded offset geometry but never let a chunk start
297 # or end past the true extent. A rank that owns only padding
298 # rows collapses to a zero-size chunk at the boundary.
299 start = min(offset, extent)
300 end = min(offset + size, extent)
301 clamped_offsets.append(start)
302 clamped_sizes.append(max(0, end - start))
303 offsets = tuple(clamped_offsets)
304 sizes = tuple(clamped_sizes)
305 return global_shape, ChunkStorageMetadata(offsets=offsets, sizes=sizes)
308def _set_shard_metadata(
309 parameter: torch.nn.Parameter,
310 layout: Any,
311 chunk: ChunkStorageMetadata,
312 global_shape: Tuple[int, ...],
313) -> None:
314 """Attach one parameter's layout and chunk description.
316 ``_sharding_spec`` aliases are only set for layouts that actually shard a
317 tensor dim, matching the eager path so consumers do not wrap a replicated
318 parameter in a sharded DTensor.
319 """
320 placements = tuple(layout.placements or ())
321 if any(placement.is_shard() for placement in placements):
322 setattr(parameter, "_sharding_spec", layout)
323 setattr(parameter, "_layout", layout)
324 setattr(parameter, "_placements", placements)
325 setattr(
326 parameter,
327 CHUNK_INFO,
328 ChunkInfo(chunk=chunk, global_shape=global_shape),
329 )
332def attach_shard_metadata(compiler: Any, *, strict_strided: bool = True) -> None:
333 """Annotate graph-sharded parameters for HF export and DCP consumers.
335 Called by checkpoint/export paths after compilation; keeping it out of
336 ``compile`` avoids building layouts for callers that never checkpoint.
338 Args:
339 compiler: Compiled graph compiler owning the sharded live model.
340 strict_strided: Raise on a strided FSDP shard (export cannot describe
341 it). Optimizer resharding passes False so an unrelated strided
342 parameter does not block resharding of parameters that do have
343 optimizer state.
344 """
345 if compiler.joint_graph is None:
346 return
347 layouts = compiler.parameter_layouts
348 if not layouts:
349 return
350 rank = dist.get_rank() if dist.is_available() and dist.is_initialized() else 0
351 names = canonical_parameter_names(compiler.model)
352 padded = getattr(compiler.joint_graph.graph_module, "fsdp_padded_params", {})
353 for parameter, layout in layouts.items():
354 global_shape = tuple(layout.tensor_shape or ())
355 if not global_shape:
356 continue
357 if has_strided_placement(layout):
358 if strict_strided:
359 raise RuntimeError(
360 f"Cannot describe checkpoint metadata for {names.get(parameter)!r}: "
361 "its FSDP shard is strided (for example TP and FSDP shard the same "
362 "axis), so the local shard is not a single rectangular chunk. "
363 "Checkpoint export and optimizer-state resharding of strided "
364 "shards are not supported yet."
365 )
366 continue
367 rank_list = tuple(layout.rank_list)
368 if rank not in rank_list:
369 continue
370 global_shape, chunk = shard_chunk_metadata(
371 layout,
372 rank_list.index(rank),
373 global_shape,
374 padded.get(names.get(parameter)),
375 )
376 _set_shard_metadata(parameter, layout, chunk, global_shape)
379def attach_source_shard_metadata(compiler: Any) -> None:
380 """Annotate source-local parameters for pre-compile checkpoint load/save.
382 Restore happens before lazy compilation, when TP/EP parameters are still
383 plain local tensors. Without this, DCP would treat every rank as the first
384 source shard and reject a global checkpoint whose size differs from the
385 local shape.
386 """
387 if compiler.joint_graph is not None:
388 return
389 layouts = compiler.source_parameter_layouts
390 if not layouts:
391 return
392 rank = dist.get_rank() if dist.is_available() and dist.is_initialized() else 0
393 for parameter, layout in layouts.items():
394 global_shape = tuple(layout.tensor_shape or ())
395 if not global_shape or has_strided_placement(layout):
396 continue
397 rank_list = tuple(layout.rank_list)
398 if rank not in rank_list:
399 continue
400 _, chunk = shard_chunk_metadata(layout, rank_list.index(rank), global_shape)
401 _set_shard_metadata(parameter, layout, chunk, global_shape)
404def build_source_parameter_layouts(compiler: Any, parameters: dict) -> Optional[dict]:
405 """Describe source TP/EP storage before FSDP shards the live model."""
406 if compiler.source_shard_info is None and compiler.mesh_context is None:
407 return None
408 compiler.ensure_expert_param_names()
409 layouts = {}
410 for name, parameter in parameters.items():
411 layout = compiler.source_global_layout(name, len(parameter.shape))
412 if layout is None:
413 continue
414 placements = tuple(layout.placements or ())
415 if not placements or not any(placement.is_shard() for placement in placements):
416 continue
417 if any(isinstance(placement, StridedShard) for placement in placements):
418 raise RuntimeError(
419 f"Cannot describe checkpoint metadata for {name!r}: its source "
420 "TP/EP shard is strided and cannot be represented as one "
421 "rectangular chunk."
422 )
423 global_shape = layout.get_global_shape(tuple(parameter.shape))
424 layout.set_tensor_meta(
425 tuple(global_shape),
426 make_contiguous_strides_for(global_shape),
427 parameter.dtype,
428 )
429 layouts[parameter] = layout
430 return layouts or None