kempnerforge.config¶
Configuration system for KempnerForge.
- class kempnerforge.config.CheckpointConfig[source]¶
Bases:
objectCheckpointing settings.
- dyn_ckpt_window: DynamicCheckpointWindow | None = None¶
- async_mode: AsyncCheckpointMode = 'disabled'¶
- should_save(step)[source]¶
Whether to write a checkpoint at
step.Inside
dyn_ckpt_window: the registered strategy decides (default"power2"saves atstartand eachstart + 2^kwhile<= stop). Outside the window: everyintervalsteps. Dynamic milestones are exempt fromkeep_last_n(seeCheckpointManager._cleanup).
- is_dynamic_milestone(step)[source]¶
True if
stepis a milestone of the configureddyn_ckpt_window.CheckpointManager._cleanupexcludes these fromkeep_last_nso the dense early-window checkpoints survive a finite retention.
- __init__(dir='checkpoints', interval=1000, dyn_ckpt_window=None, async_mode=AsyncCheckpointMode.disabled, keep_last_n=3, load_path=None, export_dtype='bfloat16', exclude_from_loading=<factory>, ignore_freeze_mismatch=False, ignore_rank_state_mismatch=False, ignore_plugins_mismatch=False, ignore_extra_model_tensors=False)¶
- Parameters:
dir (str)
interval (int)
dyn_ckpt_window (DynamicCheckpointWindow | None)
async_mode (AsyncCheckpointMode)
keep_last_n (int)
load_path (str | None)
export_dtype (Literal['float32', 'bfloat16'])
ignore_freeze_mismatch (bool)
ignore_rank_state_mismatch (bool)
ignore_plugins_mismatch (bool)
ignore_extra_model_tensors (bool)
- Return type:
None
- class kempnerforge.config.DataConfig[source]¶
Bases:
objectData pipeline settings.
token_dtypeis the integer type of the raw.bintoken shards,"uint16"or"uint32", fordataset_pathand everydatasetssource that does not set its own. Left empty, themetadata.yamlnext to the shards decides, asMemoryMappedDatasetdescribes..npyshards carry their dtype in their header and ignore it.- datasets: list[DatasetSource]¶
- phases: list[TrainingPhase]¶
- mixture_weight_fields()[source]¶
The settings that reweight a
[[data.datasets]]mixture, named for an error.Each phase that sets
dataset_weights, andanneal_start_stepwithanneal_weightswhen the two make a phase. A run without a mixture refuses them.
- unknown_mixture_weight_keys()[source]¶
The keys of each setting
mixture_weight_fieldslists that name no source.Maps
data.phases[i].dataset_weights, anddata.anneal_weightswhenanneal_start_stepmakes it a phase, to its sorted keys that match noDatasetSource.mixture_nameindatasets. A setting whose keys all match is left out, so the result is empty when every key names a source.
- duplicate_mixture_names()[source]¶
Each
DatasetSource.mixture_namethat two or moredatasetssources go by.Maps each such name, in the order the names first appear, to the indices of its sources in
datasets. The result is empty when every source has a name of its own.
- __init__(dataset_path='', file_pattern='*.npy', token_dtype='', tokenizer_path='', num_workers=4, pin_memory=True, prefetch_factor=2, hf_dataset_name=None, hf_dataset_config=None, hf_dataset_split='train', hf_dataset_text_field='text', hf_dataset_image_field='image', hf_dataset_prompt_field='', hf_image_size=224, hf_max_images=1, hf_streaming=False, pack_sequences=False, datasets=<factory>, mix_temperature=1.0, phases=<factory>, anneal_start_step=0, anneal_weights=<factory>)¶
- Parameters:
dataset_path (str)
file_pattern (str)
token_dtype (str)
tokenizer_path (str)
num_workers (int)
pin_memory (bool)
prefetch_factor (int)
hf_dataset_name (str | None)
hf_dataset_config (str | None)
hf_dataset_split (str)
hf_dataset_text_field (str)
hf_dataset_image_field (str)
hf_dataset_prompt_field (str)
hf_image_size (int)
hf_max_images (int)
hf_streaming (bool)
pack_sequences (bool)
datasets (list[DatasetSource])
mix_temperature (float)
phases (list[TrainingPhase])
anneal_start_step (int)
- Return type:
None
- class kempnerforge.config.DistributedConfig[source]¶
Bases:
objectParallelism dimensions and distributed settings.
- pp_schedule: PipelineSchedule = '1f1b'¶
- validate_world_size(world_size)[source]¶
Validate that parallelism dimensions match world size.
- Parameters:
world_size (int)
- Return type:
None
- resolve(world_size)[source]¶
Return a copy with dp_shard resolved to a concrete value.
- Parameters:
world_size (int)
- Return type:
- __init__(dp_shard=-1, dp_replicate=1, tp=1, pp=1, pp_schedule=PipelineSchedule.schedule_1f1b, cp=1, ep=1, nccl_timeout_sec=1800, backend='cpu:gloo,cuda:nccl')¶
- class kempnerforge.config.EvalConfig[source]¶
Bases:
objectEvaluation pipeline settings (disabled by default).
token_dtypeis the integer type of the raw.bineval shards, asDataConfig.token_dtypeis for the training shards.- __init__(enabled=False, interval=1000, steps=50, dataset_path='', file_pattern='*.npy', token_dtype='', hf_dataset_name=None, hf_dataset_config=None, hf_dataset_split='validation')¶
- class kempnerforge.config.JobConfig[source]¶
Bases:
objectTop-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 atNoneand 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¶
- train: TrainConfig¶
- optimizer: OptimizerConfig¶
- scheduler: SchedulerConfig¶
- data: DataConfig¶
- eval: EvalConfig¶
- distributed: DistributedConfig¶
- checkpoint: CheckpointConfig¶
- metrics: MetricsConfig¶
- profiling: ProfilingConfig¶
- vision_encoder: VisionEncoderConfig | None = None¶
- adapter: AdapterConfig | None = None¶
- video: VideoConfig | None = None¶
- property images_per_document: int¶
the image cap, or one clip on a video run.
- Type:
Images one document may hold
- property views_per_sample: int¶
a clip’s frames, a tiled image’s views, or one.
- Type:
Images the encoder sees per sample
- masks_frames_in_backend_attention()[source]¶
Whether a frame mask reaches self-attention that runs under
model.sdpa_backend.The modality strategy, which the vlm section’s
archpicks, 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 whosearchan override changed is judged by both.- Return type:
- check_flash_attention_masks()[source]¶
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 wheremasks_frames_in_backend_attentionsays 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 toAttention, such as video evaluation’s frame mask under Joint-Decoder or MoMa, raises theValueErrorfromAttention.forward.- Raises:
ValueError – The run would train with
sdpa_backend="flash"and a mask.- Return type:
None
- validate(world_size=1, *, training=True)[source]¶
Run cross-config validations that depend on the world size.
training=Falseskips 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).
- __init__(model=<factory>, train=<factory>, optimizer=<factory>, scheduler=<factory>, data=<factory>, eval=<factory>, distributed=<factory>, checkpoint=<factory>, metrics=<factory>, profiling=<factory>, vision_encoder=None, adapter=None, vlm=None, video=None, plugins=<factory>)¶
- Parameters:
model (ModelConfig)
train (TrainConfig)
optimizer (OptimizerConfig)
scheduler (SchedulerConfig)
data (DataConfig)
eval (EvalConfig)
distributed (DistributedConfig)
checkpoint (CheckpointConfig)
metrics (MetricsConfig)
profiling (ProfilingConfig)
vision_encoder (VisionEncoderConfig | None)
adapter (AdapterConfig | None)
vlm (VLMConfig | None)
video (VideoConfig | None)
- Return type:
None
- class kempnerforge.config.MetricsConfig[source]¶
Bases:
objectLogging and metrics settings.
- resolve_mlflow_tracking_uri()[source]¶
The tracking URI in force: the field, else $MLFLOW_TRACKING_URI, else Databricks.
- Return type:
- __init__(log_interval=10, enable_wandb=False, enable_tensorboard=False, enable_mlflow=False, wandb_project='kempnerforge', wandb_run_name=None, wandb_run_id='', tensorboard_dir='tb_logs', mlflow_tracking_uri=None, mlflow_experiment=None, mlflow_run_name=None, mlflow_description=None, mlflow_tags=<factory>, mlflow_run_id='', mlflow_log_system_metrics=True, mlflow_system_metrics_interval=10.0, mlflow_register_checkpoints=False)¶
- Parameters:
log_interval (int)
enable_wandb (bool)
enable_tensorboard (bool)
enable_mlflow (bool)
wandb_project (str)
wandb_run_name (str | None)
wandb_run_id (str)
tensorboard_dir (str)
mlflow_tracking_uri (str | None)
mlflow_experiment (str | None)
mlflow_run_name (str | None)
mlflow_description (str | None)
mlflow_run_id (str)
mlflow_log_system_metrics (bool)
mlflow_system_metrics_interval (float)
mlflow_register_checkpoints (bool)
- Return type:
None
- class kempnerforge.config.ModelConfig[source]¶
Bases:
objectArchitecture hyperparameters for a transformer model.
activationis anActivationmember, or the name of an MLP a plugin registered undermlp. Core’s ownmlpkeys (CORE_MLP_KEY_ACTIVATIONS) are rejected in favor of the activation that selects each, and a plugin’s MLP is rejected withnum_experts > 0: the MoE expert kernels compute core’s SwiGLU or standard MLP.- activation: Activation = 'silu'¶
- property tp_sequence_parallel: bool¶
Whether tensor parallelism runs this model with
SequenceParallel.apply_tensor_parallelshards activations along the sequence between blocks unless the embeddings are tied, since sharding the output head’s columns would also shard the shared embedding weight, or the model is MoE, since boolean indexing in expert dispatch breaks sequence-sharded DTensors. Pipeline stages also run without it; that depends on the stage, not on this config.
- property head_dim: int¶
Per-head attention width.
Derived rather than stored so a later
dim/n_headschange (a TOML or CLI overlay onto a default config) cannot leave a stale value behind.head_dim_overridedecouples it fromdim.
FFN hidden dimension, rounded to nearest multiple of 256 for hardware efficiency.
Per-expert FFN hidden dim =
computed_ffn_hidden_dim*moe_expert_ffn_multiplier.Rounded to a multiple of 16 for tensor-core alignment. With the default multiplier 1.0 this equals
computed_ffn_hidden_dim(zero behavior change); set 0.5 for fine-grained experts so top-2 routing matches the dense FFN’s activated FLOPs (2 * F/2 = F). Routed experts are this wide (build_moe and MoMa’s ExpertChoiceMoE); build_moe’s shared experts are one MLPmoe_shared_expertstimes this wide.
- property mlp_matrices: int¶
Weight matrices in each MLP the model builds, dense layers and experts alike.
Three for
silu, which builds SwiGLU (gate, up and down projections), and two forgeluandrelu, which build the standard MLP (up and down). An MLP a plugin registers under another name is counted as gated, three matrices, whatever it builds, so the estimates that use this are exact for the built-in activations only.
- property num_params_estimate: int¶
Rough total parameter count estimate (excluding embedding if tied).
For MoE models, counts all expert parameters (total, not active). Each MLP counts
mlp_matricesweight matrices.
- __init__(dim=4096, n_layers=32, n_heads=32, n_kv_heads=None, head_dim_override=0, vocab_size=32000, ffn_dim_multiplier=1.0, ffn_hidden_dim=None, norm_type=NormType.rmsnorm, norm_eps=1e-05, activation=Activation.silu, max_seq_len=2048, rope_theta=10000.0, tie_embeddings=False, qk_norm=False, init_std=0.02, model_type='transformer', sdpa_backend='auto', attention_backend='sdpa', num_experts=0, moe_top_k=2, moe_frequency=1, moe_router='softmax_topk', moe_shared_experts=0, moe_aux_loss_weight=0.01, moe_capacity_factor=0.0, moe_sequence_aux_loss_weight=0.0, moe_gradient_scale=False, moe_bias_schedule='constant', moe_packed_experts=False, moe_expert_ffn_multiplier=1.0, moe_router_z_loss_weight=0.0)¶
- Parameters:
dim (int)
n_layers (int)
n_heads (int)
n_kv_heads (int | None)
head_dim_override (int)
vocab_size (int)
ffn_dim_multiplier (float)
ffn_hidden_dim (int | None)
norm_type (NormType)
norm_eps (float)
activation (Activation)
max_seq_len (int)
rope_theta (float)
tie_embeddings (bool)
qk_norm (bool)
init_std (float)
model_type (str)
sdpa_backend (str)
attention_backend (str)
num_experts (int)
moe_top_k (int)
moe_frequency (int)
moe_router (str)
moe_shared_experts (int)
moe_aux_loss_weight (float)
moe_capacity_factor (float)
moe_sequence_aux_loss_weight (float)
moe_gradient_scale (bool)
moe_bias_schedule (str)
moe_packed_experts (bool)
moe_expert_ffn_multiplier (float)
moe_router_z_loss_weight (float)
- Return type:
None
- class kempnerforge.config.OptimizerConfig[source]¶
Bases:
objectOptimizer settings.
- __init__(name='adamw', lr=0.0003, weight_decay=0.1, betas=(0.9, 0.95), eps=1e-08, fused=True, muon_momentum=0.95, muon_ns_steps=5, muon_adam_lr=None, muon_nesterov=False, muon_adjust_lr='original', muon_orthogonalize='local', muon_ns_dtype='fp32', muon_router=False, schedule_free_warmup_steps=0, weight_decay_scope='exclude_norms_and_biases', lr_multipliers=<factory>)¶
- Parameters:
name (str)
lr (float)
weight_decay (float)
eps (float)
fused (bool)
muon_momentum (float)
muon_ns_steps (int)
muon_adam_lr (float | None)
muon_nesterov (bool)
muon_adjust_lr (str)
muon_orthogonalize (str)
muon_ns_dtype (str)
muon_router (bool)
schedule_free_warmup_steps (int)
weight_decay_scope (str)
- Return type:
None
- class kempnerforge.config.SchedulerConfig[source]¶
Bases:
objectLearning rate schedule settings.
- name: SchedulerType = 'cosine'¶
- __init__(name=SchedulerType.cosine, warmup_steps=2000, warmup_start_factor=0.0, decay_steps=None, min_lr_ratio=0.1, stable_steps=None, wsd_decay_type='cosine', rex_alpha=1.0)¶
- class kempnerforge.config.TrainConfig[source]¶
Bases:
objectTraining hyperparameters.
"fp16"stays in themixed_precisionLiteralonly 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_actionandnan_max_consecutiveset the training loop’sNaNDetector: its response to a NaN/Inf step, and how many in a row stop the loop.grad_reduce_dtypeis 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"andgrad_accum_steps > 1every 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 inmaster_dtypeand 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 takesvision_encoder.grad_reduce_dtypeinstead.JobConfig.validaterefuses"bf16"on a run FSDP2 does not wrap (one GPU, a pp-only mesh), since nothing would be reduced.shutdown_timeout_secbounds a rank’s shutdown with a forced exit;0disables it, and left unset aSIGTERM’s fits the launch script’s signal lead (seekempnerforge.resilience.signal_handler.resolve_shutdown_timeouts).- activation_checkpointing: ActivationCheckpointing = 'none'¶
- property param_dtype: 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
master_dtype, which is fp32 withfp32_master_weights. A config switched to"fp16"after construction skips__post_init__, so"fp16"raises the sameValueErrorhere.
- property master_dtype: torch.dtype¶
Dtype the parameters, their gradients and the optimizer state are kept in.
- property reduce_dtype: torch.dtype¶
Dtype FSDP2 reduces the transformer’s and adapter’s gradients in.
- property reduces_every_micro_step: bool¶
Whether the transformer’s FSDP2 units reduce every micro-step, as a pipeline stage.
- __init__(batch_size=8, seq_len=2048, max_steps=100000, grad_accum_steps=1, grad_clip_norm=1.0, seed=42, data_seed=None, compile_model=True, mixed_precision='bf16', fp32_master_weights=False, tf32=False, grad_reduce_dtype='fp32', activation_checkpointing=ActivationCheckpointing.none, loss_fn='cross_entropy', z_loss_weight=0.0, ce_chunk_size=0, fp32_cross_entropy=False, shutdown_timeout_sec=None, nccl_health_check_interval=0, nan_action='warn', nan_max_consecutive=10)¶
- Parameters:
batch_size (int)
seq_len (int)
max_steps (int)
grad_accum_steps (int)
grad_clip_norm (float)
seed (int)
data_seed (int | None)
compile_model (bool)
mixed_precision (Literal['bf16', 'fp16', 'fp32', 'fp8'])
fp32_master_weights (bool)
tf32 (bool)
grad_reduce_dtype (Literal['fp32', 'bf16'])
activation_checkpointing (ActivationCheckpointing)
loss_fn (str)
z_loss_weight (float)
ce_chunk_size (int)
fp32_cross_entropy (bool)
shutdown_timeout_sec (float | None)
nccl_health_check_interval (int)
nan_action (Literal['warn', 'skip', 'raise'])
nan_max_consecutive (int)
- Return type:
None
- property effective_data_seed: int¶
Seed for data shuffling / batch composition.
Falls back to
seedwhendata_seedis unset, so existing configs reproduce their current trajectory. Kept independent fromseed(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.
- kempnerforge.config.load_config(config_path=None, cli_args=None)[source]¶
Load a JobConfig from optional TOML file + CLI overrides.
The returned config has all sub-config __post_init__ validations applied. They run once, on the TOML with the CLI overrides laid over it, so a check that compares fields reads them whichever layer sets each. Each section is built from its field defaults and the merged layers, so a default that
__post_init__derives from other fields, such asmodel.n_kv_headsfrommodel.n_heads, follows them whichever layer sets them. Cross-config validation (e.g., parallelism vs world_size) requires calling config.validate(world_size=…) separately at distributed setup time.Modules named by the top-level
pluginskey are imported before the overlay, so components they register are visible to those validations.
Modules
Adapter (connector) configuration. |
|
Checkpoint configuration. |
|
Data pipeline configuration. |
|
Distributed parallelism configuration. |
|
Evaluation configuration. |
|
Top-level job configuration aggregating all sub-configs. |
|
Config loading: TOML files → dataclass configs with CLI overrides. |
|
Metrics configuration. |
|
Model architecture configuration. |
|
Optimizer configuration. |
|
Profiling configuration. |
|
Central registry for named components. |
|
LR scheduler configuration. |
|
Backward-compatible re-exports. |
|
Training configuration. |
|
Video input configuration. |
|
Vision-encoder configuration. |
|
VLM (vision-language model) configuration. |