Source code for kempnerforge.config.job

"""Top-level job configuration aggregating all sub-configs."""

from __future__ import annotations

from dataclasses import dataclass, field, fields

from kempnerforge.config.adapter import AdapterConfig
from kempnerforge.config.checkpoint import CheckpointConfig
from kempnerforge.config.data import DataConfig
from kempnerforge.config.distributed import DistributedConfig
from kempnerforge.config.eval import EvalConfig
from kempnerforge.config.metrics import MetricsConfig
from kempnerforge.config.model import FLEX_BLOCK_SIZE, ModelConfig
from kempnerforge.config.optimizer import OptimizerConfig
from kempnerforge.config.profiling import ProfilingConfig
from kempnerforge.config.scheduler import SchedulerConfig
from kempnerforge.config.training import FP8_DIM_MULTIPLE, TrainConfig
from kempnerforge.config.video import VideoConfig
from kempnerforge.config.vision import VisionEncoderConfig
from kempnerforge.config.vlm import MoMaConfig, MoTConfig, VLMConfig

_HF_VISION_ENCODER_TYPES = frozenset({"siglip2", "clip"})

_VIDEO_INSTEAD_OF_DATA_HF_FIELDS = {
    "hf_dataset_name": "set video.data_root and video.dataset_name instead",
    "hf_dataset_config": "no [video] counterpart",
    "hf_dataset_split": "set video.split instead",
    "hf_dataset_text_field": "no [video] counterpart",
    "hf_dataset_image_field": "no [video] counterpart",
    "hf_dataset_prompt_field": "set video.prompt instead, one instruction for every clip",
    "hf_image_size": "set video.frame_size instead",
    "hf_streaming": "no [video] counterpart",
}


def _set_away_from_default(value: object, default: object) -> bool:
    """Whether ``value`` departs from ``default``; ``""`` is unset where the default is ``None``."""
    return bool(value) if default is None else value != default


def _arch_of(vlm: VLMConfig) -> str:
    """The arch of ``vlm``'s class, which is what the parallelism checks act on.

    The instance's ``arch`` field can name another arch after an assignment to
    it, which ``__post_init__`` does not see; the loader rejects a ``--vlm.arch``
    override that would need another class.
    """
    return type(vlm).declared_arch()


