Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / distributed / _builder / fsdp_adapter.py: 82%
417 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"""fsdp_adapter: FSDP2 construction-time adapter (05 §15.2.4).
17Wrap policy, mesh/policy construction, ``fully_shard`` application and
18prefetch configuration all happen at model-construction time (not in the
19Trainer step runtime); ``FSDP2Manager`` / ``_instantiate_fsdp2`` and the
20``parallelize`` signature are unchanged. The source-layout discovery logic
21(FQN/DTensor source-shard resolution) merged into
22``distributed/_builder/source_shard.py`` (05 row 406).
23"""
25from __future__ import annotations
27import fnmatch
28import logging
29from collections import defaultdict
30from collections.abc import Mapping, Sequence
31from dataclasses import dataclass
32from typing import TYPE_CHECKING, Any
34import torch
35from torch.nn import Module as ModuleClass
36from torch.nn import Parameter as ParameterClass
38from hyper_parallel.components.modules.module_family import collect_family_modules
39import hyper_parallel.core.fully_shard.utils as fully_shard_utils
40from hyper_parallel import DeviceMesh, HSDPModule, fully_shard
41from hyper_parallel.core.fully_shard.hsdp_utils import get_managed_modules_parameters
42from hyper_parallel.distributed._builder.source_shard import (
43 SourceShardInfoByFQN, # pylint: disable=unused-import
44 SourceShardInfoByParam, # pylint: disable=unused-import
45 _build_managed_source_shard_info,
46 _build_source_shard_info_by_param,
47 _source_infos_for_fully_shard,
48)
49from hyper_parallel.models.build_options import FSDP2Config
50from hyper_parallel.models.registry import get_model_adapter
52if TYPE_CHECKING:
53 from hyper_parallel.distributed.mesh import (
54 MeshContext,
55 )
57logger = logging.getLogger(__name__)
60@dataclass(frozen=True)
61class _WrapModuleInfo:
62 """One FSDP child unit selected by automatic or adapter policy."""
64 fqn: str
65 module: ModuleClass
68def _is_expert_source_mesh(mesh: DeviceMesh | None) -> bool:
69 """Whether a source mesh carries the expert (EP) axis."""
70 return mesh is not None and "ep" in (getattr(mesh, "mesh_dim_names", None) or ())
73def _get_checkpoint_wrapped_module(module: ModuleClass) -> ModuleClass | None:
74 """Return the module directly wrapped by a supported checkpoint wrapper."""
75 for attr_name in ("_wrapped_module", "_checkpoint_wrapped_module"):
76 wrapped_module = getattr(module, attr_name, None)
77 if isinstance(wrapped_module, ModuleClass):
78 return wrapped_module
79 return None
82def _declared_expert_unit_fqns(model, expert_parameters):
83 """Find family/native execution units by identity rather than an experts path suffix."""
84 expert_module_fqns = set()
85 for boundary in collect_family_modules(model):
86 parameters = set(boundary.module.parameters())
87 if parameters and parameters <= expert_parameters:
88 expert_module_fqns.add(boundary.fqns[0])
89 for fqn, module in model.named_modules():
90 binding = getattr(module, "_hp_parallel_binding", None)
91 if binding is not None and binding.ep_context is not None:
92 expert_module_fqns.add(fqn)
93 expert_module_fqns.discard("")
94 return expert_module_fqns
97class FSDP2Manager:
98 """Configure and apply nested FSDP2 wrapping for a dual-mode model."""
100 def __init__(
101 self,
102 config: FSDP2Config,
103 mesh_context: MeshContext,
104 fp32_main_params: bool = False,
105 ) -> None:
106 """Initialize the manager from resolved YAML config and runtime mesh.
108 Args:
109 config: Resolved top-level ``fsdp_config``.
110 mesh_context: Runtime topology containing the shared world mesh.
111 fp32_main_params: Whether FSDP writes reduced gradients to
112 ``main_grad`` for the fp32 main-parameter optimizer wrapper.
113 """
114 self.config = config
115 self.mesh_context = mesh_context
116 self.fp32_main_params = fp32_main_params
117 self._mp_policy: fully_shard_utils.MixedPrecisionPolicy | None = None
120 def _resolve_replicate_params(
121 self,
122 model: ModuleClass,
123 ) -> set[ParameterClass] | None:
124 """Resolve configured replicate-parameter FQNs on the final model."""
125 if not self.config.replicate_params:
126 return None
128 parameters_by_fqn = dict(model.named_parameters(remove_duplicate=False))
129 replicate_params = set()
130 for parameter_fqn in self.config.replicate_params:
131 parameter = parameters_by_fqn.get(parameter_fqn)
132 if parameter is None:
133 raise ValueError(
134 "replicate_params contains unknown parameter FQN: "
135 f"{parameter_fqn}"
136 )
137 replicate_params.add(parameter)
138 return replicate_params
140 def _build_expert_fsdp_mesh(self) -> DeviceMesh:
141 """Select the expert FSDP child mesh."""
142 expert_mesh = self.mesh_context.fsdp_moe_mesh
143 if expert_mesh is None:
144 raise ValueError("Expert FSDP units require MeshContext.fsdp_moe_mesh")
145 if "edp_replicate" in (expert_mesh.mesh_dim_names or ()):
146 return expert_mesh[("edp_replicate", "edp_shard")]
147 return expert_mesh["edp_shard"]
149 def _build_dense_fsdp_mesh(self) -> DeviceMesh | None:
150 """Select the prebuilt dense FSDP child mesh when available."""
151 dense_mesh = self.mesh_context.fsdp_non_moe_mesh
152 if dense_mesh is None:
153 return None
154 if self.mesh_context.dp_replicate_size > 1:
155 return dense_mesh[("fsdp_replicate", "fsdp_shard")]
156 return dense_mesh["fsdp_shard"]
158 def _build_compatibility_fsdp_mesh(self) -> DeviceMesh:
159 """Build an FSDP mesh from the combined world mesh."""
160 world_mesh = self.mesh_context.device_mesh
161 if world_mesh is None:
162 raise ValueError("FSDP2 requires MeshContext.fsdp_non_moe_mesh")
163 mesh_dim_names = world_mesh.mesh_dim_names
164 if mesh_dim_names is None:
165 raise ValueError("FSDP2 requires named DeviceMesh dimensions")
166 shard_dim_names = tuple(
167 dim_name for dim_name in ("dp_shard", "cp") if dim_name in mesh_dim_names
168 )
169 if not shard_dim_names:
170 raise ValueError("FSDP2 requires a dp_shard or cp dimension in the world mesh")
171 shard_mesh = (
172 world_mesh[shard_dim_names[0]]
173 if len(shard_dim_names) == 1
174 else world_mesh[shard_dim_names].flatten("fsdp_shard")
175 )
176 if "dp_replicate" not in mesh_dim_names:
177 return shard_mesh
178 return DeviceMesh.concatenate([world_mesh["dp_replicate"], shard_mesh])
180 def _build_fsdp_actual_mesh(self, expert: bool = False) -> DeviceMesh:
181 """Select the prebuilt dense or expert FSDP child mesh."""
182 if expert:
183 return self._build_expert_fsdp_mesh()
184 dense_mesh = self._build_dense_fsdp_mesh()
185 if dense_mesh is not None:
186 return dense_mesh
187 return self._build_compatibility_fsdp_mesh()
189 def parameter_mesh_bindings(
190 self, model: ModuleClass, source_shard_info: SourceShardInfoByFQN | None,
191 ignored_params: set[ParameterClass] | None = None,
192 ) -> dict[ParameterClass, DeviceMesh]:
193 """Resolve unit-owned parameter meshes without installing FSDP hooks.
195 Args:
196 model: Final model before graph capture or eager wrapping.
197 source_shard_info: The planner's non-FSDP parameter placements.
198 ignored_params: Parameters managed outside FSDP.
200 The same managed-parameter selector runs inside-out in both paths.
201 Claimed identities model the initialized inner units, including tied
202 aliases; nearest-parent ownership alone would not match fully_shard.
203 """
204 metadata = _build_source_shard_info_by_param(self, model, source_shard_info)
205 units = self._find_wrap_modules(model, metadata)
206 units = [unit.module for unit in sorted(units, key=lambda unit: unit.fqn.count("."), reverse=True)]
207 claimed = set(ignored_params or ())
208 bindings = {}
209 for owner in [*units, model]:
210 parameters = get_managed_modules_parameters((owner,), claimed)
211 source = _build_managed_source_shard_info(self, owner, metadata, claimed)
212 expert = self._uses_expert_mesh(source)
213 if owner is model and expert:
214 raise ValueError("Routed expert parameters must belong to a nested experts FSDP unit")
215 mesh = self._build_fsdp_actual_mesh(expert)
216 bindings.update(dict.fromkeys(parameters, mesh))
217 claimed.update(parameters)
218 return bindings
220 def mixed_precision_bindings(
221 self, model: ModuleClass, source_shard_info: SourceShardInfoByFQN | None,
222 ) -> tuple[fully_shard_utils.MixedPrecisionPolicy, tuple[ModuleClass, ...]]:
223 """Return the eager dtype policy and its module boundaries without installing hooks."""
224 metadata = _build_source_shard_info_by_param(self, model, source_shard_info)
225 units = self._find_wrap_modules(model, metadata)
226 modules = tuple(dict.fromkeys([model, *(unit.module for unit in units)]))
227 return self._resolve_model_precision_policy(model), modules
229 def _resolve_model_precision_policy(self, model: ModuleClass) -> fully_shard_utils.MixedPrecisionPolicy:
230 """Bind overrides before parameter identities can change."""
231 custom = None
232 if self.config.mix_precision.custom_params:
233 custom = self._resolve_custom_params(dict(model.named_parameters(remove_duplicate=False)))
234 return self._build_mixed_precision_policy(custom)
236 def _resolve_custom_params(
237 self, parameters_by_fqn: Mapping[str, ParameterClass]
238 ) -> dict[ParameterClass, dict[str, Any]]:
239 """Resolve configured names and patterns against the supplied parameter mapping."""
240 custom_params = {}
241 for parameter_fqn, custom_dtypes in self.config.mix_precision.custom_params.items():
242 matched_fqns = [parameter_fqn] if parameter_fqn in parameters_by_fqn else [
243 fqn for fqn in parameters_by_fqn if fnmatch.fnmatchcase(fqn, parameter_fqn)
244 ]
245 if not matched_fqns:
246 raise ValueError(f"mix_precision.custom_params matches no parameter: {parameter_fqn}")
247 for matched_fqn in matched_fqns:
248 parameter = parameters_by_fqn[matched_fqn]
249 if parameter in custom_params and custom_params[parameter] != custom_dtypes:
250 raise ValueError(f"mix_precision.custom_params has conflicting overrides for {matched_fqn}")
251 custom_params[parameter] = dict(custom_dtypes)
252 return custom_params
254 def _build_mixed_precision_policy(
255 self, custom_params: Mapping[ParameterClass, Mapping[str, Any]] | None = None
256 ) -> fully_shard_utils.MixedPrecisionPolicy:
257 """Build or reuse the shared precision policy for the current model."""
258 if custom_params is None and self._mp_policy is not None:
259 return self._mp_policy
260 mix_precision = self.config.mix_precision
261 dtype_by_name = {
262 None: None,
263 "bfloat16": torch.bfloat16,
264 "float16": torch.float16,
265 "float32": torch.float32,
266 }
267 custom_dtype_overrides = {}
268 for parameter, custom_dtypes in (custom_params or {}).items():
269 resolved_dtypes = {}
270 for policy_field, dtype_name in custom_dtypes.items():
271 if dtype_name not in dtype_by_name:
272 raise ValueError(f"Unsupported mix_precision.custom_params dtype: {dtype_name!r}")
273 resolved_dtypes[policy_field] = dtype_by_name[dtype_name]
274 custom_dtype_overrides[parameter] = resolved_dtypes
275 self._mp_policy = fully_shard_utils.MixedPrecisionPolicy(
276 param_dtype=dtype_by_name[mix_precision.param_dtype],
277 reduce_dtype=dtype_by_name[mix_precision.reduce_dtype],
278 output_dtype=dtype_by_name[mix_precision.output_dtype],
279 cast_forward_inputs=mix_precision.cast_forward_inputs,
280 apply_grad_on_fp32_main_grad=self.fp32_main_params,
281 custom_params=custom_dtype_overrides or None,
282 )
283 return self._mp_policy
285 def _build_offload_policy(self) -> fully_shard_utils.OffloadPolicy:
286 """Return CPU offload when enabled, otherwise the default no-offload policy."""
287 if not self.config.enable_offload:
288 return fully_shard_utils.OffloadPolicy()
289 return fully_shard_utils.CPUOffloadPolicy()
291 def _build_fully_shard_kwargs(
292 self,
293 fsdp_mesh: DeviceMesh,
294 ) -> tuple[dict[str, Any], dict[str, Any]]:
295 """Build child and root kwargs with the same configured reshard policy."""
296 mp_policy = self._build_mixed_precision_policy()
297 offload_policy = self._build_offload_policy()
299 fsdp_sublayer_kwargs = {
300 "mesh": fsdp_mesh,
301 "reshard_after_forward": self.config.reshard_after_forward,
302 "mp_policy": mp_policy,
303 "offload_policy": offload_policy,
304 "comm_fusion": self.config.comm_fusion,
305 "comm_fusion_zero_copy": self.config.comm_fusion_zero_copy,
306 }
307 fsdp_root_kwargs = fsdp_sublayer_kwargs.copy()
308 return fsdp_sublayer_kwargs, fsdp_root_kwargs
310 @staticmethod
311 def _find_transformer_block_modules(
312 model: ModuleClass,
313 excluded_subtree_module_fqns: set[str] | None = None,
314 ) -> tuple[list[_WrapModuleInfo], set[int]]:
315 """Find transformer blocks under HF gradient-checkpointing containers.
317 Args:
318 model: Root model to inspect.
319 excluded_subtree_module_fqns: Roots declared by a model adapter as
320 non-decoder branches or self-contained FSDP units. Automatic
321 decoder discovery skips these roots and their descendants.
322 """
323 wrap_modules = []
324 wrapped_module_ids = set()
325 excluded_subtree_module_fqns = excluded_subtree_module_fqns or set()
327 def is_inside_declared_subtree(module_fqn: str) -> bool:
328 """Whether one module is inside an automatic-discovery exclusion.
330 Args:
331 module_fqn: Fully qualified name of the module.
332 """
333 return any(
334 module_fqn == declared_fqn
335 or module_fqn.startswith(f"{declared_fqn}.")
336 for declared_fqn in excluded_subtree_module_fqns
337 )
339 for container_fqn, container in model.named_modules():
340 if container_fqn and is_inside_declared_subtree(container_fqn):
341 continue
342 if id(container) in wrapped_module_ids:
343 continue
344 if not hasattr(container, "gradient_checkpointing"):
345 continue
346 for child_name, child in container.named_children():
347 child_fqn = f"{container_fqn}.{child_name}" if container_fqn else child_name
348 if is_inside_declared_subtree(child_fqn):
349 continue
350 blocks = list(child.named_children())
351 if not blocks:
352 continue
353 for block_name, block in blocks:
354 if id(block) in wrapped_module_ids:
355 continue
356 wrapped_module_ids.add(id(block))
357 wrapped_module = _get_checkpoint_wrapped_module(block)
358 if wrapped_module is not None:
359 # The wrapper and its direct child represent one logical
360 # transformer block during module-tree traversal.
361 wrapped_module_ids.add(id(wrapped_module))
362 wrap_modules.append(
363 _WrapModuleInfo(f"{child_fqn}.{block_name}", block)
364 )
365 return wrap_modules, wrapped_module_ids
367 def _find_expert_wrap_modules(
368 self,
369 model: ModuleClass,
370 metadata_by_parameter: SourceShardInfoByParam | None,
371 wrapped_module_ids: set[int],
372 ) -> list[_WrapModuleInfo]:
373 """Find nested expert containers whose parameters use the expert mesh."""
374 if metadata_by_parameter is None or self.mesh_context.fsdp_moe_mesh is None:
375 return []
376 expert_parameters = {
377 parameter
378 for parameter, source_shard_info in metadata_by_parameter.items()
379 if _is_expert_source_mesh(source_shard_info.mesh)
380 }
381 expert_module_fqns = {
382 parameter_fqn.split(".experts.", 1)[0] + ".experts"
383 for parameter_fqn, parameter in model.named_parameters(remove_duplicate=False)
384 if parameter in expert_parameters and ".experts." in parameter_fqn
385 }
386 expert_module_fqns.update(_declared_expert_unit_fqns(model, expert_parameters))
387 expert_module_fqns.discard("")
388 module_by_fqn = dict(model.named_modules())
389 expert_wrap_modules = []
390 for expert_module_fqn in sorted(expert_module_fqns):
391 expert_module = module_by_fqn.get(expert_module_fqn)
392 if expert_module is None or id(expert_module) in wrapped_module_ids:
393 continue
394 wrapped_module_ids.add(id(expert_module))
395 expert_wrap_modules.append(
396 _WrapModuleInfo(expert_module_fqn, expert_module)
397 )
398 return expert_wrap_modules
400 @staticmethod
401 def _get_model_adapter_spec(model: ModuleClass) -> Any | None:
402 """Resolve a model adapter from the final model configuration."""
403 if hasattr(model, "_hp_model_adapter_spec"):
404 return model._hp_model_adapter_spec # pylint: disable=protected-access
405 config = getattr(model, "config", None)
406 if config is None:
407 return None
408 identities = (
409 getattr(config, "model_type", ""),
410 *((getattr(config, "architectures", None) or [])[:1]),
411 )
412 for identity in identities:
413 if identity:
414 adapter_spec = get_model_adapter(identity)
415 if adapter_spec is not None:
416 return adapter_spec
417 return None
419 @classmethod
420 def _find_adapter_declared_wrap_modules(
421 cls,
422 model: ModuleClass,
423 ) -> list[_WrapModuleInfo]:
424 """Resolve adapter-declared FSDP units outside HF decoder containers.
426 ``ModelAdapterSpec.fsdp_wrap_modules`` keeps architecture-specific
427 execution boundaries on the family adapter side. It receives the
428 finalized model and returns exact root-relative module FQNs.
430 Args:
431 model: Root model being wrapped.
433 Returns:
434 Additional FSDP child units selected by model declarations.
436 Raises:
437 ValueError: If a declaration has an invalid type, targets no
438 module in the model tree, or aliases the same module twice.
439 """
440 adapter_spec = cls._get_model_adapter_spec(model)
441 if adapter_spec is None or adapter_spec.fsdp_wrap_modules is None:
442 return []
444 declared_fqns = adapter_spec.fsdp_wrap_modules(model)
445 if isinstance(declared_fqns, str) or not isinstance(declared_fqns, Sequence):
446 raise ValueError(
447 "ModelAdapterSpec.fsdp_wrap_modules must return a sequence of exact module FQNs"
448 )
449 module_by_fqn = dict(model.named_modules())
450 declared_wrap_modules = []
451 wrapped_module_ids = set()
452 for module_fqn in declared_fqns:
453 if not isinstance(module_fqn, str) or not module_fqn:
454 raise ValueError(
455 "ModelAdapterSpec.fsdp_wrap_modules entries must be non-empty strings"
456 )
457 wrap_module = module_by_fqn.get(module_fqn)
458 if wrap_module is None:
459 raise ValueError(
460 "ModelAdapterSpec.fsdp_wrap_modules declared an unknown module: "
461 f"{module_fqn}"
462 )
463 if id(wrap_module) in wrapped_module_ids:
464 raise ValueError(
465 "ModelAdapterSpec.fsdp_wrap_modules aliases one module more than once: "
466 f"{module_fqn}"
467 )
468 wrapped_module_ids.add(id(wrap_module))
469 declared_wrap_modules.append(_WrapModuleInfo(module_fqn, wrap_module))
470 return declared_wrap_modules
472 @classmethod
473 def _find_adapter_excluded_subtrees(cls, model: ModuleClass) -> set[str]:
474 """Resolve model branches excluded from automatic decoder discovery."""
475 adapter_spec = cls._get_model_adapter_spec(model)
476 excluded_subtrees_provider = getattr(adapter_spec, "fsdp_excluded_subtrees", None)
477 if excluded_subtrees_provider is None:
478 return set()
479 if not callable(excluded_subtrees_provider):
480 raise ValueError("ModelAdapterSpec.fsdp_excluded_subtrees must be callable")
481 excluded_fqns = excluded_subtrees_provider(model) # pylint: disable=not-callable
482 if isinstance(excluded_fqns, str) or not isinstance(excluded_fqns, Sequence):
483 raise ValueError(
484 "ModelAdapterSpec.fsdp_excluded_subtrees must return a sequence of exact module FQNs"
485 )
486 module_by_fqn = dict(model.named_modules())
487 for module_fqn in excluded_fqns:
488 if not isinstance(module_fqn, str) or not module_fqn:
489 raise ValueError(
490 "ModelAdapterSpec.fsdp_excluded_subtrees entries must be non-empty strings"
491 )
492 if module_fqn not in module_by_fqn:
493 raise ValueError(
494 "ModelAdapterSpec.fsdp_excluded_subtrees declared an unknown module: "
495 f"{module_fqn}"
496 )
497 return set(excluded_fqns)
499 def _find_class_wrap_modules(self, model: ModuleClass) -> list[_WrapModuleInfo]:
500 """Select explicit classes, retaining checkpoint wrappers as the units."""
501 requested = set(self.config.wrapper_class)
502 matched = set()
503 selected = []
504 seen = set()
505 aliases = defaultdict(list)
506 for name, parameter in model.named_parameters(remove_duplicate=False):
507 aliases[parameter].append(name)
508 for fqn, module in model.named_modules():
509 if not fqn or id(module) in seen:
510 continue
511 underlying = _get_checkpoint_wrapped_module(module)
512 candidate = underlying if underlying is not None else module
513 class_name = type(candidate).__name__
514 if class_name not in requested:
515 continue
516 matched.add(class_name)
517 parameters = list(module.parameters())
518 if not parameters:
519 raise ValueError(f"wrapper_class selected a parameterless module: {fqn}")
520 if any(not name.startswith(f"{fqn}.") for param in parameters for name in aliases[param]):
521 raise ValueError(f"wrapper_class module shares parameters outside its subtree: {fqn}")
522 selected.append(_WrapModuleInfo(fqn, module))
523 seen.add(id(module))
524 seen.add(id(candidate))
525 if requested - matched:
526 raise ValueError(f"wrapper_class matched no child module for: {sorted(requested - matched)}")
527 return selected
529 def _find_wrap_modules(
530 self,
531 model: ModuleClass,
532 metadata_by_parameter: SourceShardInfoByParam | None = None,
533 ) -> list[_WrapModuleInfo]:
534 """Find automatic decoder/expert units and adapter-declared units."""
535 if self.config.wrapper_class:
536 wrap_modules = self._find_class_wrap_modules(model)
537 wrapped_module_ids = {id(unit.module) for unit in wrap_modules}
538 else:
539 declared_wrap_modules = self._find_adapter_declared_wrap_modules(model)
540 if declared_wrap_modules:
541 logger.info(
542 "Adapter-declared FSDP child units: %s",
543 [wrap_module.fqn for wrap_module in declared_wrap_modules],
544 )
545 excluded_subtree_module_fqns = {
546 wrap_module.fqn for wrap_module in declared_wrap_modules
547 }
548 excluded_subtree_module_fqns.update(
549 self._find_adapter_excluded_subtrees(model)
550 )
551 wrap_modules, wrapped_module_ids = self._find_transformer_block_modules(
552 model,
553 excluded_subtree_module_fqns=excluded_subtree_module_fqns,
554 )
555 wrapped_module_ids.update(
556 id(wrap_module.module) for wrap_module in declared_wrap_modules
557 )
558 wrap_modules.extend(declared_wrap_modules)
559 wrap_modules.extend(
560 self._find_expert_wrap_modules(
561 model,
562 metadata_by_parameter,
563 wrapped_module_ids,
564 )
565 )
566 if not wrap_modules:
567 raise ValueError(
568 "wrap_policy='transformer_block' found no decoder, expert, or "
569 "adapter-declared FSDP child unit"
570 )
571 return wrap_modules
573 @staticmethod
574 def _resolve_parameter_owners(
575 model: ModuleClass,
576 wrap_modules: list[_WrapModuleInfo],
577 ) -> dict[ParameterClass, ModuleClass]:
578 """Assign each parameter to its deepest common FSDP wrap module."""
579 aliases_by_parameter: dict[ParameterClass, list[str]] = defaultdict(list)
580 for parameter_fqn, parameter in model.named_parameters(remove_duplicate=False):
581 aliases_by_parameter[parameter].append(parameter_fqn)
583 owner_by_parameter = {}
584 for parameter, parameter_fqns in aliases_by_parameter.items():
585 common_wrap_modules = []
586 for wrap_module in wrap_modules:
587 module_fqn_prefix = f"{wrap_module.fqn}."
588 if all(parameter_fqn.startswith(module_fqn_prefix) for parameter_fqn in parameter_fqns):
589 common_wrap_modules.append(wrap_module)
590 if common_wrap_modules:
591 owner_by_parameter[parameter] = max(
592 common_wrap_modules,
593 key=lambda wrap_module: wrap_module.fqn.count("."),
594 ).module
595 else:
596 owner_by_parameter[parameter] = model
597 return owner_by_parameter
600 def _uses_expert_mesh(self, metadata_by_parameter: SourceShardInfoByParam | None) -> bool:
601 """Return whether one FSDP unit owns routed-expert source metadata."""
602 if metadata_by_parameter is None or self.mesh_context.fsdp_moe_mesh is None:
603 return False
604 return any(
605 _is_expert_source_mesh(source_shard_info.mesh)
606 for source_shard_info in metadata_by_parameter.values()
607 )
610 @staticmethod
611 def _build_managed_replicate_params(
612 owner: ModuleClass,
613 owner_by_parameter: Mapping[ParameterClass, ModuleClass],
614 replicate_params: set[ParameterClass] | None,
615 ignored_params: set[ParameterClass] | None = None,
616 ) -> set[ParameterClass] | None:
617 """Select configured replicate parameters owned by one FSDP module."""
618 if replicate_params is None:
619 return None
620 ignored_params = ignored_params or set()
621 return {
622 parameter
623 for parameter in replicate_params
624 if owner_by_parameter.get(parameter) is owner and parameter not in ignored_params
625 }
627 def _configure_source_layout_gradient_scaling(
628 self,
629 hsdp_module: HSDPModule,
630 managed_source_shard_info: SourceShardInfoByParam | None,
631 ) -> bool:
632 """Restore global-mean gradients for one source-layout FSDP unit.
634 Master defaults every ``fully_shard`` unit to AVG reduction, so units
635 with source-layout metadata explicitly select SUM. The token-weighted
636 backward loss is scaled by the FSDP data domain (DP x CP), so a
637 source-layout SUM-reduced unit must apply its inverse exactly once.
638 With loss parallelism, TP ranks hold shards or partial contributions
639 to one logical loss and TP is not another averaging axis. Without loss
640 parallelism, logits and the loss are replicated over TP, so the SUM
641 path also accumulates ``tp_size`` identical loss replicas and must
642 divide by TP. EP is excluded because expert ranks own different
643 parameters.
645 Returns:
646 Whether a gradient scaling factor was configured for the unit.
647 """
648 if not managed_source_shard_info:
649 return False
650 hsdp_module.set_reduce_op_type("sum", recurse=False)
652 tp_loss_replica_size = (
653 1 if self.mesh_context.loss_parallel else self.mesh_context.tp_size
654 )
655 source_gradient_domain_size = (
656 self.mesh_context.dp_size
657 * self.mesh_context.cp_size
658 * tp_loss_replica_size
659 )
660 if source_gradient_domain_size <= 1:
661 return False
662 hsdp_module.set_gradient_scaling_factor(1.0 / source_gradient_domain_size)
663 return True
665 def _configure_prefetch(self, hsdp_modules: list[HSDPModule]) -> None:
666 """Configure forward and backward prefetch targets by list depth."""
667 for module_index, hsdp_module in enumerate(hsdp_modules):
668 forward_end = module_index + self.config.forward_prefetch_depth + 1
669 hsdp_module.set_modules_to_forward_prefetch(
670 hsdp_modules[module_index + 1:forward_end]
671 )
673 backward_start = max(
674 0, module_index - self.config.backward_prefetch_depth
675 )
676 hsdp_module.set_modules_to_backward_prefetch(
677 list(reversed(hsdp_modules[backward_start:module_index]))
678 )
680 def _order_wrap_modules(
681 self,
682 model: ModuleClass,
683 wrap_modules: list[_WrapModuleInfo],
684 ) -> list[_WrapModuleInfo]:
685 """Order FSDP units by adapter execution order or module traversal."""
686 module_order = {
687 id(module): module_index
688 for module_index, (_, module) in enumerate(model.named_modules())
689 }
690 default_order = sorted(
691 wrap_modules,
692 key=lambda wrap_module: module_order.get(id(wrap_module.module), len(module_order)),
693 )
694 adapter_spec = self._get_model_adapter_spec(model)
695 execution_order_provider = getattr(adapter_spec, "fsdp_execution_order", None)
696 if execution_order_provider is None:
697 return default_order
698 if not callable(execution_order_provider):
699 raise ValueError("ModelAdapterSpec.fsdp_execution_order must be callable")
701 wrap_module_by_fqn = {
702 wrap_module.fqn: wrap_module for wrap_module in wrap_modules
703 }
704 execution_fqns = execution_order_provider( # pylint: disable=not-callable
705 model,
706 tuple(wrap_module.fqn for wrap_module in default_order),
707 )
708 if isinstance(execution_fqns, str) or not isinstance(execution_fqns, Sequence):
709 raise ValueError(
710 "ModelAdapterSpec.fsdp_execution_order must return a sequence of module FQNs"
711 )
712 if any(not isinstance(module_fqn, str) for module_fqn in execution_fqns):
713 raise ValueError(
714 "ModelAdapterSpec.fsdp_execution_order entries must be module FQN strings"
715 )
716 if (
717 len(execution_fqns) != len(wrap_module_by_fqn)
718 or len(set(execution_fqns)) != len(execution_fqns)
719 or set(execution_fqns) != set(wrap_module_by_fqn)
720 ):
721 raise ValueError(
722 "ModelAdapterSpec.fsdp_execution_order must return every selected FSDP "
723 "child-unit FQN exactly once"
724 )
725 logger.info("Adapter-declared FSDP execution order: %s", list(execution_fqns))
726 return [wrap_module_by_fqn[module_fqn] for module_fqn in execution_fqns]
728 def _parallelize_child_units(
729 self,
730 wrap_modules: list[_WrapModuleInfo],
731 owner_by_parameter,
732 metadata_by_parameter,
733 replicate_params,
734 dense_fsdp_kwargs: dict[str, Any],
735 ignored_params: set[ParameterClass] | None = None,
736 ) -> int:
737 """Apply FSDP to child units and return the gradient-scaled count."""
738 gradient_scaled_units = 0
739 wrapping_order = sorted(
740 wrap_modules, key=lambda wrap_module: wrap_module.fqn.count("."), reverse=True
741 )
742 for wrap_module in wrapping_order:
743 managed_source_info = _build_managed_source_shard_info(
744 self,
745 wrap_module.module,
746 metadata_by_parameter,
747 ignored_params,
748 )
749 fsdp_sublayer_kwargs = dense_fsdp_kwargs
750 if self._uses_expert_mesh(managed_source_info):
751 if self.mesh_context.fsdp_moe_mesh is None:
752 raise ValueError("Expert TP metadata requires MeshContext.fsdp_moe_mesh")
753 fsdp_sublayer_kwargs, _ = self._build_fully_shard_kwargs(
754 self._build_fsdp_actual_mesh(expert=True)
755 )
756 fully_shard( # pylint: disable=unexpected-keyword-arg
757 wrap_module.module,
758 source_shard_infos=_source_infos_for_fully_shard(managed_source_info),
759 replicate_params=self._build_managed_replicate_params(
760 wrap_module.module, owner_by_parameter, replicate_params, ignored_params
761 ),
762 ignored_params=ignored_params,
763 **fsdp_sublayer_kwargs,
764 )
765 if self._configure_source_layout_gradient_scaling(wrap_module.module, managed_source_info):
766 gradient_scaled_units += 1
767 return gradient_scaled_units
769 def _parallelize_root(
770 self,
771 model: ModuleClass,
772 owner_by_parameter,
773 metadata_by_parameter,
774 replicate_params,
775 dense_root_kwargs: dict[str, Any],
776 ignored_params: set[ParameterClass] | None = None,
777 ) -> int:
778 """Apply root FSDP and report whether gradient scaling was configured."""
779 root_source_info = _build_managed_source_shard_info(
780 self,
781 model,
782 metadata_by_parameter,
783 ignored_params,
784 )
785 if self._uses_expert_mesh(root_source_info):
786 raise ValueError("Routed expert parameters must belong to a nested experts FSDP unit")
787 fully_shard( # pylint: disable=unexpected-keyword-arg
788 model,
789 source_shard_infos=_source_infos_for_fully_shard(root_source_info),
790 replicate_params=self._build_managed_replicate_params(
791 model, owner_by_parameter, replicate_params, ignored_params
792 ),
793 ignored_params=ignored_params,
794 **dense_root_kwargs,
795 )
796 return int(self._configure_source_layout_gradient_scaling(model, root_source_info))
798 def _log_gradient_scaling(self, gradient_scaled_units: int) -> None:
799 """Log the source-layout gradient scaling applied to FSDP units."""
800 if not gradient_scaled_units:
801 return
802 domain_size = (
803 self.mesh_context.dp_size
804 * self.mesh_context.cp_size
805 * (1 if self.mesh_context.loss_parallel else self.mesh_context.tp_size)
806 )
807 logger.info(
808 "Applied source-layout SUM gradient scaling: dp_size=%d, cp_size=%d, tp_size=%d, "
809 "source_gradient_domain_size=%d, factor=%s, units=%d",
810 self.mesh_context.dp_size,
811 self.mesh_context.cp_size,
812 self.mesh_context.tp_size,
813 domain_size,
814 1.0 / domain_size,
815 gradient_scaled_units,
816 )
818 def parallelize(
819 self,
820 model: ModuleClass,
821 source_shard_info: SourceShardInfoByFQN | None = None,
822 ignored_params: set[ParameterClass] | None = None,
823 ) -> ModuleClass:
824 """Apply configured child FSDP units, root FSDP, and prefetch links.
826 Args:
827 model: Model to wrap in place.
828 source_shard_info: FQN-keyed source-layout metadata returned by
829 ``apply_sharding_plan``. The manager resolves parameter
830 identities before applying nested FSDP units.
832 Returns:
833 The model enhanced with the HyperParallel HSDPModule interface.
835 Raises:
836 ValueError: If TP is enabled without FQN metadata or configured
837 parameter FQNs cannot be resolved.
838 """
839 self._mp_policy = None
840 metadata_by_parameter = _build_source_shard_info_by_param(
841 self,
842 model,
843 source_shard_info,
844 )
845 replicate_params = self._resolve_replicate_params(model)
846 self._resolve_model_precision_policy(model)
848 wrap_modules = self._find_wrap_modules(model, metadata_by_parameter)
849 owner_by_parameter = self._resolve_parameter_owners(model, wrap_modules)
850 dense_fsdp_kwargs, dense_root_kwargs = self._build_fully_shard_kwargs(
851 self._build_fsdp_actual_mesh()
852 )
854 gradient_scaled_units = self._parallelize_child_units(
855 wrap_modules,
856 owner_by_parameter,
857 metadata_by_parameter,
858 replicate_params,
859 dense_fsdp_kwargs,
860 ignored_params,
861 )
862 gradient_scaled_units += self._parallelize_root(
863 model,
864 owner_by_parameter,
865 metadata_by_parameter,
866 replicate_params,
867 dense_root_kwargs,
868 ignored_params,
869 )
870 self._log_gradient_scaling(gradient_scaled_units)
871 ordered_wrap_modules = self._order_wrap_modules(model, wrap_modules)
872 self._configure_prefetch(
873 [wrap_module.module for wrap_module in ordered_wrap_modules]
874 )
875 logger.info(
876 "Applied FSDP2 to %d child units and the root module",
877 len(wrap_modules),
878 )
879 return model
882def _instantiate_fsdp2(
883 *,
884 config: Any,
885 mesh_context: MeshContext,
886 fp32_main_params: bool = False,
887) -> FSDP2Manager | None:
888 """Create an FSDP2 manager for the resolved strategy config."""
889 if config is None:
890 return None
891 if isinstance(config, FSDP2Config):
892 return FSDP2Manager(
893 config=config,
894 mesh_context=mesh_context,
895 fp32_main_params=fp32_main_params,
896 )
897 raise ValueError(f"FSDP2Manager requires FSDP2Config, got {type(config).__name__}")
900def _apply_fsdp2(
901 model: ModuleClass,
902 fsdp2_manager: Any,
903 source_shard_info: Any,
904 ignored_params: set[ParameterClass] | None = None,
905) -> ModuleClass:
906 """Apply FSDP2; Torch scheduler hooks remain outside Dynamo by design.
908 Moved from ``_transformers/infrastructure.py`` (05 §15.2.1) so the FSDP
909 application step lives with ``FSDP2Manager.parallelize``.
910 """
911 if fsdp2_manager is None:
912 return model
913 if not isinstance(fsdp2_manager, FSDP2Manager):
914 logger.warning("fsdp2_manager is not an FSDP2Manager instance")
915 return model
916 model = fsdp2_manager.parallelize(
917 model,
918 source_shard_info=source_shard_info,
919 ignored_params=ignored_params,
920 )
921 logger.info("FSDP2 wrap applied")
922 return model