kempnerforge.distributed.parallel¶
Parallelism application: TP, AC, Float8, FSDP2, and model building.
Applies parallelism to Transformer models in the correct order.
- Application order (critical — wrong order causes silent correctness bugs):
Tensor parallelism (apply_tensor_parallel) — must see raw blocks
Expert parallelism (apply_expert_parallel) — partitions MoE experts
Float8 training (apply_float8) — wraps Linear → Float8Linear
Activation checkpointing (apply_ac) — wraps blocks in CheckpointWrapper
FSDP2 (apply_fsdp2) — shards everything (uses float8 all-gather if enabled)
For convenience, build_parallel_model combines all steps including
model creation, meta-device initialization, and optional torch.compile.
It also dispatches to a VLM branch when vlm_config is provided.
Functions
|
Apply activation checkpointing to the model's blocks. |
|
Apply Float8 training (torchao) to the model. |
|
Apply FSDP2 (fully_shard) to a Transformer model. |
|
|
|
Build a Transformer (or a VLMWrapper) with parallelism applied. |
|
Mixed-precision policy: |
|
Extract the data-parallel sub-mesh from a DeviceMesh. |
|
Check whether the DeviceMesh contains any data-parallel dimensions. |
|
Whether |
|
Recompute the reduction dtypes of the FSDP2 units that manage |
- kempnerforge.distributed.parallel.has_dp_mesh(device_mesh)[source]¶
Check whether the DeviceMesh contains any data-parallel dimensions.
- Parameters:
device_mesh (torch.distributed.device_mesh.DeviceMesh)
- Return type:
- kempnerforge.distributed.parallel.get_dp_mesh(device_mesh)[source]¶
Extract the data-parallel sub-mesh from a DeviceMesh.
Returns a 1D mesh (pure sharding) or 2D mesh (replicate + shard / HSDP) depending on which dimensions are present.
Raises ValueError if no DP dimensions exist (e.g., pure TP mesh). Use
has_dp_meshto check first.- Parameters:
device_mesh (torch.distributed.device_mesh.DeviceMesh)
- Return type:
- kempnerforge.distributed.parallel.default_mp_policy(param_dtype=torch.bfloat16, reduce_dtype=torch.float32)[source]¶
Mixed-precision policy:
param_dtypecompute,reduce_dtypegradient reduction.cast_forward_inputs=Trueensures FSDP2 casts input tensors to the declaredparam_dtypeat each wrapped module’s forward boundary. The VLM path relies on this so image embeddings produced by the adapter (bf16) reach the sharded transformer with matching dtype without needing the caller to do manual casts. The default onMixedPrecisionPolicyis False, so we set it explicitly here to pin the contract.- Parameters:
param_dtype (torch.dtype)
reduce_dtype (torch.dtype)
- Return type:
torch.distributed._composable.fsdp.MixedPrecisionPolicy
- kempnerforge.distributed.parallel.is_fsdp_wrapped(model)[source]¶
Whether
fully_shardwas applied tomodelor any of its submodules.- Parameters:
model (torch.nn.Module)
- Return type:
- kempnerforge.distributed.parallel.refresh_fsdp_dtypes(model, params)[source]¶
Recompute the reduction dtypes of the FSDP2 units that manage
params.Call it after unfreezing parameters of an FSDP2-wrapped model. Each unit that manages one of
paramsitself, not through a nested unit, is unsharded and resharded. Every rank calls it with the same parameters.- Parameters:
model (torch.nn.Module) – The model, wrapped with FSDP2 or not.
params (Iterable[torch.Tensor]) – The parameters whose
requires_gradwas turned on.
- Return type:
None
- kempnerforge.distributed.parallel.autocast_dtype(model, master_dtype, compute_dtype)[source]¶
compute_dtypeif no FSDP2 wrap castsmaster_dtypeparameters to it, else None.- Parameters:
model (torch.nn.Module)
master_dtype (torch.dtype)
compute_dtype (torch.dtype)
- Return type:
torch.dtype | None
- kempnerforge.distributed.parallel.apply_ac(model, mode)[source]¶
Apply activation checkpointing to the model’s blocks.
Must be called BEFORE apply_fsdp2.
The blocks are the children of
model.layersand, when present,model.cross_attention_layers, selected by position, so every block class is covered:TransformerBlock,MoTBlock,MoMaBlockandCrossAttentionBlockalike. A block that already holds aCheckpointWrapperis left as it is, so calling this twice wraps nothing new.- Parameters:
model (Transformer | PipelineStageModule) – Transformer model or pipeline stage.
mode (ActivationCheckpointing | str) – Checkpointing mode, “none”, “full”, or “selective”, as an
ActivationCheckpointingmember or its string value.fullcheckpoints every block (maximum memory savings);selectivecheckpoints theAttention,MoTAttentionandCrossAttentionmodules inside each block (balanced trade-off) and warns, naming the class, about a block that holds none of them. Underfull, a block that holds anMoEMLPkeeps its routers’ top-k outputs for the recompute, which leaves the routers’ state as the forward set it, and runs eagerly undertorch.compile(see_routing_contexts). Its recompute uses those outputs up, so the graph through it takes one backward: a second, afterbackward(retain_graph=True), raises.
- Returns:
The number of modules this call wrapped.
- Return type:
- kempnerforge.distributed.parallel.apply_float8(model, enable_fsdp_float8_all_gather=True)[source]¶
Apply Float8 training (torchao) to the model.
Converts nn.Linear modules to Float8Linear for E4M3 forward / E5M2 backward with dynamic tensorwise scaling. Master weights keep their dtype (bf16, or fp32).
Must be called AFTER apply_tensor_parallel / apply_expert_parallel and BEFORE apply_ac / apply_fsdp2. The shape check below reads each Linear’s global
in_featuresandout_features, which are its weight’s dimensions only without TP; config validation rejects FP8 with TP.Routed MoE experts are excluded because they use grouped GEMM (torch._grouped_mm), which bypasses Float8Linear.forward(). The shared expert is a plain Linear call; the same name filter excludes it, by convention.
A Linear whose
in_featuresorout_featuresis not a multiple ofFP8_DIM_MULTIPLE(16) stays in high precision, because torch._scaled_mm rejects it on CUDA. One warning names each such layer with its shape, and the info line counts the converted Linears.- Parameters:
model (Transformer) – Transformer model.
enable_fsdp_float8_all_gather (bool) – If True, FSDP2 all-gathers use float8 (halves communication volume). Requires FSDP2 to be applied after. Must be False when TP is active — the float8 weight wrapper calls aten.is_pinned on DTensors, which has no sharding strategy yet.
- Raises:
ValueError – If the model has Linear layers but none of them converts, so an FP8 run would train entirely in high precision.
- Return type:
None
- kempnerforge.distributed.parallel.apply_fsdp2(model, device_mesh, mp_policy=None, reshard_after_forward=True)[source]¶
Apply FSDP2 (fully_shard) to a Transformer model.
Shards each TransformerBlock independently (via
_fsdp_wrap_transformer_blocksso the EP-MoE per-sub-module wrap is shared with the VLM path), then wraps the top-level model for remaining parameters (embeddings, final norm, output head).Must be called AFTER apply_ac and apply_tensor_parallel.
EP interaction: Blocks with expert parallelism get per-sub-module wrapping (attention and MoE individually) instead of per-block wrapping. Per-block wrapping would cause FSDP2’s reduce-scatter to fire between EP’s backward all-to-all calls (deadlock). Per-sub-module wrapping avoids this: the MoE reduce-scatter fires after the entire MoE backward (both EP all-to-alls complete), while attention reduce-scatter is EP-free.
- Parameters:
model (Transformer | PipelineStageModule) – Transformer model to shard.
device_mesh (DeviceMesh) – Full DeviceMesh (dp sub-mesh is extracted automatically).
mp_policy (MixedPrecisionPolicy | None) – Mixed precision policy. Defaults to bf16 params + fp32 reduce.
reshard_after_forward (bool | int) – Whether to free gathered params after forward. True = always reshard (saves memory, default). False = keep gathered (useful when PP needs params across microbatches). int = the world size to reshard to after forward, a divisor of the
dp_shardsize: each unit stays sharded over groups of that many ranks, so the backward all-gather runs within a group, at more memory than True.
- Return type:
None
- kempnerforge.distributed.parallel.build_parallel_model(model_config, device, device_mesh, *, vision_config=None, adapter_config=None, vlm_config=None, ac_mode=ActivationCheckpointing.none, mp_policy=None, encoder_mp_policy=None, param_dtype=torch.bfloat16, compile_model=False, fp8=False, frames_per_clip=1)[source]¶
Build a Transformer (or a VLMWrapper) with parallelism applied.
Dispatches on
vlm_config(None-> text-only path). Non-VLM configurations follow the original order:TP enabled: meta-device init -> TP -> EP -> [Float8] -> AC -> FSDP -> materialize
TP disabled: create on device -> EP -> [Float8] -> AC -> FSDP
VLM configurations follow the order documented on
_build_vlm.This is the non-PP model building path. For pipeline parallelism, use
build_stage_module+ apply parallelism directly.- Parameters:
model_config – ModelConfig for the Transformer.
device (torch.device) – Target device for the model.
device_mesh (DeviceMesh | None) – Full DeviceMesh (may contain tp, dp_shard, dp_replicate dims).
vision_config – VisionEncoderConfig (required iff vlm_config is set).
adapter_config – AdapterConfig (required iff vlm_config is set).
vlm_config – VLMConfig. None for a pure text-only run.
ac_mode (ActivationCheckpointing) – Activation checkpointing mode.
mp_policy (MixedPrecisionPolicy | None) – FSDP2 mixed-precision policy. Defaults to bf16 params + fp32 reduce.
encoder_mp_policy (MixedPrecisionPolicy | None) – A trainable vision encoder’s FSDP2 policy.
Nonegives itmp_policyunchanged, unlessvision_configsetsmixed_precisionor a bf16grad_reduce_dtype, which give it its own policy.param_dtype (torch.dtype) – Dtype for model parameters.
compile_model (bool) – Whether to torch.compile the model.
fp8 (bool) – Whether to enable Float8 mixed precision (torchao).
frames_per_clip (int)
- Returns:
The parallelized model, ready for training.
- Return type: