Config sections

JobConfig aggregates ten typed sub-configs that every run has, plus four VLM sections that stay None unless the config sets them, except that a [vlm] run without [adapter] gets the default adapter. Each one lives in its own module under kempnerforge/config/ and declares its fields with dataclass defaults. TOML sections map one-to-one onto these dataclass attributes:

[model]          # → config.model   (ModelConfig)
[train]          # → config.train   (TrainConfig)
[optimizer]      # → config.optimizer
[scheduler]      # → config.scheduler
[data]           # → config.data
[eval]           # → config.eval
[distributed]    # → config.distributed
[checkpoint]     # → config.checkpoint
[metrics]        # → config.metrics
[profiling]      # → config.profiling
[vlm]            # → config.vlm             (the class its arch registers)
[vision_encoder] # → config.vision_encoder  (VisionEncoderConfig)
[adapter]        # → config.adapter         (AdapterConfig)
[video]          # → config.video           (VideoConfig)

JobConfig

Owns the sub-configs and the cross-section checks, __post_init__ and validate(world_size). kempnerforge/config/job.py.

Field

Type

Purpose

model

ModelConfig

architecture + MoE knobs

train

TrainConfig

loop-level hyperparameters

optimizer

OptimizerConfig

registry key + LR + betas + optimizer-specific knobs

scheduler

SchedulerConfig

LR schedule shape and warmup

data

DataConfig

dataset sources, mixing, annealing

eval

EvalConfig

in-loop eval cadence and data source

distributed

DistributedConfig

parallelism dims, NCCL timeout

checkpoint

CheckpointConfig

DCP save cadence, retention, resume path

metrics

MetricsConfig

logging cadence and backends

profiling

ProfilingConfig

torch.profiler window and trace dir

vlm

VLMConfig | None

VLM architecture, text length, tiling and freeze; None is a text run

vision_encoder

VisionEncoderConfig | None

VLM image encoder; [vlm] requires it

adapter

AdapterConfig | None

VLM connector; a [vlm] run without it gets the defaults

video

VideoConfig | None

video dataset and frame sampling; requires [vlm]

plugins

list[str]

module paths imported before the config is built, for their registry side effects; see Registry

plugins is a top-level key, not a section: plugins = ["pkg.module"].

[model]: ModelConfig

Architecture hyperparameters and MoE knobs. kempnerforge/config/model.py.

Dense

Field

Type

Default

Purpose

dim

int

4096

hidden size

n_layers

int

32

number of transformer blocks

n_heads

int

32

attention heads

n_kv_heads

int | None

None

GQA: None → MHA (= n_heads), 1 → MQA, else GQA

head_dim_override

int

0

0 → head_dim is dim // n_heads; a positive even value decouples the attention width, so n_heads * head_dim need not equal dim

vocab_size

int

32000

embedding table size

ffn_dim_multiplier

float

1.0

scales Llama-style 4·dim·(2/3) hidden width

ffn_hidden_dim

int | None

None

hard-override the computed FFN width

norm_type

"rmsnorm" | "layernorm" or a registered norm name

"rmsnorm"

registry key for norm builder

norm_eps

float

1e-5

norm epsilon

activation

"silu" | "gelu" | "relu" or a plugin’s registered mlp name

"silu"

MLP activation (silu → SwiGLU); a plugin’s mlp name selects that builder, but not with num_experts > 0; core’s swiglu, standard_gelu and standard_relu are rejected in favor of silu, gelu and relu

max_seq_len

int

2048

RoPE table length; train.seq_len must be ≤ this

rope_theta

float

10000.0

RoPE frequency base

tie_embeddings

bool

False

share embedding and output-head weight

qk_norm

bool

False

RMSNorm over Q/K per head before RoPE

init_std

float

0.02

weight-init std (GPT-2 / Llama convention)

model_type

str

"transformer"

model registry key

sdpa_backend

str

"auto"

one of "auto", "flash", "efficient", "cudnn", "math"; "flash" takes no attention mask on CUDA, so training runs that build one are refused (see Validation rules)

attention_backend

str

"sdpa"

"sdpa" or "flex"; "flex" routes packed batches (data.pack_sequences) through FlexAttention’s block-sparse mask. Requires train.seq_len ≥ 128 and head_dim ≥ 16

MoE (all defaults produce a dense model)

Field

Type

Default

Purpose

num_experts

int

0

0 → dense; >0 → MoE

moe_top_k

int

2

experts selected per token

moe_frequency

int

1

MoE every N layers (1=all, 2=alternating)

moe_router

str

"softmax_topk"

router registry key

moe_shared_experts

int

0

shared experts that always process every token

moe_aux_loss_weight

float

0.01

coefficient in training loss

moe_capacity_factor

float

0.0

0 → no drop; >0 → cap the routes per expert across its top-k slots (typical 1.25)

moe_sequence_aux_loss_weight

float

0.0

sequence-level balance loss (0 = off)

moe_gradient_scale

bool

False

per-expert gradient normalization

moe_bias_schedule

str

"constant"

"constant", "cosine_decay", "linear_warmup"

moe_packed_experts

bool

False

pack expert weights into one tensor per projection

moe_expert_ffn_multiplier

float

1.0

expert FFN hidden width relative to dense (0.5 → fine-grained)

moe_router_z_loss_weight

float

0.0

router-logit z-loss coefficient (0 = off)

Computed properties: is_moe, head_dim, computed_ffn_hidden_dim, computed_expert_ffn_hidden_dim, mlp_matrices, num_params_estimate.

[train]: TrainConfig

Training-loop hyperparameters. kempnerforge/config/training.py.

Field

Type

Default

Purpose

batch_size

int

8

per-device micro-batch size

seq_len

int

2048

tokens per sequence

max_steps

int

100000

training-loop termination

grad_accum_steps

int

1

microbatches per optimizer step

grad_clip_norm

float

1.0

clip_grad_norm_ cap

seed

int

42

torch/numpy/python RNG seed

data_seed

int | None

None

RNG seed for data and batch order; None → falls back to seed

compile_model

bool

True

wrap the model with torch.compile

mixed_precision

"bf16" | "fp32" | "fp8"

"bf16"

compute dtype, and the master-weight dtype unless fp32_master_weights is set; "fp8" computes in fp8, with bf16 masters unless fp32_master_weights is set; "fp16" is rejected (no loss scaling)

fp32_master_weights

bool

False

keep parameters, gradients and optimizer state in fp32 and compute in param_dtype through FSDP2’s mixed precision; without an FSDP2 wrap (1 GPU, a pp-only mesh) the forward runs under torch.autocast; rejected with mixed_precision = "fp32", and for MoE on a single GPU; see FSDP2 § fp32 master weights

tf32

bool

False

run fp32 matmuls (a frozen fp32 vision encoder, mixed_precision = "fp32") on TF32 tensor cores via torch.set_float32_matmul_precision("high"), applied at startup by training and scripts/eval.py; this also covers the matmuls that run in fp32 on purpose in a bf16 run, so Muon’s Newton–Schulz step moves to TF32 (still more precise than the bf16 that torch.optim.Muon uses); False leaves torch’s setting as it is

grad_reduce_dtype

"fp32" | "bf16"

"fp32"

dtype FSDP2 reduce-scatters (and with replicas all-reduces) the transformer’s and adapter’s gradients in; with "bf16" and grad_accum_steps > 1 every micro-step is reduced (one reduce-scatter per micro-step instead of one per step) so the running sum stays in master_dtype; leaves the storage and optimizer dtype (master_dtype) and the vision encoder (its own grad_reduce_dtype) alone; refused without a data-parallel mesh (one GPU, a pp-only mesh); see FSDP2 § Gradient reduce dtype

activation_checkpointing

"none" | "full" | "selective"

"none"

AC policy

loss_fn

str

"cross_entropy"

loss registry key (or "chunked_cross_entropy")

z_loss_weight

float

0.0

logit-magnitude regularizer (PaLM uses 1e-4)

ce_chunk_size

int

0

chunk size for chunked_cross_entropy (0 → auto 4096)

fp32_cross_entropy

bool

False

compute cross_entropy / chunked_cross_entropy and their gradient in fp32 from bf16 logits, without an fp32 copy of the logits; rejected for any other loss_fn; see Losses § fp32 cross-entropy

shutdown_timeout_sec

float | None

None

seconds a rank has, from the start of its shutdown (the signal, or for a rank the vote stops, the vote), to finish the step in flight, write and flush the emergency checkpoint and tear down, before a forced exit (0 = disabled); unset, a SIGTERM gets three quarters of the KEMPNERFORGE_SHUTDOWN_LEAD_SEC the launch script exports (90 s under the srun scripts, 22.5 s under singlenode.sh), so it fires before the launcher can kill the rank, and 600 s without one, while a SIGUSR1, which no kill follows, gets 600 s; a value you set applies to both, with a warning when it is at or above that lead; the timer starts when the signal handler runs, up to a step after the signal, and never while the main thread is stuck in a call that does not return; see SLURM preemption § Forced-exit timer

nccl_health_check_interval

int

0

NCCL liveness all-reduce every N steps (0 = disabled)

nan_action

"warn" | "skip" | "raise"

"warn"

what the NaN detector does on a step whose loss or gradient norm is NaN / Inf on any rank: "warn" and "skip" log a warning and the loop skips the step (the two differ only in the warning), "raise" raises RuntimeError on every rank; see NaN detection

nan_max_consecutive

int

10

NaN / Inf steps in a row after which the loop stops, without a checkpoint, for a manual rollback; must be positive; see NaN detection § Rollback recommendation

Computed properties: param_dtype (compute dtype), master_dtype (storage dtype: fp32 with fp32_master_weights, otherwise param_dtype), reduce_dtype (from grad_reduce_dtype), is_fp8.

[optimizer]: OptimizerConfig

Optimizer settings. name picks the registry builder; the other fields are shared (AdamW/Lion) or optimizer-specific. kempnerforge/config/optimizer.py.

Field

Type

Default

Purpose

name

str

"adamw"

one of adamw, lion, muon, schedule_free_adamw

lr

float

3e-4

peak learning rate

weight_decay

float

0.1

decoupled weight decay, applied to the group weight_decay_scope selects

betas

tuple[float, float]

(0.9, 0.95)

AdamW / Lion momenta

eps

float

1e-8

numerical safety (AdamW)

fused

bool

True

use fused AdamW when available

muon_momentum

float

0.95

Muon momentum coefficient

muon_ns_steps

int

5

Newton–Schulz iterations for Muon

muon_adam_lr

float | None

None

LR for the parameters Muon leaves to its AdamW fallback; None → same as lr

muon_nesterov

bool

False

Orthogonalize the Nesterov look-ahead instead of the momentum buffer