[docs] @dataclass class JobConfig: """Top-level configuration aggregating all sub-configs. The VLM stack lives as three sibling top-level sections, ``[vision_encoder]`` / ``[adapter]`` / ``[vlm]``. A pure text run leaves all three at ``None`` and writes only ``[model]`` (plus the other operational sections). A VLM run sets ``[vlm]`` and is required to provide ``[vision_encoder]``; ``[adapter]`` defaults to the registered 2-layer MLP and may be omitted. """ model: ModelConfig = field(default_factory=ModelConfig) train: TrainConfig = field(default_factory=TrainConfig) optimizer: OptimizerConfig = field(default_factory=OptimizerConfig) scheduler: SchedulerConfig = field(default_factory=SchedulerConfig) data: DataConfig = field(default_factory=DataConfig) eval: EvalConfig = field(default_factory=EvalConfig) distributed: DistributedConfig = field(default_factory=DistributedConfig) checkpoint: CheckpointConfig = field(default_factory=CheckpointConfig) metrics: MetricsConfig = field(default_factory=MetricsConfig) profiling: ProfilingConfig = field(default_factory=ProfilingConfig) vision_encoder: VisionEncoderConfig | None = None adapter: AdapterConfig | None = None vlm: VLMConfig | None = None video: VideoConfig | None = None plugins: list[str] = field(default_factory=list) def __post_init__(self) -> None: """Cross-section invariants that fire at construction time. ``validate(world_size)`` covers checks that depend on the distributed world size; everything that is decidable from the config alone runs here so loader-time mistakes surface before any distributed init. ``load_config`` builds the config once, from the TOML with the command-line overrides laid over it, so these checks read both layers together. """ if not isinstance(self.plugins, list) or not all(isinstance(p, str) for p in self.plugins): raise ValueError(f"plugins must be a list of module paths (got {self.plugins!r})") if self.data.hf_max_images != 1: if self.vlm is None or self.video is not None: raise ValueError( "data.hf_max_images applies to VLM image runs, not text runs or [video]" ) if self.vlm.arch != "joint_decoder": raise ValueError( "data.hf_max_images != 1 requires vlm.arch='joint_decoder' (got " f"{self.vlm.arch!r}); only its inline route places several images per document" ) if self.train.is_fp8: raise ValueError( "data.hf_max_images != 1 is not supported with train.mixed_precision='fp8'" ) if self.model.sdpa_backend == "flash" and self.model.attention_backend == "sdpa": raise ValueError( "data.hf_max_images != 1 is not supported with model.sdpa_backend='flash'" ) if self.video is not None: if self.vlm is None: raise ValueError( "[video] is set but [vlm] is missing; video training runs through " "the VLM wrapper, so a [vlm] section (and [vision_encoder]) is required." ) if self.vlm.tile_grid: raise ValueError( "vlm.tile_grid tiles the image path, but [video] is set; a video run " "samples frames instead, so leave vlm.tile_grid at 0" ) if self.vlm is not None: if self.vision_encoder is None: raise ValueError( "[vlm] is set but [vision_encoder] is missing; a VLM run requires a " "vision encoder section." ) if self.adapter is None: self.adapter = AdapterConfig() if self.vision_encoder.type in _HF_VISION_ENCODER_TYPES and ( self.vision_encoder.feature_dim > 0 or self.vision_encoder.num_tokens > 0 ): import logging overrides = [] if self.vision_encoder.feature_dim > 0: overrides.append(f"feature_dim={self.vision_encoder.feature_dim}") if self.vision_encoder.num_tokens > 0: overrides.append(f"num_tokens={self.vision_encoder.num_tokens}") logging.getLogger(__name__).warning( "vision_encoder.type=%r is HF-backed and probes its own dims; " "setting %s overrides the probe and may desync from the loaded " "model. Leave both at 0 to use the probed values; feature_dim is " "needed only for a model whose config has no hidden_size.", self.vision_encoder.type, " and ".join(overrides), ) if self.vision_encoder.num_tokens > 0: assert self.adapter is not None per_frame = self.adapter.output_num_tokens(self.vision_encoder.num_tokens) visual_tokens = self.views_per_sample * self.images_per_document * per_frame residual_image_tokens = self.vlm.residual_stream_image_tokens(visual_tokens) required = residual_image_tokens + self.vlm.max_text_len if self.model.max_seq_len < required: raise ValueError( f"model.max_seq_len ({self.model.max_seq_len}) insufficient for VLM: " f"residual_image_tokens ({residual_image_tokens}) + " f"vlm.max_text_len ({self.vlm.max_text_len}) = {required}" ) if self.data.pack_sequences and self.vlm is not None: if self.video is not None: raise ValueError("data.pack_sequences is not supported with [video]") if self.vlm.arch != "joint_decoder": raise ValueError( "data.pack_sequences on a VLM run requires vlm.arch='joint_decoder' " f"(got {self.vlm.arch!r}); the other arches place image tokens as a " "prefix only" ) if self.train.is_fp8: raise ValueError( "data.pack_sequences on a VLM run does not support " "train.mixed_precision='fp8': the packed head runs over the batch's text " "tokens, whose count is the inner dimension of the head's FP8 " f"weight-gradient GEMM and must be a multiple of {FP8_DIM_MULTIPLE}" ) if self.optimizer.lr_multipliers: if self.vlm is None: raise ValueError( "optimizer.lr_multipliers names modules of vlm.module_patterns, so it needs " "a [vlm] section" ) unknown = sorted(set(self.optimizer.lr_multipliers) - set(self.vlm.module_patterns)) if unknown: raise ValueError( f"optimizer.lr_multipliers names unknown modules {unknown}; the modules of " f"vlm.module_patterns are {sorted(self.vlm.module_patterns)}" ) if self.model.attention_backend == "flex" and self.train.seq_len < FLEX_BLOCK_SIZE: raise ValueError( f"attention_backend='flex' requires train.seq_len >= {FLEX_BLOCK_SIZE}, " f"got {self.train.seq_len}. Use attention_backend='sdpa' for shorter sequences." ) @property def images_per_document(self) -> int: """Images one document may hold: the image cap, or one clip on a video run.""" if self.video is not None: return 1 return self.data.hf_max_images @property def is_vlm(self) -> bool: """Whether this job builds a ``VLMWrapper`` around the text backbone.""" return self.vlm is not None @property def is_video(self) -> bool: """Whether this job trains on a video dataset (a VLM sub-mode).""" return self.video is not None @property def views_per_sample(self) -> int: """Images the encoder sees per sample: a clip's frames, a tiled image's views, or one.""" if self.video is not None: return self.video.max_frames if self.vlm is not None: return self.vlm.views_per_image return 1
[docs] def masks_frames_in_backend_attention(self) -> bool: """Whether a frame mask reaches self-attention that runs under ``model.sdpa_backend``. The modality strategy, which the vlm section's ``arch`` picks, masks padded frames in self-attention under Joint-Decoder, MoT and MoMa; Cross-Attention masks them in its cross-attention layers only. The model's attention, which the section's class picks, runs SDPA under the configured backend except under MoT. A section whose ``arch`` an override changed is judged by both. """ if self.vlm is None: return False masks = self.vlm.arch in ("joint_decoder", "mot", "moma") return masks and _arch_of(self.vlm) != "mot"
[docs] def check_flash_attention_masks(self) -> None: """Refuse ``sdpa_backend="flash"`` for a training run whose batches carry a mask. PyTorch's CUDA FlashAttention kernel takes no attention mask. Packed rows mask their documents from each other under ``attention_backend="sdpa"``, where a run reads them from a dataset (flex turns them into a block mask), and the padded frames of a video run are masked under either backend where ``masks_frames_in_backend_attention`` says so: Joint-Decoder and MoMa. The training setup calls this on CUDA, after the CLI overrides and before the process group starts. Evaluation and generation are not checked at setup: on CUDA, a forward there that passes a dense mask to ``Attention``, such as video evaluation's frame mask under Joint-Decoder or MoMa, raises the ``ValueError`` from ``Attention.forward``. Raises: ValueError: The run would train with ``sdpa_backend="flash"`` and a mask. """ if self.model.sdpa_backend != "flash": return data = self.data masked = None if ( data.pack_sequences and self.model.attention_backend == "sdpa" and (self.is_vlm or data.datasets or data.dataset_path or data.hf_dataset_name) ): masked = "data.pack_sequences, which masks the documents of a row from each other" elif self.video is not None and self.masks_frames_in_backend_attention(): assert self.vlm is not None masked = f"[video] on vlm.arch={self.vlm.arch!r}, which masks padded frames" if masked is not None: raise ValueError( f"model.sdpa_backend='flash' is not supported with {masked}: PyTorch's " "FlashAttention kernel takes no attention mask on CUDA. Use another " "sdpa_backend, such as 'auto'." )
[docs] def validate(self, world_size: int = 1, *, training: bool = True) -> None: """Run cross-config validations that depend on the world size. ``training=False`` skips the checks that concern only a training run, such as a bf16 gradient reduce without a data-parallel mesh, for a job that computes no gradient (``scripts/eval.py``). """ self.distributed.validate_world_size(world_size) if self.train.seq_len > self.model.max_seq_len: raise ValueError( f"train.seq_len ({self.train.seq_len}) exceeds " f"model.max_seq_len ({self.model.max_seq_len})" ) if self.model.tie_embeddings and self.distributed.pp > 1: raise ValueError( "Tied embeddings are not supported with pipeline parallelism " "(embedding and output head must be on different stages)" ) if self.eval.enabled and not self.eval.dataset_path and not self.eval.hf_dataset_name: raise ValueError( "eval.enabled is True but no eval data source is configured. " "Set eval.dataset_path or eval.hf_dataset_name." ) if ( self.eval.enabled and self.distributed.pp > 1 and self.eval.steps % self.train.grad_accum_steps ): raise ValueError( f"eval.steps ({self.eval.steps}) must be a multiple of train.grad_accum_steps " f"({self.train.grad_accum_steps}) under pipeline parallelism: eval runs its " f"batches through the training schedule, grad_accum_steps at a time." ) weighted = self.data.mixture_weight_fields() if self.is_vlm: unread = (["data.datasets"] if self.data.datasets else []) + weighted if unread: source = ( "[video]" if self.is_video else "data.hf_dataset_name and the other data.hf_* fields" ) lr_scale = "; a data phase's lr_scale applies without a mixture" if weighted else "" raise ValueError( "A VLM run never builds a [[data.datasets]] mixture (it reads its data from " f"{source}), so these [data] fields would be ignored: {', '.join(unread)}. " f"Remove them{lr_scale}." ) elif weighted and not self.data.datasets: raise ValueError( f"{', '.join(weighted)} would reweight a [[data.datasets]] mixture, but this run " "has none (data.datasets is empty), so the weights would be ignored. List the " "sources as [[data.datasets]] tables or remove the weights; a data phase's " "lr_scale applies without a mixture." ) shared = [ " and ".join(f"data.datasets[{i}]" for i in indices) + f" share the name {name!r}" for name, indices in self.data.duplicate_mixture_names().items() ] if shared: raise ValueError( f"{', '.join(shared)}; the mixture knows each [[data.datasets]] source by its " "name (a source without a name goes by its path or hf_name), so these sources " "would take one weight once a data phase starts, and their per-source metrics " "would share one name. Give each source its own name." ) unknown = self.data.unknown_mixture_weight_keys() if unknown: named = ", ".join( f"{field} names unknown sources {keys}" for field, keys in unknown.items() ) sources = [source.mixture_name for source in self.data.datasets] raise ValueError( f"{named}; the [[data.datasets]] sources are {sources} (a source without a name " "goes by its path or hf_name), and a weight for an unknown source would be " "ignored." ) if self.train.fp32_master_weights and self.model.is_moe: resolved = self.distributed.resolve(world_size) if max(resolved.dp_replicate, resolved.dp_shard, resolved.tp, resolved.ep) == 1: raise ValueError( "train.fp32_master_weights with an MoE model needs a mesh FSDP2 wraps " "(more than one GPU): without one the forward runs under torch.autocast, " "the expert inputs stay fp32 and the experts lose grouped GEMM. Turn " "fp32_master_weights off or train on more than one GPU." ) unwrapped = [ f"{field} = 'bf16'" for field, dtype in ( ("train.grad_reduce_dtype", self.train.grad_reduce_dtype), ( "vision_encoder.grad_reduce_dtype", self.vision_encoder.grad_reduce_dtype if self.is_vlm and self.vision_encoder is not None else "fp32", ), ) if dtype != "fp32" ] if training and unwrapped: resolved = self.distributed.resolve(world_size) if max(resolved.dp_replicate, resolved.dp_shard, resolved.tp, resolved.ep) == 1: raise ValueError( f"{' and '.join(unwrapped)} has no effect: FSDP2 does not wrap the model " "without a data-parallel mesh (one GPU, or a pp-only mesh), so no gradient " "is reduced. Leave it 'fp32'." ) if self.model.is_moe and self.train.compile_model: import logging logging.getLogger(__name__).warning( "torch.compile is not yet optimized for MoE dispatch (data-dependent shapes " "cause graph breaks). Set compile_model=false for MoE models." ) if self.distributed.tp > 1: if isinstance(self.vlm, MoTConfig): raise ValueError( f"vlm.arch={_arch_of(self.vlm)!r} does not support tensor parallelism " f"(distributed.tp={self.distributed.tp}): the tensor-parallel plan is keyed " "on TransformerBlock's module names, and MoTBlock renames the attention " "modules (attn_norm, attn) and holds mlp_norm and mlp as per-modality " "ModuleDicts, so the build fails or no parameter is sharded. Set " "distributed.tp = 1." ) if ( self.vlm is not None and self.distributed.pp == 1 and self.model.tp_sequence_parallel ): ways = ( "tied embeddings give (MoMa keeps model.num_experts = 0)" if isinstance(self.vlm, MoMaConfig) else "an MoE model or tied embeddings give" ) raise ValueError( f"vlm.arch={_arch_of(self.vlm)!r} does not support tensor parallelism with " f"sequence parallelism on (distributed.tp={self.distributed.tp}): tensor " "parallelism shards the activations along the sequence for a dense model " "with untied embeddings, and the first forward then fails on mixed " "torch.Tensor and DTensor operands. Set distributed.tp = 1. This arch " "runs under tensor parallelism only with sequence parallelism off, which " f"{ways}." ) if self.model.n_heads % self.distributed.tp != 0: raise ValueError( f"n_heads ({self.model.n_heads}) must be divisible by " f"tp ({self.distributed.tp})" ) if self.model.n_kv_heads and self.model.n_kv_heads % self.distributed.tp != 0: raise ValueError( f"n_kv_heads ({self.model.n_kv_heads}) must be divisible by " f"tp ({self.distributed.tp})" ) if self.train.is_fp8 and self.distributed.tp > 1: raise ValueError( "FP8 + Tensor Parallelism is not yet supported (torchao Float8Linear " "does not compose with DTensor sharding). Use FP8 with FSDP only, " "or TP without FP8." ) if self.train.is_fp8 and self.model.dim % FP8_DIM_MULTIPLE: raise ValueError( f"train.mixed_precision='fp8' needs model.dim divisible by {FP8_DIM_MULTIPLE} " f"(got {self.model.dim}): torch._scaled_mm needs both dimensions of an FP8 " f"weight divisible by {FP8_DIM_MULTIPLE}, and every attention and MLP " "projection and the output head has model.dim on one side, so no layer would " f"run in FP8. Use a multiple of {FP8_DIM_MULTIPLE} or train in bf16." ) tokens = self.train.batch_size * self.train.seq_len if self.train.is_fp8 and self.vlm is None and tokens % FP8_DIM_MULTIPLE: raise ValueError( "train.mixed_precision='fp8' needs train.batch_size * train.seq_len divisible " f"by {FP8_DIM_MULTIPLE} (got {self.train.batch_size} * {self.train.seq_len} = " f"{tokens}): the FP8 weight gradient multiplies over the micro-batch's tokens, " f"and torch._scaled_mm needs that dimension divisible by {FP8_DIM_MULTIPLE}, so " "the first backward would fail. Change batch_size or seq_len, or train in bf16." ) if self.model.is_moe and self.distributed.pp > 1: alternatives = ( "Use FSDP instead; MoT runs neither TP nor EP." if isinstance(self.vlm, MoTConfig) else "Use FSDP, TP, or EP instead." ) raise ValueError( "MoE + Pipeline Parallelism is not supported. MoE layers use " "data-dependent routing that is incompatible with pipeline stage " f"splitting. {alternatives}" ) if self.distributed.ep > 1: if isinstance(self.vlm, MoTConfig): raise ValueError( f"vlm.arch={_arch_of(self.vlm)!r} does not support expert parallelism " f"(distributed.ep={self.distributed.ep}): the FSDP2 wrap for expert-parallel " "blocks expects layer.attention and layer.mlp, and MoTBlock names its " "attention attn and keeps its FFNs per modality, so a MoT model with experts " "fails to build. Set distributed.ep = 1." ) if isinstance(self.vlm, MoMaConfig): raise ValueError( f"vlm.arch={_arch_of(self.vlm)!r} does not support expert parallelism " f"(distributed.ep={self.distributed.ep}): apply_expert_parallel partitions " "MoEMLP experts only, and MoMa's per-modality expert groups need an EP-aware " "dispatch that is not wired yet, so every rank would keep every expert. Set " "distributed.ep = 1." ) if not self.model.is_moe: raise ValueError("ep > 1 requires an MoE model (num_experts > 0)") if self.model.num_experts % self.distributed.ep != 0: raise ValueError( f"num_experts ({self.model.num_experts}) must be divisible by " f"ep ({self.distributed.ep})" ) if self.is_vlm: assert self.vlm is not None assert self.vision_encoder is not None if ( self.vision_encoder.type in _HF_VISION_ENCODER_TYPES and not self.vision_encoder.path ): raise ValueError( f"vision_encoder.type = {self.vision_encoder.type!r} loads a pretrained " "Hugging Face model, but vision_encoder.path is empty; set " "vision_encoder.path to the model's Hub id or local directory" ) if self.video is not None: defaults = {f.name: f.default for f in fields(DataConfig)} unread = [ name for name in _VIDEO_INSTEAD_OF_DATA_HF_FIELDS if _set_away_from_default(getattr(self.data, name), defaults[name]) ] if unread: settings = "; ".join( f"data.{name} = {getattr(self.data, name)!r} " f"({_VIDEO_INSTEAD_OF_DATA_HF_FIELDS[name]})" for name in unread ) reset = ", ".join(f"{name} = {defaults[name]!r}" for name in unread) raise ValueError( "[video] is set, so the dataset comes from [video] and these [data] " f"fields would be ignored: {settings}. Leave them at their defaults " f"({reset})." ) if self.vision_encoder.num_tokens > 0: assert self.adapter is not None per_frame = self.adapter.output_num_tokens(self.vision_encoder.num_tokens) visual_tokens = self.views_per_sample * self.images_per_document * per_frame residual_image_tokens = self.vlm.residual_stream_image_tokens(visual_tokens) required = residual_image_tokens + self.vlm.max_text_len if self.train.seq_len < required: raise ValueError( f"train.seq_len ({self.train.seq_len}) insufficient for VLM: " f"residual_image_tokens ({residual_image_tokens}) + " f"vlm.max_text_len ({self.vlm.max_text_len}) = {required}" ) if self.distributed.pp > 1: raise ValueError( "VLM + Pipeline Parallelism is not supported on this branch. " "The vlm-cross-attention branch will address PP integration." ) if isinstance(self.vlm, MoMaConfig): if self.model.num_experts > 0: raise ValueError( "MoMa + model.num_experts > 0 is rejected. MoMa derives expert " "counts per modality from vlm.moma_experts_per_modality; set " "model.num_experts=0 (the dense-LLM default) when using arch='moma'." ) if self.train.compile_model: import logging logging.getLogger(__name__).warning( "torch.compile is not yet validated for MoMa dispatch " "(modality_ids-based scatter/gather + expert-choice top-k cause " "graph breaks). Set compile_model=false for MoMa models." )