Source code for kempnerforge.config.training

"""Training configuration."""

from __future__ import annotations

import math
from dataclasses import dataclass
from enum import StrEnum
from typing import TYPE_CHECKING, Literal, get_args

if TYPE_CHECKING:
    import torch

FP32_CROSS_ENTROPY_LOSSES = ("cross_entropy", "chunked_cross_entropy")

NaNAction = Literal["warn", "skip", "raise"]
"""What ``NaNDetector`` does on a step whose loss or gradient norm is NaN/Inf."""

FP8_DIM_MULTIPLE = 16
"""``torch._scaled_mm`` needs both dimensions of an FP8 weight to be multiples of this."""

_FP16_UNSUPPORTED = (
    "train.mixed_precision='fp16' is not supported: it would train in pure fp16 "
    "with no loss scaling, so small gradients underflow to zero. Use 'bf16', or "
    "'fp32' on GPUs without bf16."
)


[docs] class ActivationCheckpointing(StrEnum): none = "none" full = "full" selective = "selective"
[docs] @dataclass class TrainConfig: """Training hyperparameters. ``"fp16"`` stays in the ``mixed_precision`` ``Literal`` only so the config loader passes it on to ``__post_init__``, which rejects it with the reason; without it the loader would fail first with a generic Literal error. ``nan_action`` and ``nan_max_consecutive`` set the training loop's ``NaNDetector``: its response to a NaN/Inf step, and how many in a row stop the loop. ``grad_reduce_dtype`` is the dtype FSDP2 reduces gradients in (reduce-scatter and, with replicas, all-reduce) for every unit the training build wraps with the language model's policy: the transformer, and on a VLM the adapter. ``"fp32"`` is the default; ``"bf16"`` halves the reduce traffic and rounds each rank's gradient to bf16 before the sum. With ``"bf16"`` and ``grad_accum_steps > 1`` every micro-step is reduced, one reduce-scatter per micro-step instead of one per step, and FSDP2 adds each reduced gradient into the sharded gradient, so the running sum is kept in ``master_dtype`` and never in bf16. ``"fp32"`` keeps one reduce per step, at the last micro-step, with the running sum held unsharded in fp32. Neither changes the stored parameter dtype or the dtype gradients are stepped in (``master_dtype``); a VLM's vision encoder takes ``vision_encoder.grad_reduce_dtype`` instead. ``JobConfig.validate`` refuses ``"bf16"`` on a run FSDP2 does not wrap (one GPU, a pp-only mesh), since nothing would be reduced. ``shutdown_timeout_sec`` bounds a rank's shutdown with a forced exit; ``0`` disables it, and left unset a ``SIGTERM``'s fits the launch script's signal lead (see ``kempnerforge.resilience.signal_handler.resolve_shutdown_timeouts``). """ batch_size: int = 8 seq_len: int = 2048 max_steps: int = 100000 grad_accum_steps: int = 1 grad_clip_norm: float = 1.0 seed: int = 42 data_seed: int | None = None compile_model: bool = True mixed_precision: Literal["bf16", "fp16", "fp32", "fp8"] = "bf16" fp32_master_weights: bool = False tf32: bool = False grad_reduce_dtype: Literal["fp32", "bf16"] = "fp32" activation_checkpointing: ActivationCheckpointing = ActivationCheckpointing.none loss_fn: str = "cross_entropy" z_loss_weight: float = 0.0 ce_chunk_size: int = 0 fp32_cross_entropy: bool = False shutdown_timeout_sec: float | None = None nccl_health_check_interval: int = 0 nan_action: NaNAction = "warn" nan_max_consecutive: int = 10 def __post_init__(self) -> None: if self.batch_size <= 0: raise ValueError("batch_size must be positive") if self.seq_len <= 0: raise ValueError("seq_len must be positive") if self.max_steps <= 0: raise ValueError("max_steps must be positive") if self.grad_accum_steps <= 0: raise ValueError("grad_accum_steps must be positive") if self.grad_clip_norm <= 0: raise ValueError("grad_clip_norm must be positive") if self.mixed_precision == "fp16": raise ValueError(_FP16_UNSUPPORTED) if self.fp32_master_weights and self.mixed_precision == "fp32": raise ValueError( "train.fp32_master_weights has no effect with mixed_precision='fp32': the " "weights are already fp32. Use it with 'bf16' or 'fp8', or turn it off." ) if self.grad_reduce_dtype not in ("fp32", "bf16"): raise ValueError( "train.grad_reduce_dtype must be one of ['fp32', 'bf16'] " f"(got {self.grad_reduce_dtype!r})" ) if self.fp32_cross_entropy and self.loss_fn not in FP32_CROSS_ENTROPY_LOSSES: raise ValueError( f"train.fp32_cross_entropy applies to {', '.join(FP32_CROSS_ENTROPY_LOSSES)}, " f"not loss_fn={self.loss_fn!r}" ) if self.nan_action not in get_args(NaNAction): raise ValueError( f"nan_action must be one of {', '.join(get_args(NaNAction))} " f"(got {self.nan_action!r})" ) if self.nan_max_consecutive <= 0: raise ValueError("nan_max_consecutive must be positive") if self.shutdown_timeout_sec is not None and not 0 <= self.shutdown_timeout_sec < math.inf: raise ValueError( "shutdown_timeout_sec must be a finite number of seconds >= 0, where 0 disables " f"the forced exit, or unset (got {self.shutdown_timeout_sec!r})" ) @property def param_dtype(self) -> torch.dtype: """Resolve mixed_precision to the compute dtype, also the master weight dtype by default. FP8 resolves to bf16 -- FP8 is a compute mode, not a storage dtype. The storage dtype is :attr:`master_dtype`, which is fp32 with ``fp32_master_weights``. A config switched to ``"fp16"`` after construction skips ``__post_init__``, so ``"fp16"`` raises the same ``ValueError`` here. """ import torch if self.mixed_precision == "fp16": raise ValueError(_FP16_UNSUPPORTED) _DTYPE_MAP = { "bf16": torch.bfloat16, "fp32": torch.float32, "fp8": torch.bfloat16, } return _DTYPE_MAP[self.mixed_precision] @property def master_dtype(self) -> torch.dtype: """Dtype the parameters, their gradients and the optimizer state are kept in.""" import torch return torch.float32 if self.fp32_master_weights else self.param_dtype @property def reduce_dtype(self) -> torch.dtype: """Dtype FSDP2 reduces the transformer's and adapter's gradients in.""" import torch return {"fp32": torch.float32, "bf16": torch.bfloat16}[self.grad_reduce_dtype] @property def reduces_every_micro_step(self) -> bool: """Whether the transformer's FSDP2 units reduce every micro-step, as a pipeline stage.""" return self.grad_reduce_dtype == "bf16" @property def is_fp8(self) -> bool: """Whether FP8 mixed precision is enabled.""" return self.mixed_precision == "fp8" @property def effective_data_seed(self) -> int: """Seed for data shuffling / batch composition. Falls back to ``seed`` when ``data_seed`` is unset, so existing configs reproduce their current trajectory. Kept independent from ``seed`` (parameter init) so stability studies can vary batch order while holding initialization fixed. Must stay identical across data-parallel ranks so the global shuffle is consistent before rank partitioning. """ return self.data_seed if self.data_seed is not None else self.seed