muon_adjust_lr

"original" | "match_rms_adamw" | "spectral_unclamped"

"original"

Factor on each orthogonalized update

muon_orthogonalize

"local" | "exact"

"local"

Newton–Schulz on each rank’s shard, or on the full matrix

muon_ns_dtype

"fp32" | "bf16"

"fp32"

dtype Newton–Schulz iterates in; the momentum and the applied update keep the parameter dtype, so with bf16 parameters (the default without train.fp32_master_weights) "bf16" changes only that precision, and with fp32 parameters it also halves the "exact" all-to-alls; see Optimizers § Muon

muon_router

bool

False

Orthogonalize MoE router gates with Muon instead of its AdamW fallback

schedule_free_warmup_steps

int

0

internal warmup for schedule-free

weight_decay_scope

"exclude_norms_and_biases" | "all"

"exclude_norms_and_biases"

which parameters are decayed; "all" decays every parameter, as torch.optim.AdamW does by default. A resume that restores optimizer state saved under the other scope is refused

lr_multipliers

dict[str, float]

{}

per-module learning rates: each vlm.module_patterns module listed trains at lr times its multiplier, in its own param groups (see Optimizers § Per-module learning rates). A resume that restores optimizer or scheduler state saved with other multipliers, or other patterns for their modules, is refused

[scheduler]: SchedulerConfig

LR schedule shape and warmup. kempnerforge/config/scheduler.py.

Field

Type

Default

Purpose

name

"cosine" | "linear" | "wsd" | "constant" | "rex" | "none" or a registered scheduler name

"cosine"

scheduler registry key

warmup_steps

int

2000

linear warmup length

warmup_start_factor

float

0.0

LR factor the warmup starts from (torch LinearLR start_factor)

decay_steps

int | None

None

None → decay over remaining steps

min_lr_ratio

float

0.1

floor = lr * min_lr_ratio

stable_steps

int | None

None

WSD: steps at constant LR between warmup and decay

wsd_decay_type

"cosine" | "linear" | "sqrt"

"cosine"

WSD cooldown shape

rex_alpha

float

1.0

REX exponent: (1 - t/T)^alpha

[data]: DataConfig

Single dataset, HuggingFace source, or mixture; optional phase schedule. kempnerforge/config/data.py.

Field

Type

Default

Purpose

dataset_path

str

""

directory of pre-tokenized shards

file_pattern

str

"*.npy"

glob inside dataset_path; each match is read by its own suffix, .bin or .npy

token_dtype

str

""

dtype of raw .bin shards, "uint16" or "uint32"; "" takes tokenized_info.dtype from the metadata.yaml beside them (see Memory-mapped dataset)

tokenizer_path

str

""

path or HF id for the tokenizer

num_workers

int

4

DataLoader workers

pin_memory

bool

True

DataLoader pin memory

prefetch_factor

int

2

DataLoader prefetch factor

hf_dataset_name

str | None

None

HF dataset id (e.g. "wikitext")

hf_dataset_config

str | None

None

HF dataset config (e.g. "wikitext-2-raw-v1")

hf_dataset_split

str

"train"

HF split

hf_dataset_text_field

str

"text"

field to tokenize

hf_dataset_image_field

str

"image"

VLM only: image column

hf_dataset_prompt_field

str

""

VLM only: prompt column ("" = no prompt mask)

hf_image_size

int

224

VLM only: target square image size

hf_max_images

int

1

VLM only: images a document may hold; rows holding more are skipped when the dataset is loaded, and one warning counts them. n ≥ 2 places a document’s images’ tokens before its text and, without packing, lays each document out on its own row of train.seq_len (Joint-Decoder only, not with train.mixed_precision = "fp8" or, under attention_backend = "sdpa", model.sdpa_backend = "flash")

hf_streaming

bool

False

use IterableDataset for large corpora

pack_sequences

bool

False

document-aware packing with cross-doc isolation (feeds doc_ids to attention); on a Joint-Decoder VLM run, packs train.batch_size image-text documents per micro-batch into rows of train.seq_len, each document’s image tokens before its text, positions restarting per document

datasets

list[DatasetSource]

[]

multi-dataset mixture of a text run (overrides dataset_path/hf_dataset_name when non-empty); refused on a VLM run

mix_temperature

float

1.0

weight scaling; 1.0 → as-is, larger → more uniform

phases

list[TrainingPhase]

[]

multi-phase schedule: LR scaling on any run, weight transitions on a datasets mixture

anneal_start_step

int

0

syntactic sugar for a common 2-phase annealing pattern of a datasets mixture (0 = disabled)

anneal_weights

dict[str, float]

{}

per-dataset weights applied at anneal_start_step, keyed by source name

A [video] run builds its dataset from [video], so every hf_* field keeps its default there; see Validation rules.

DatasetSource

Field

Type

Default

Purpose

path

str

""

pre-tokenized directory

weight

float

1.0

relative sampling weight (must be > 0)

name

str

""

name for per-dataset metrics and phase weights, one per source; if empty, the source goes by its path, else its hf_name

hf_name

str

""

HF dataset id

hf_config

str

""

HF dataset config

token_dtype

str

""

dtype of this source’s .bin shards; "" uses data.token_dtype

Either path or hf_name must be set per source, and no two sources may go by one name; see Validation rules.

TrainingPhase

Field

Type

Default

Purpose

start_step

int

0

step at which the phase activates

dataset_weights

dict[str, float]

{}

per-dataset weights for this phase, keyed by source name; needs a datasets mixture

lr_scale

float

1.0

multiplier applied to scheduler LR, with or without a mixture

phases[*].start_step must be strictly increasing; phases and anneal_start_step are mutually exclusive. A run without a datasets mixture, on one source or a VLM run, takes neither a phase’s dataset_weights nor the annealing shortcut, and a VLM run takes no datasets either; every key of the weights must name a source. See Validation rules.

[eval]: EvalConfig

In-loop evaluation. Disabled by default. kempnerforge/config/eval.py.

Field

Type

Default

Purpose

enabled

bool

False

gate in-loop eval

interval

int

1000

eval every N training steps

steps

int

50

eval batches per evaluation; under pipeline parallelism a multiple of train.grad_accum_steps

dataset_path

str

""

pre-tokenized eval shards

file_pattern

str

"*.npy"

glob inside dataset_path

token_dtype

str

""

dtype of raw .bin eval shards, "uint16" or "uint32"; "" takes it from the metadata.yaml beside them, never from data.token_dtype

hf_dataset_name

str | None

None

HF dataset id

hf_dataset_config

str | None

None

HF dataset config

hf_dataset_split

str

"validation"

HF split

If enabled=True, at least one of dataset_path / hf_dataset_name must be set; validate() rejects the combination otherwise.

[distributed]: DistributedConfig

Parallelism dimensions and NCCL settings. kempnerforge/config/distributed.py.

Field

Type

Default

Purpose

dp_shard

int

-1

FSDP shard degree; -1 → auto (use remaining GPUs)

dp_replicate

int

1

replicates the dp_shard groups (HSDP), and every rank in dp_replicate × dp_shard reads its own data; with no dp_shard dimension (it resolves to 1, no TP or EP), FSDP2 shards over dp_replicate instead

tp

int

1

tensor parallel

pp

int

1

pipeline parallel

pp_schedule

"1f1b" | "gpipe" | "interleaved_1f1b"

"1f1b"

pipeline schedule

cp

int

1

context parallel; reserved, not implemented, must be 1 (cp > 1 is rejected at load)

ep

int

1

expert parallel (MoE only)

nccl_timeout_sec

int

1800

Collective timeout, in seconds, of the default process group and every mesh group

backend

str

"cpu:gloo,cuda:nccl"

torch.distributed backend mapping

The product dp_replicate × dp_shard × tp × pp × cp × ep must equal world_size. Methods: validate_world_size(ws), resolve(ws).

[checkpoint]: CheckpointConfig

DCP-based checkpointing. kempnerforge/config/checkpoint.py.

Field

Type

Default

Purpose

dir

str

"checkpoints"

root directory for step_N/ + latest symlink

interval

int

1000

save every N steps (outside any dyn_ckpt_window)

dyn_ckpt_window

DynamicCheckpointWindow | None

None

optional dense save phase; see [checkpoint.dyn_ckpt_window]

async_mode

"disabled" | "async" | "async_with_pinned_mem"

"disabled"

DCP async-save mode

keep_last_n

int

3

retain the most recent N checkpoints (<= 0 keeps all); steps saved by dyn_ckpt_window are always kept

load_path

str | None

None

checkpoint for training to start from while dir holds none (a warm start); once dir has a checkpoint, auto-resume loads that instead and rank 0 warns that load_path is not used, unless it names that checkpoint. scripts/eval.py and scripts/generate.py load load_path first

export_dtype

"float32" | "bfloat16"

"bfloat16"

dtype for HF exports via scripts/convert_checkpoint.py dcp-to-hf when its --dtype flag is not given; the flag wins and also takes float16 (see HuggingFace conversion)

exclude_from_loading

list[str]

[]

state to skip when warm-starting from load_path: "model" and/or "optimizer", or exactly ["optimizer", "train_state"] for a weights-only warm start that loads the model alone and skips train_state.pt (step, scheduler, dataloader position, RNG) and the saved freeze comparison, so a new stage starts fresh from the weights; ignored on a resume, which always restores full state

ignore_freeze_mismatch

bool

False

load a checkpoint whose VLM freeze metadata disagrees with the configured freeze specs, downgrading the error to a warning

ignore_rank_state_mismatch

bool

False

resume when the saved per-rank dataloader/RNG state does not fit this run (changed world size or data-parallel layout, or an unreadable or incomplete envelope), with a warning instead of raising: step, model, optimizer and scheduler continue and the random streams restart fresh. On a changed world size or layout every rank keeps the data position the saved rank 0 reached, or for a stream on the saved data-parallel size the one its own data-parallel rank saved, where the loaders can place it on the new layout, and otherwise every rank starts the data at its first sample; an unreadable or incomplete envelope restarts the data too. On the topology that saved a sound envelope the flag changes nothing: each rank restores its own state, and a position its loader cannot place, such as a changed stream, still raises DataPositionError. A checkpoint saved before per-rank state was recorded gives this check nothing to refuse: without the flag every rank restores rank 0’s data position and RNG state, and with it the resume treats the topology as changed, even the one that saved it, keeping rank 0’s data position by the rule above and restarting the random streams (see Resharding)

ignore_plugins_mismatch

bool

False

resume, or warm start with the train state, from a checkpoint saved with another plugins list, with a warning instead of raising; for plugins that build no part of the model (see Registry)

ignore_extra_model_tensors

bool

False

load a checkpoint that holds model tensors this run’s model does not have, such as a deeper model’s last layers, and leave them unread with a warning instead of refusing it; a tensor of another size, or one this run loads that the checkpoint lacks, is still refused (see Resharding)

[checkpoint.dyn_ckpt_window]: DynamicCheckpointWindow

Opt-in dense save phase. Inside [start, stop] a registered strategy decides which steps to save; outside the window the regular interval cadence applies. Steps saved by the strategy are exempt from keep_last_n retention, so a finite keep_last_n rotates only the later interval checkpoints; the dense window checkpoints are never pruned. Useful for inspecting early-training dynamics at fine granularity.

Field

Type

Default

Purpose

start

int

0

first step of the dense window; 0 captures the initial weights before any training step

stop

int

512

last step of the dense window

strategy

str

"power2"

name of a registered strategy (see below)

Example TOML:

# Off by default, interval cadence only:
[checkpoint]
interval = 1000
keep_last_n = 3

# Opt in with defaults (start=0, stop=512, strategy="power2"):
[checkpoint.dyn_ckpt_window]

# Customize:
[checkpoint.dyn_ckpt_window]
start = 0
stop  = 1024
strategy = "power2"

Dyn_ckpt strategies

A strategy is a Callable[[DynamicCheckpointWindow, int], bool] registered via @registry.register_dyn_ckpt_strategy("name") (see kempnerforge/config/registry.py). The strategy receives the window and the current training step and returns True iff the step should be saved. The registry must be populated before config load, either by kempnerforge itself (the default "power2" is registered in kempnerforge/config/checkpoint.py) or by an explicit import of the user’s module.

Name

Behavior

"power2" (default)

save at start and at every start + 2^k while <= stop (offset-based powers of two; tight near start, doubling thereafter)

[metrics]: MetricsConfig

Logging cadence and backend toggles. The backends are independent, so any combination can be enabled in one run config. kempnerforge/config/metrics.py.

Field

Type

Default

Purpose

log_interval

int

10

log every N steps (stdout + enabled backends)

enable_wandb

bool

False

turn on WandB backend

enable_tensorboard

bool

False

turn on TensorBoard backend

wandb_project

str

"kempnerforge"

WandB project name

wandb_run_name

str | None

None

None → auto-generated

wandb_run_id

str

""

restored from the checkpoint on an auto-resume, never on a checkpoint.load_path warm start; empty = new run

tensorboard_dir

str

"tb_logs"

TB log directory

enable_mlflow

bool

False

turn on MLflow backend (Databricks or local)

mlflow_tracking_uri

str | None

None

tracking URI; None → $MLFLOW_TRACKING_URI, else "databricks"; databricks://<profile> selects a ~/.databrickscfg profile

mlflow_experiment

str | None

None

absolute workspace path on Databricks; None → $MLFLOW_EXPERIMENT/auto

mlflow_run_name

str | None

None

None → auto-generated

mlflow_description

str | None

None

run description (Markdown, the mlflow.note.content tag), set on a new run

mlflow_tags

dict[str, str]

{}

extra run tags, set on a new run after the automatic ones; keys and values must be non-empty strings

mlflow_run_id

str

""

restored from the checkpoint on an auto-resume, never on a checkpoint.load_path warm start; empty = new run

mlflow_log_system_metrics

bool

True

sample CPU/GPU/memory on a background thread

mlflow_system_metrics_interval

float

10.0

seconds between system-metric samples

mlflow_register_checkpoints

bool

False

register each committed checkpoint as an MLflow external model on the background worker; metadata.json records its model_name at save and its model_id once registered; requires enable_mlflow

Credentials never go in config. The auth routes, the URI and experiment resolution, and the bounds on tracking calls are on the MLflow backend page.

[profiling]: ProfilingConfig

torch.profiler window. kempnerforge/config/profiling.py.

Field

Type

Default

Purpose

enable

bool

False

run the profiler during the loop

start_step

int

5

first step recorded

end_step

int

8

last step recorded (must be > start_step)

trace_dir

str

"profiler_traces"

output directory for Chrome/Perfetto traces

[vlm]: VLMConfig

The vision-language architecture: how image tokens join the transformer, the fixed text length, image tiling, and which modules train. A run without [vlm] is a text run. A run with it wraps the transformer in a VLMWrapper, needs [vision_encoder], and takes the default [adapter] when that section is absent. kempnerforge/config/vlm.py.

arch selects the config class. The loader looks it up in the vlm_config registry and builds the [vlm] table as that class, so the table takes the fields below plus the ones its arch adds, and a field of another arch fails to load as an unknown key. When the TOML has a [vlm] section, a --vlm.arch override naming another arch is rejected, so set arch in the TOML (see CLI overrides). Code builds one with VLMConfig.for_arch(arch, **fields).

Field

Type

Default

Purpose

arch

str

"joint_decoder"

vlm_config and modality_strategy registry key: "joint_decoder", "cross_attention", "mot", "moma", or an arch a plugin registers

max_text_len

int

512

text tokens per sample: longer text is truncated to it; without data.pack_sequences or data.hf_max_images != 1, shorter text is also padded to it, so batches keep one shape on every rank; at least 2 (a caption token and its target)

tile_grid

int

0

0 encodes each image as one view; n ≥ 2 cuts it into an n × n grid of crops, in raster order; 1 and negative values are rejected, and a [video] run keeps 0

tile_global

bool

True

a tiled image’s views start with the whole image, so it has n² + 1 views; ignored when tile_grid = 0

freeze

list[FreezeSpec]

[FreezeSpec("vision_encoder", True)]

freeze specs applied when the model is built; the default freezes the vision encoder, and freeze = [] trains every module (see [[vlm.freeze]])

freeze_schedule

list[FreezeStage]

[]

freeze changes that take effect at a step (see [[vlm.freeze_schedule]])

module_patterns

dict[str, list[str]]

transformer, vision_encoder and adapter, plus the arch’s own alias

module aliases that freeze specs and optimizer.lr_multipliers name, each a list of fnmatch patterns over parameter names

The default module_patterns give each alias its module and everything in it:

Alias

Patterns

Arch

transformer

transformer, transformer.*

all

vision_encoder

vision_encoder, vision_encoder.*

all

adapter

adapter, adapter.*

all

cross_attention

transformer.cross_attention_layers, transformer.cross_attention_layers.*

cross_attention

mot

transformer.layers, transformer.layers.*

mot

moma

transformer.layers, transformer.layers.*

moma

A [vlm.module_patterns] table replaces the whole map, so the default aliases it leaves out are gone, including the vision_encoder that the default freeze names. A dotted override sets one alias and keeps the others (see CLI overrides).

The image tokens must fit the sequence. With vision_encoder.num_tokens > 0, model.max_seq_len (when JobConfig is built) and train.seq_len (in JobConfig.validate) must each hold max_text_len plus the image tokens in the residual stream. Those are the tokens the adapter emits per view, times the views per image (one, or tile_grid² plus one with tile_global when tiled; video.max_frames on a [video] run), times the images a document may hold (data.hf_max_images; one clip on a [video] run). Cross-Attention keeps image tokens out of the residual stream, so only max_text_len counts there. The model build checks model.max_seq_len again once the encoder has reported its token count.

JobConfig also limits what each arch runs with (see Validation rules):

  • data.pack_sequences and data.hf_max_images != 1 need joint_decoder.

  • [[data.datasets]], a data phase’s dataset_weights and the annealing shortcut (data.anneal_start_step with data.anneal_weights) are refused for every arch: a VLM run reads its data from the data.hf_* fields or [video] and builds no mixture. A phase’s lr_scale still applies (see Validation rules).

  • distributed.pp > 1 is refused for every arch.

  • distributed.tp > 1 is refused for mot, and for the other arches while sequence parallelism is on (see Validation rules).

  • distributed.ep > 1 is refused for mot and moma.

  • optimizer.lr_multipliers may name only keys of module_patterns.

A minimal VLM run sets [vlm] and [vision_encoder]:

[vlm]
arch = "joint_decoder"
max_text_len = 128

[vision_encoder]
type = "siglip2"
path = "google/siglip2-base-patch16-224"

arch = "joint_decoder": JointDecoderConfig

The image tokens come before the text in the residual stream, and the output head runs on the text positions. No fields beyond the ones above. The only arch that takes data.pack_sequences and data.hf_max_images != 1.

arch = "cross_attention": CrossAttentionConfig

The residual stream carries text only; the image features enter as the keys and values of cross-attention blocks between the transformer blocks. Adds the cross_attention alias to module_patterns.

Field

Type

Default

Purpose

cross_attention_every_n_layers

int

4

a cross-attention block after every n-th transformer block, model.n_layers // n blocks in all, so none when n > model.n_layers; must be positive

cross_attention_n_heads

int

0

attention heads of each cross-attention block; 0 → model.n_heads; must be non-negative

cross_attention_n_kv_heads

int

0

key/value heads of each cross-attention block; 0 → the resolved cross_attention_n_heads; must be non-negative

arch = "mot": MoTConfig

Mixture-of-Transformers: every block holds its own attention projections, norms and FFN for each modality, and one global self-attention runs over the image-then-text sequence. Adds the mot alias, which covers the blocks and leaves out the embedding, the output head and the final norms. MoT trains with distributed.tp = 1 and distributed.ep = 1.

Field

Type

Default

Purpose

mot_modalities

tuple[str, ...]

("image", "text")

modalities with weights of their own; at least two, "image" and "text" among them, without repeats

mot_image_n_heads

int

0

image attention heads; 0 → model.n_heads; must be non-negative, and the model build refuses any count but the text backbone’s

mot_image_n_kv_heads

int

0

image key/value heads; 0 → model.n_kv_heads; must be non-negative, and the model build refuses any count but the text backbone’s

mot_warm_start_from_text

bool

False

copy the dense block weights in mot_warm_start_path into every modality’s copy on a fresh start (no checkpoint in checkpoint.dir and no checkpoint.load_path), or on a load_path warm start whose checkpoint.exclude_from_loading holds "model"

mot_warm_start_path

str

""

a torch.saved state dict of a Joint-Decoder or text-only model, or a dict holding one under "model"; required with mot_warm_start_from_text

arch = "moma": MoMaConfig

Mixture of Modality-Aware Experts: one set of attention projections, and in every block an FFN that sends each token to its modality’s group of experts, where each expert picks the tokens it processes by sigmoid score (expert-choice routing). Adds the moma alias, which covers the blocks. Each expert’s choice depends on the whole batch, so MoMa trains but does not generate (is_generative is False). MoMa needs model.num_experts = 0 and distributed.ep = 1 (JobConfig.validate), and logs a warning with train.compile_model.

Field

Type

Default

Purpose

moma_modalities

tuple[str, ...]

("image", "text")

modality groups; at least two, "image" and "text" among them, without repeats

moma_experts_per_modality

dict[str, int]

{"image": 4, "text": 4}

experts in each group: a positive count for every modality and no other keys

moma_capacity_factor

float

0.0

each expert picks ceil(factor × n) of its group’s n tokens in a batch, at least one and at most n; 0 → 1 / (experts in the group), the balanced load; must be ≥ 0

moma_gumbel_noise

bool

True

add Gumbel noise to the router logits in training

[[vlm.freeze]]: FreezeSpec

Field

Type

Default

Purpose

module

str

required

a key of module_patterns, or an fnmatch pattern over parameter names, which holds a dot or one of *?[

frozen

bool

True

True freezes the parameters it matches, False trains them

Parameter names are the VLMWrapper’s: transformer.*, vision_encoder.* and adapter.*. A bare word that is not a key of module_patterns, such as a misspelled alias, fails when the config loads; a pattern that matches no parameter fails the model build.

[[vlm.freeze_schedule]]: FreezeStage

Field

Type

Default

Purpose

start_step

int

required

step count at which the stage takes effect; 0 applies it from the start; strictly increasing across stages

specs

tuple[FreezeSpec, ...]

required

the freeze specs the stage applies

The build applies freeze. Once the step count reaches a stage’s start_step, its specs apply on top, and for each module the latest stage replaces what freeze or an earlier stage set; a resume applies freeze and every stage up to the step it resumes at. A stage may unfreeze a module that freeze froze: the module trains from that stage on, and its parameters are in the optimizer from the start. Each checkpoint records the freeze in effect at its step. A resume, or a warm start from checkpoint.load_path that loads the train state, compares that record with this run’s freeze at the same step, and fails when a module both name is frozen in one and trained in the other, unless checkpoint.ignore_freeze_mismatch is set. A weights-only warm start (checkpoint.exclude_from_loading = ["optimizer", "train_state"]) skips the comparison and starts at step 0 under this run’s freeze (see [checkpoint]).

Train the adapter alone first, then the transformer too from step 2000. A freeze list replaces the default one, so this one names vision_encoder again to keep the encoder frozen:

[vlm]
arch = "joint_decoder"

[[vlm.freeze]]
module = "vision_encoder"

[[vlm.freeze]]
module = "transformer"

[[vlm.freeze_schedule]]
start_step = 2000
specs = [{ module = "transformer", frozen = false }]

[vision_encoder]
type = "siglip2"
path = "google/siglip2-base-patch16-224"

[vision_encoder]: VisionEncoderConfig

The image encoder of a VLM run, which turns each image, tile or frame into patch features for the adapter. [vlm] requires this section; a run without [vlm] does not use it. kempnerforge/config/vision.py.

Field

Type

Default

Purpose

type

str

"random"

vision_encoder registry key: "random" (a stub that needs no weights and returns random features, for tests and smoke runs), "siglip2" or "clip" (pretrained Hugging Face towers), or an encoder a plugin registers

path

str

""

Hub id or local directory of the pretrained model; JobConfig.validate requires it for "siglip2" and "clip", and "random" ignores it

feature_dim

int

0

width of the features the encoder returns; 0 → read at build time (the Hugging Face tower config’s hidden_size, or 768 for "random"); must be non-negative

num_tokens

int

0

tokens the encoder returns per image; 0 → read at build time ((image_size // patch_size)² from the Hugging Face tower config, without CLIP’s class token, or 16 for "random"); a positive value lets the config check the sequence length (see [vlm]); must be non-negative

mixed_precision

"bf16" | "fp32" | None

None

dtype the encoder computes in, independent of train.mixed_precision, while its parameters keep the dtype they were loaded in; None (left out of the TOML) keeps the default: an encoder FSDP2 wraps computes in the language model’s compute dtype, and one it does not wrap in its loaded dtype, except on one GPU with train.fp32_master_weights, where the forward runs under torch.autocast and the encoder’s matmuls run in bf16 (see FSDP2 and fp32 master weights)

drop_pooling_head

bool

False

remove a SigLIP tower’s attention-pooling head, whose pooled output the encoder never returns; only a type whose builder declares a drop_pooling_head parameter takes it ("siglip2" among the built-in ones), and any other is refused when the config loads; the build refuses a tower without a pooling head

On a VLM run, a Hugging Face encoder with feature_dim or num_tokens above 0 logs a warning when JobConfig is built: the values replace the ones the encoder reads from its model and can disagree with them. Leave both at 0 unless the model’s config has no hidden_size, which the build then asks to be given as feature_dim.

drop_pooling_head changes the encoder’s tensors, which a checkpoint holds whether the encoder trains or not. Loading the model from a checkpoint saved with the head into a run that drops it is refused unless checkpoint.ignore_extra_model_tensors is set, which leaves the head’s tensors unread. The other way round, from a checkpoint saved without the head into a run that keeps it, is refused, and that flag does not cover it (see [checkpoint]).

[adapter]: AdapterConfig

The VLM connector that maps vision-encoder features into the transformer’s embedding space. A run that sets [vlm] without [adapter] gets these defaults. kempnerforge/config/adapter.py.

Field

Type

Default

Used by

Purpose

type

str

"mlp_2layer"

all

adapter registry key: mlp_2layer and linear keep the token count, avgpool and attentional_pool pool it

hidden_dim

int

0

mlp_2layer, avgpool

MLP hidden width. mlp_2layer: 0 means out_dim. avgpool: a positive width makes the head after the pool a 2-layer MLP, normed first when pre_norm is set; 0 keeps the single Linear. Must be non-negative

activation

str

"gelu"

mlp_2layer; avgpool with hidden_dim > 0

"gelu", "silu" or "relu" between the two MLP projections

pre_norm

str

""

mlp_2layer; avgpool with hidden_dim > 0

norm-registry key for a norm ahead of the MLP, over the vision features (mlp_2layer) or the pooled features (avgpool); "" builds none

pool_window

int

2

avgpool, attentional_pool

pooling window side, e.g. 2 for 2×2; must be positive

pool_heads

int

16

attentional_pool

attention heads; must be positive, and divide the vision feature dim when the adapter is built

A field outside the selected adapter’s “Used by” entries must keep its default, or the config fails to load with an error naming the field and the adapter type. The column follows each adapter’s builder parameters, which avgpool narrows by hidden_dim with the accepts it registers; a plugin adapter’s come from its own builder (see Registry).

An avgpool connector with a 2×2 window and an RMSNorm + MLP head as wide as its input (here a 1152-wide encoder):

[adapter]
type = "avgpool"
pool_window = 2
hidden_dim = 1152
pre_norm = "rmsnorm"

hidden_dim picks the avgpool head, and the head fixes the adapter’s checkpoint keys. hidden_dim = 0 builds the single Linear, saved as adapter.proj.weight and adapter.proj.bias. A positive hidden_dim builds the MLP head, saved as adapter.proj.proj1.* and adapter.proj.proj2.*, plus adapter.proj.ln_q.* when pre_norm is set. A checkpoint loads only into the head it was saved with: the other head’s load is refused before any tensor is read, naming the parameters of that head the checkpoint lacks. To resume a checkpoint saved with the single Linear, set hidden_dim = 0 and leave activation and pre_norm at their defaults.

A command-line override sets a value and never restores a default, so switching adapter.type on the command line keeps every other field the TOML sets. Reset the ones the new type does not use in the same command; an empty value sets the empty string. For a TOML with type = "mlp_2layer", hidden_dim = 2048 and pre_norm = "rmsnorm":

--adapter.type=attentional_pool --adapter.hidden_dim=0 --adapter.pre_norm=

The check reads the TOML with the overrides laid over it, so a field and the type that uses it may sit in different layers: a TOML with type = "attentional_pool" and hidden_dim = 1152 loads with --adapter.type=avgpool, which uses hidden_dim.

[video]: VideoConfig

Video input for a VLM run: the job trains on clips, each decoded into frames that the vision encoder and adapter process like images. Requires [vlm], and so [vision_encoder]. Decoding needs PyAV (uv sync --group video); see Train on video. kempnerforge/config/video.py.

Field

Type

Default

Purpose

data_root

str

""

root directory of the on-disk corpus

dataset_type

str

"webvid"

video_dataset registry key: "webvid" (WebVid-style CSV manifests and .mp4 files) or a dataset a plugin registers

dataset_name

str

"webvid-10M"

corpus within the style; "webvid" reads its manifests under <data_root>/raw/<dataset_name>/data/

sampling_policy

str

"uniform"

sampling_policy registry key: "uniform" (about fps frames per second, clamped to [min_frames, max_frames], spread evenly from the first frame to the last) or a policy a plugin registers

split

str

"train"

"train" or "validation"

max_samples

int

0

read at most this many manifest entries (0 = all); must be non-negative

max_frames

int

16

frames per clip: a clip with fewer is padded to this many, and the padding is masked; must be at least 1

min_frames

int

4

fewest frames the policy samples from a clip of known, positive length ("uniform" takes one frame when the length is unknown); at least 1 and at most max_frames

fps

float

2.0

target sampling rate in frames per second; must be positive

frame_size

int

224

side, in pixels, of the square each frame is resized to; must be positive

prompt

str

""

instruction placed before every caption and masked from the loss; must leave room in vlm.max_text_len for a caption token, checked when the dataset is built

A [video] run keeps vlm.tile_grid = 0, and takes neither data.pack_sequences nor data.hf_max_images != 1. It builds its dataset from [video], and from [data] reads tokenizer_path and the loader settings (num_workers, pin_memory, prefetch_factor). JobConfig.validate refuses a data.hf_* field set away from its default (see Validation rules) and, as on every VLM run, [[data.datasets]], a data phase’s dataset_weights and the annealing shortcut, since the run builds no mixture; a phase’s lr_scale still applies (see Validation rules). The residual stream holds max_frames times the adapter’s tokens per frame, none under Cross-Attention, and with vision_encoder.num_tokens > 0 the config checks that they fit with vlm.max_text_len (see [vlm]). The training setup refuses model.sdpa_backend = "flash" on CUDA for a Joint-Decoder or MoMa video run, whose padded frames need an attention mask.

Eight frames of 49 tokens each (SigLIP2’s 14×14 patches pooled 2×2) and 64 text tokens take 456 positions:

[model]
max_seq_len = 576

[train]
seq_len = 576

[vlm]
max_text_len = 64

[vision_encoder]
type = "siglip2"
path = "google/siglip2-base-patch16-224"

[adapter]
type = "avgpool"
pool_window = 2

[video]
data_root = "/data/webvid"
max_frames = 8