Megatron backend configuration reference

August 12, 2026 · View on GitHub

This page lists the flat configuration keys exposed by Primus when framework: megatron. Unless a section says otherwise, values are the defaults from primus/configs/modules/megatron/trainer_base.yaml and related model presets. The effective pretraining preset is pre_trainer.yaml, which extends trainer_base.yaml and overrides several high-impact training defaults.

Where parameters live. Set overrides under modules.pre_trainer.overrides: in your experiment YAML. Model architecture keys usually come from models.<role>.overrides: (or your chosen model preset), but the same names map to Megatron’s argparse namespace either way.

Presets.

  • Module presets: primus/configs/modules/megatron/ (the main pretraining bundle is pre_trainer.yaml, which extends trainer_base.yaml and Primus Megatron add-ons).
  • Model presets: primus/configs/models/megatron/ (for example language_model.yaml).

Mapping to Megatron-LM. Keys are passed through 1:1 to Megatron’s training arguments (same names as argparse / Namespace). Primus builds that namespace with MegatronArgBuilder.

Upstream reference. Full flag semantics and newer options are defined in Megatron-LM: megatron/training/arguments.py.

Example (experiment YAML)

framework: megatron

modules:
  pre_trainer:
    overrides:
      global_batch_size: 256
      train_iters: 50000
      tensor_model_parallel_size: 2

models:
  pre_train:
    overrides:
      hidden_size: 2048
      num_layers: 32

1. Base module parameters

Source: primus/configs/modules/module_base.yaml (merged into Megatron presets; trainer_base.yaml sets trainable: true).

ParameterDefaultDescription
trainabletrueWhen true, this module participates in training workflows. (module_base.yaml alone defaults to false; Megatron trainer_base.yaml overrides to true.)
sink_levelnullLog level for the structured sink (Primus module plumbing); null uses framework default.
file_sink_levelDEBUGMinimum level for file-backed logging.
stderr_sink_levelINFOMinimum level for stderr logging.

2. Training and batching

Source: primus/configs/modules/megatron/trainer_base.yaml; effective pre_trainer.yaml overrides are noted where they differ.

ParameterDefaultDescription
yaml_cfgnullReserved; not supported as a Megatron override in this preset.
specnullOptional trainer spec hook (unused in defaults).
micro_batch_size2Samples per microbatch per data-parallel rank (per forward/backward step before gradient accumulation).
batch_sizenullDeprecated; use micro_batch_size / global_batch_size.
global_batch_size128 (16 in pre_trainer.yaml)Total batch size across the data-parallel world (before or after splitting, per Megatron semantics).
rampup_batch_sizenullOptional batch-size ramp schedule string / config.
decrease_batch_size_if_neededfalseAllow shrinking batch if memory is insufficient.
check_for_nan_in_loss_and_gradtrueAbort on NaNs in loss or gradients.
check_for_spiky_lossfalseDetect abnormal loss spikes.
check_for_large_gradsfalseDetect abnormally large gradients.
make_vocab_size_divisible_by128Pads vocabulary size for efficient kernels / partitioning.
exit_signal_handlerfalseInstall handlers for graceful shutdown signals.
exit_duration_in_minsnullStop training after this many minutes.
exit_intervalnullExit after this many iterations (if set).
onnx_safenullONNX export compatibility tweaks.
bert_binary_headtrueUse BERT binary classification head when applicable.
use_flash_attnfalse (true in pre_trainer.yaml)Prefer FlashAttention kernels when available.
seed1234RNG seed for reproducibility.
data_parallel_random_initfalseRandom init that varies across data-parallel ranks.
init_method_xavier_uniformfalseUse Xavier uniform for some weights.
test_modefalseLightweight test path (fewer steps / checks).
train_itersnull (1000 in pre_trainer.yaml)Total training iterations (mutually exclusive with sample-based stopping in typical setups).
train_samplesnullTotal training samples (when using sample-based training).
eval_iters32 (0 in pre_trainer.yaml)Validation iterations per eval.
eval_interval2000 (1000 in pre_trainer.yaml)Run validation every this many iterations.
full_validationfalseRun a full pass over validation data.
multiple_validation_setsfalseMultiple validation datasets / passes.
skip_trainfalseOnly run eval / test, no training updates.
train_sync_intervalnullPeriodic distributed sync barrier for debugging.
adlr_autoresumefalseADLR autoresume integration.
adlr_autoresume_interval1000Autoresume checkpoint interval.
manual_gcfalseForce Python GC on a schedule.
manual_gc_interval1GC every N steps when manual_gc is enabled.
manual_gc_evalfalseRun manual GC during evaluation.
mask_typerandomMasking strategy for MLM / similar objectives.
mask_factor1.0Masking strength multiplier.
iter_per_epoch1250Iterations interpreted as one “epoch” for logging.

3. Mixed precision

Source: trainer_base.yaml.

ParameterDefaultDescription
fp16falseEnable FP16 mixed precision training.
bf16trueEnable BF16 mixed precision training.
grad_reduce_in_bf16falseAll-reduce gradients in BF16 (saves bandwidth).
calculate_per_token_lossfalseNormalize loss per token instead of per sample.
loss_scalenullStatic loss scale for FP16; null uses dynamic scaling.
initial_loss_scale4294967296Initial dynamic loss scale.
min_loss_scale1.0Floor for dynamic loss scale.
loss_scale_window1000Window for dynamic loss scaling updates.
hysteresis2Hysteresis steps for loss-scale decreases.
accumulate_allreduce_grads_in_fp32falseAccumulate and reduce gradients in FP32.
fp16_lm_cross_entropyfalseCompute LM cross-entropy in FP16.
fp8nullFP8 recipe selection (e4m3, hybrid, etc.); null disables.
fp8_margin0FP8 scaling margin.
fp8_recipedelayedFP8 recipe variant (e.g. delayed scaling).
fp8_interval1Deprecated FP8 interval (kept for compatibility).
fp8_amax_history_len1024History length for FP8 amax statistics.
fp8_amax_compute_algo"max"How to combine amax history (max, etc.).
fp8_wgradtrueRun weight gradients in FP8 where supported.
fp8_param_gatherfalseFP8 parameter gather for distributed optimizer paths.
te_rng_trackerfalseTransformer Engine RNG tracker for FP8.
inference_rng_trackerfalseSeparate RNG tracker for inference FP8.
fp4nullFP4 mode; null disables.
fp4_recipenvfp4FP4 recipe name.
fp4_paramfalseStore parameters in FP4.
first_last_layers_bf16falseKeep first/last layers in BF16 for stability.
num_layers_at_start_in_bf161Count of early layers forced to BF16 when enabled.
num_layers_at_end_in_bf161Count of final layers forced to BF16 when enabled.
no_fp8_weight_transpose_cachefalsePrimus: disable FP8 weight transpose cache (see primus_megatron_module.yaml).

4. Optimizer and learning rate

Source: trainer_base.yaml.

ParameterDefaultDescription
optimizeradamOptimizer family (adam, sgd, etc.).
lr2.5e-4 (2.0e-05 in pre_trainer.yaml)Peak learning rate.
lr_decay_stylecosineLR decay schedule (cosine, linear, constant, WSD, etc.).
lr_decay_itersnullDecay duration in iterations.
lr_decay_samplesnullDecay duration in samples.
lr_warmup_fractionnullWarmup as a fraction of total train steps.
lr_warmup_iters0 (40 in pre_trainer.yaml)Linear warmup steps.
lr_warmup_samples0Warmup in samples.
lr_warmup_init0.0LR at the start of warmup.
min_lr2.5e-5 (0.0 in pre_trainer.yaml)Minimum LR after decay.
lr_wsd_decay_styleexponentialWeight-decay schedule style for WSD when used.
lr_wsd_decay_samplesnullWSD decay window in samples.
lr_wsd_decay_itersnullWSD decay window in iterations.
head_lr_mult1.0LR multiplier for attention/head modules when supported.
weight_decay0.01 (0.0 in pre_trainer.yaml)AdamW / L2-style weight decay.
start_weight_decaynullStarting weight decay for schedules.
end_weight_decaynullEnding weight decay for schedules.
weight_decay_incr_styleconstantHow weight decay changes between start/end.
clip_grad1.0Global gradient norm clip.
adam_beta10.9Adam first moment decay.
adam_beta20.95 (0.999 in pre_trainer.yaml)Adam second moment decay.
adam_eps1.0e-08Adam epsilon.
sgd_momentum0.9SGD momentum when optimizer is SGD.
override_opt_param_schedulerfalse (true in pre_trainer.yaml)Override optimizer parameter groups’ schedulers.
use_checkpoint_opt_param_schedulerfalseLoad optimizer scheduler state strictly from checkpoint.
warmupnullAlternate warmup specification (legacy / schedule hooks).
decoupled_lrnullDecoupled LR for certain param groups.
decoupled_min_lrnullMinimum for decoupled LR.
muon_extra_scale_factor1.0Muon optimizer scaling.
muon_scale_mode"spectral"Muon scaling mode.
muon_fp32_matmul_prec"medium"Muon matmul precision hint.
muon_num_ns_steps5Muon Newton–Schulz iterations.
muon_tp_mode"blockwise"Muon tensor-parallel mode.
muon_use_nesterovfalseMuon Nesterov momentum.
muon_split_qkvtrueSplit QKV for Muon.
muon_momentum0.95Muon momentum.
muon_weight_decay0.01Muon-specific decay.
muon_weight_decay_method"decoupled"How Muon applies decay.
optimizer_cpu_offloadfalseOffload optimizer state to CPU.
optimizer_offload_fraction1.0Fraction of optimizer state offloaded.
use_torch_optimizer_for_cpu_offloadfalseUse PyTorch optimizer for offload path.
overlap_cpu_optimizer_d2h_h2dfalseOverlap CPU optimizer device transfers.
pin_cpu_gradstruePin memory for CPU gradients.
pin_cpu_paramstruePin memory for CPU params in offload.
use_precision_aware_optimizerfalseUse precision-aware optimizer (main grads/params in lower precision).
main_grads_dtypefp32Dtype for main gradients (fp32, bf16).
main_params_dtypefp32Dtype for master params.
exp_avg_dtypefp32Optimizer first moment dtype (fp32, fp16, fp8).
exp_avg_sq_dtypefp32Optimizer second moment dtype.

5. Parallelism and distribution

Sources: trainer_base.yaml (distributed runtime) and primus/configs/models/megatron/language_model.yaml (model-parallel sizes and TP communication).

5.1 Data / distributed runtime (trainer)

ParameterDefaultDescription
overlap_p2p_commtrueOverlap pipeline P2P with compute.
distributed_backendncclProcess-group backend (nccl, gloo, …).
distributed_timeout_minutes10 (60 in pre_trainer.yaml)Collective timeout.
defer_embedding_wgrad_computefalseDefer embedding weight gradients.
wgrad_deferral_limit0Max deferred embedding wgrad steps.
align_grad_reducetrueAlign gradient reductions for efficiency.
ddp_num_bucketsnullNumber of DDP buckets.
ddp_bucket_sizenullDDP bucket size in elements.
ddp_pad_buckets_for_high_nccl_busbwfalsePad buckets for NCCL bus bandwidth.
ddp_average_in_collectivefalseAverage inside collective vs outside.
overlap_grad_reducefalseOverlap gradient all-reduce with backward.
overlap_param_gatherfalseOverlap param all-gather (distributed optimizer).
overlap_param_gather_with_optimizer_stepfalseOverlap param gather with optimizer step.
align_param_gathertrueAlign param gather for distributed optimizer.
scatter_gather_tensors_in_pipelinetrueScatter/gather tensors across PP ranks.
use_ring_exchange_p2pfalseRing-exchange P2P for PP.
local_ranknullLocal rank override (normally from launcher).
lazy_mpu_initnullDefer Megatron parallel state init.
account_for_embedding_in_pipeline_splitfalseAccount for embedding in PP partition.
account_for_loss_in_pipeline_splitfalseAccount for loss partition in PP.
empty_unused_memory_level0Aggressiveness of torch.cuda.empty_cache.
standalone_embedding_stagefalseDedicated PP stage for embeddings.
use_distributed_optimizerfalse (true in pre_trainer.yaml)Shard optimizer state across data parallel.
use_sharpfalseUse SHARP for collectives when available.
sharp_enabled_groupnullWhich group SHARP applies to (dp, dp_replica).
use_custom_fsdpfalseCustom FSDP integration path.
use_megatron_fsdpfalseMegatron FSDP path.
init_model_with_meta_devicefalseBuild model on meta device first.
data_parallel_sharding_strategyno_shardFSDP / ZeRO style sharding (no_shard, optim, …).
gradient_reduce_div_fusiontrueFuse division into reduce-scatter.
suggested_communication_unit_size400000000Suggested communication chunk size.
keep_fp8_transpose_cache_when_using_custom_fsdpfalseKeep FP8 transpose cache with custom FSDP.
num_distributed_optimizer_instances1Sharded optimizer instances per rank group.
use_torch_fsdp2falseUse PyTorch FSDP2 integration.
nccl_communicator_config_pathnullJSON config for NCCL communicators.
use_tp_pp_dp_mappingfalseCustom TP/PP/DP process mapping.
replicationfalseData replication mode for certain schedules.
replication_jumpnullStride between replicated ranks.
replication_factornullReplication factor.
deterministic_modefalsePrefer deterministic algorithms (slower).
check_weight_hash_across_dp_replicas_intervalnullPeriodically hash weights across DP replicas for debugging.
overlap_moe_expert_parallel_commfalseOverlap MoE expert-parallel communication.
decoder_pipeline_manual_split_listnullPrimus: manual PP split points for decoder (list of ints).
patch_moe_overlapfalsePrimus: patch MoE compute/comm overlap.

5.2 Model parallelism (model preset)

ParameterDefaultDescription
model_parallel_sizenullLegacy combined MP size override.
tensor_model_parallel_size1Tensor parallelism degree (intra-layer split).
encoder_tensor_model_parallel_size0Encoder TP size when encoder/decoder differ.
pipeline_model_parallel_size1Pipeline parallelism stages.
pipeline_model_parallel_layoutnullOptional explicit PP layout string.
pipeline_model_parallel_comm_backendnullnccl or ucc for PP collectives.
encoder_pipeline_model_parallel_size0Encoder PP stages (encoder–decoder models).
pipeline_model_parallel_split_ranknullRank where encoder/decoder split.
decoder_first_pipeline_num_layersnullLayers on first decoder PP stage.
decoder_last_pipeline_num_layersnullLayers on last decoder PP stage.
virtual_pipeline_model_parallel_sizenullVirtual PP (interleaved) depth.
num_layers_per_virtual_pipeline_stagenullLayers per virtual stage.
num_virtual_stages_per_pipeline_ranknullVirtual stages per physical PP rank.
microbatch_group_size_per_vp_stagenullMicrobatch grouping for interleaved PP.
sequence_paralleltrueSequence parallelism when TP > 1.
context_parallel_size1Context (sequence) parallelism degree.
cp_comm_typep2pContext-parallel comm pattern (p2p, a2a, allgather, a2a+p2p).
hierarchical_context_parallel_sizesnullHierarchical CP group sizes.
expert_model_parallel_size1Expert parallelism for MoE.
expert_tensor_parallel_sizenullExpert tensor-parallel degree.
high_priority_stream_groups[]Named groups that get high-priority CUDA streams.

5.3 Tensor-parallel communication overlap (model)

ParameterDefaultDescription
async_tensor_model_parallel_allreducetrueAsync TP all-reduces for column-parallel layers.
tp_comm_overlapfalseEnable TP communication overlap planner.
tp_comm_overlap_cfgnullExtra JSON / path for overlap configuration.
tp_comm_overlap_agtrueOverlap all-gather in TP backward.
tp_comm_overlap_rstrueOverlap reduce-scatter in TP backward.
tp_comm_overlap_rs_dgradfalseOverlap RS for data-grad path.
tp_comm_split_agtrueSplit all-gather for overlap.
tp_comm_split_rstrueSplit reduce-scatter for overlap.
tp_comm_bulk_wgradtrueBulk weight-gradient path for TP comm.
tp_comm_bulk_dgradtrueBulk data-gradient path for TP comm.
barrier_with_L1_timetrueBarrier using L1 timing hooks for TP comm profiling.
tp_comm_bootstrap_backendncclBackend used to bootstrap TP communicators.

6. Checkpointing

Source: trainer_base.yaml.

ParameterDefaultDescription
savenullPath prefix / pattern for checkpoints to write.
save_interval20000 (1000 in pre_trainer.yaml)Save every N iterations.
save_retain_intervalnullRetain checkpoints at this interval.
no_save_optimnullSkip optimizer state in checkpoints when truthy.
no_save_rngnullSkip RNG state in checkpoints when truthy.
loadnullCheckpoint path to load.
load_main_params_from_ckptfalseLoad only main parameters.
no_load_optimnullSkip loading optimizer state.
no_load_rngnullSkip loading RNG state.
finetunefalse (true in pre_trainer.yaml)Finetune mode (do not require full optimizer match).
use_checkpoint_argsfalseWhen true, restore training args from checkpoint metadata.
use_mp_args_from_checkpoint_argsfalseRestore model-parallel args from checkpoint.
use_tokenizer_model_from_checkpoint_argstrueRestore tokenizer path from checkpoint args.
exit_on_missing_checkpointtrueFail if load is set but checkpoint is missing.
non_persistent_save_intervalnullEphemeral checkpoint interval.
non_persistent_ckpt_typenullglobal, local, in_memory, or null.
non_persistent_global_ckpt_dirnullDirectory for non-persistent global checkpoints.
non_persistent_local_ckpt_dirnullDirectory for non-persistent local checkpoints.
non_persistent_local_ckpt_algo"fully_parallel"fully_parallel or atomic.
pretrained_checkpointnullLoad weights from a pretrained checkpoint path.
ckpt_stepnullSpecific step to load within a distributed checkpoint.
use_dist_ckpt_deprecatedfalseUse deprecated distributed checkpoint format.
use_persistent_ckpt_workerfalseBackground worker for checkpoint IO.
auto_detect_ckpt_formatfalseInfer checkpoint format automatically.
dist_ckpt_format_deprecatednullLegacy format hint.
ckpt_formattorch_disttorch, torch_dist, or zarr.
ckpt_convert_formatnullTarget format for one-shot conversion.
ckpt_convert_savenullOutput path for conversion.
ckpt_convert_update_legacy_dist_opt_formatfalseUpdate legacy distributed-optimizer layout when converting.
ckpt_fully_parallel_save_deprecatedfalseDeprecated fully-parallel save toggle.
ckpt_fully_parallel_savetrueSave shards in parallel across ranks.
async_savenullAsync checkpoint save (null = framework default).
ckpt_fully_parallel_loadfalseLoad shards in parallel.
ckpt_assume_constant_structurefalseAssume identical layer structure across ranks.
dist_ckpt_strictnessassume_ok_unexpectedHow to handle unexpected keys in distributed ckpt.
dist_ckpt_save_pre_mcore_014nullCompatibility flag for older Megatron-Core checkpoints.
dist_ckpt_optim_fully_reshardablenullOptimizer state fully reshardable layout.
auto_continue_trainfalsePrimus: resume from latest checkpoint in the save directory when enabled.
disable_last_savingfalsePrimus: skip writing the final checkpoint at shutdown.

7. Data

Source: trainer_base.yaml.

ParameterDefaultDescription
data_pathnullSingle blended dataset path / list.
data_shardingtrueShard data across ranks.
split"99,1,0" (null in pre_trainer.yaml)Train/valid/test split ratios as comma string.
train_data_pathnullTraining data blend.
valid_data_pathnullValidation data blend.
test_data_pathnullTest data blend.
data_args_pathnullExternal JSON/YAML of dataset arguments.
per_split_data_args_pathnullPer-split dataset args file.
data_cache_pathnullOn-disk cache for indexed datasets.
mock_datafalseUse synthetic data (no real files).
merge_filenullMerge file for blended datasets.
seq_length4096 (1024 in pre_trainer.yaml)Training sequence length.
encoder_seq_lengthnullEncoder sequence length (encoder–decoder).
decoder_seq_lengthnullDecoder sequence length.
retriever_seq_length256Sequence length for retriever models.
sample_rate1.0Sampling rate for dataset blending.
mask_prob0.15MLM mask probability.
short_seq_prob0.1Probability of shorter sequences in BERT-style data.
num_workers8DataLoader worker processes per rank.
reset_position_idsfalseReset position IDs at document boundaries.
reset_attention_maskfalseReset attention mask at boundaries.
eod_mask_lossfalseMask loss at end-of-document tokens.
dataloader_typenull (cyclic in pre_trainer.yaml)Dataloader implementation (single, cyclic, external, …).
mmap_bin_filestrueMemory-map .bin index files when supported.
create_attention_mask_in_dataloadertrueBuild attention masks in the dataloader.
num_dataset_builder_threads1Threads to build dataset indices.

8. Recomputation (activation checkpointing)

Sources: trainer_base.yaml and primus_megatron_module.yaml.

ParameterDefaultDescription
recompute_activationsfalseEnable activation recomputation globally.
recompute_granularitynullfull or selective checkpointing.
recompute_methodnulluniform or block selective recomputation.
recompute_num_layersnullLayers to recompute per block / schedule.
recompute_layer_idsnullPrimus: explicit global layer indices to recompute. Decoder layers are 0 … num_layers-1; the MTP depths continue the numbering, so depth d is num_layers + d. Requires recompute_granularity: full and recompute_method: null.
distribute_saved_activationsfalseDistribute saved activations across TP/PP for memory balance.
checkpoint_activationsfalseDeprecated alias for activation checkpointing.
moe_layer_recomputefalseRecompute MoE layer activations (model preset).

9. Logging and profiling

Sources: trainer_base.yaml and primus_megatron_module.yaml.

9.1 Logging

ParameterDefaultDescription
log_avg_skip_iterations2Skip first N iterations for throughput averaging.
log_avg_reset_interval10Reset moving averages periodically.
log_params_normfalseLog L2 norms of parameters.
log_num_zeros_in_gradfalseLog fraction of zero gradients.
log_throughputfalse (true in pre_trainer.yaml)Log tokens/sec and timing.
log_progressfalseVerbose progress logging.
timing_log_level0Verbosity for timing logs.
timing_log_optionminmaxAggregate style for timing (minmax, all, …).
tensorboard_log_interval1Steps between TensorBoard scalars.
tensorboard_queue_size1000TensorBoard event queue size.
log_timers_to_tensorboardfalse (true in pre_trainer.yaml)Write timer stats to TensorBoard.
log_batch_size_to_tensorboardfalse (true in pre_trainer.yaml)Log batch size.
log_learning_rate_to_tensorboardtrueLog LR.
log_validation_ppl_to_tensorboardfalseLog validation perplexity.
log_memory_to_tensorboardfalseLog memory usage.
log_world_size_to_tensorboardfalseLog distributed world size.
log_loss_scale_to_tensorboardtrueLog FP16/FP8 loss scale.
wandb_projectnullWeights & Biases project name.
wandb_exp_namenullW&B run name.
wandb_save_dirnullW&B local directory.
wandb_entitynullW&B entity / team.
enable_one_loggertrueEnable NVIDIA OneLogger integration.
one_logger_projectmegatron-lmOneLogger project string.
one_logger_run_namenullOneLogger run name.
log_interval100 (1 in pre_trainer.yaml)Console log interval in iterations.
tensorboard_dirnullTensorBoard output directory.
logging_levelnullPython logging level override.
config_logger_dir""Directory for dumped config logs.
one_logger_asyncfalseAsync OneLogger flushing.
app_tag_run_namenullApplication tag for telemetry.
app_tag_run_version0.0.0Application tag version.
disable_tensorboardtruePrimus: disable TensorBoard integration in Primus-wrapped runs.
disable_wandbtruePrimus: disable W&B.
disable_mlflowtruePrimus: disable MLflow.
mlflow_run_namenullPrimus: MLflow run name.
mlflow_experiment_namenullPrimus: MLflow experiment name.
use_rocm_mem_infofalsePrimus: collect ROCm memory info via rocm-smi every step when true.
use_rocm_mem_info_iters[1, 2]Primus: iterations at which to log memory if use_rocm_mem_info is false.

9.2 Profiling

ParameterDefaultDescription
profilefalseEnable lightweight Nsight / CUDA profiling hooks.
use_pytorch_profilerfalseEnable torch.profiler regions.
profile_ranks[0]Ranks to profile.
profile_step_start10First step to profile.
profile_step_end12Last step to profile.
iterations_to_skipnullSkip listed iterations in profiling.
result_rejected_tracker_filenamenullLog rejected samples to this file.
enable_gloo_process_groupstrueCreate auxiliary Gloo groups for CPU-side ops.
record_memory_historyfalseRecord CUDA memory history (debug).
memory_snapshot_pathsnapshot.picklePath for memory snapshot dumps.
disable_profiler_activity_cpufalsePrimus: omit CPU activities from profiler traces.
torch_profiler_record_shapestruePrimus: record tensor shapes in PyTorch profiler.
torch_profiler_with_stacktruePrimus: capture Python stacks in profiler.
torch_profiler_use_gzipfalsePrimus: gzip profiler outputs.

10. Model architecture

Sources: primus/configs/models/megatron/language_model.yaml and primus/configs/models/megatron/primus_megatron_model.yaml.

10.1 Core architecture

ParameterDefaultDescription
use_legacy_modelsfalseUse legacy Megatron model code paths.
deprecated_use_mcore_modelsfalseDeprecated flag for Megatron-Core models; prefer current transformer_impl + stack.
model_typegptgpt or mamba family.
num_layers24Transformer layers (decoder or unified stack).
encoder_num_layersnullEncoder depth (encoder–decoder).
decoder_num_layersnullDecoder depth.
hidden_size1024Hidden / model width.
num_attention_heads16Attention heads.
attention_backendautoAttention kernel backend selection.
group_query_attentionfalseEnable grouped-query attention (GQA).
qk_layernormfalseLayerNorm on Q/K projections.
qk_l2_normfalseL2-normalize Q/K vectors.
num_query_groupsnullNumber of query groups for GQA; null means MHA.
add_position_embeddingfalseAdd absolute position embeddings (non-RoPE stacks).
position_embedding_typelearned_absolutePosition embedding style.
max_position_embeddingsnullMaximum sequence positions (context length cap).
original_max_position_embeddingsnullOriginal pretrained length for interpolation / scaling.
untie_embeddings_and_output_weightstrueSeparate input embedding and LM head weights.
ffn_hidden_sizenullFFN hidden size; null often defaults via hidden_size heuristics.
kv_channelsnullPer-head KV channels override.
hidden_dropout0.1Dropout on residual / hidden states.
attention_dropout0.1Attention dropout.
fp32_residual_connectionfalseAccumulate residuals in FP32.
apply_residual_connection_post_layernormfalseApply residual after (vs before) norm where supported.
add_bias_linearfalseBiases in linear / column-parallel layers.
add_qkv_biasfalseBiases in QKV projections.
swiglutrueSwiGLU activation in FFN.
quick_geglufalseFaster GeGLU path.
openai_gelufalseOpenAI GELU variant.
squared_relufalseSquared ReLU activation.
rotary_base10000RoPE base frequency.
rotary_percent1.0Fraction of head dim spanned by RoPE.
rotary_interleavedfalseInterleaved RoPE layout.
rotary_seq_len_interpolation_factornullPositional interpolation factor for long contexts.
use_rotary_position_embeddingsnullForce RoPE on/off; null follows model type.
use_rope_scalingfalseEnable LLaMA-style rope scaling.
rope_scaling_factor8.0Scaling factor for extended contexts (LLaMA-3 style).
transformer_impltransformer_engineBackend library (transformer_engine, local, …).
rope_typenullrope or yarn style extensions.
norm_epsilon1.0e-05LayerNorm / RMSNorm epsilon.
normalization"LayerNorm"Norm type (LayerNorm, RMSNorm with TE, …).
apply_layernorm_1pfalseLayerNorm with +1 offset trick.
clone_scatter_output_in_embeddingtrueClone embedding scatter for autograd safety.
perform_initializationtrueRun weight initialization.
use_cpu_initializationnullInitialize on CPU then move to GPU.
use_te_activation_funcfalseUse Transformer Engine activation kernels.
gradient_accumulation_fusiontrueFuse gradient accumulation kernels.
delay_wgrad_computefalseDelay weight-gradient computation for scheduling.

10.2 Tokenizer and vocabulary

ParameterDefaultDescription
tokenizer_typenullTokenizer class name (GPT2BPETokenizer, HuggingFaceTokenizer, …).
tokenizer_modelnullPath to tokenizer model / vocabulary file.
vocab_sizenullVocabulary size (often inferred from tokenizer).
vocab_filenullVocabulary file path for BPE/WP tokenizers.
vocab_extra_ids0Extra reserved token slots.
tiktoken_patternnullRegex pattern for tiktoken.
tiktoken_num_special_tokens1000Special token count for tiktoken setup.
tiktoken_special_tokensnullSerialized special tokens for tiktoken.
legacy_tokenizerfalseLegacy tokenizer behavior.
trust_remote_codefalsetrust_remote_code for Hugging Face tokenizers.

10.3 Initialization and attention numerics

ParameterDefaultDescription
init_method_std0.02Standard deviation for weight init.
apply_query_key_layer_scalingfalseScale Q/K by layer index (deprecated GPT-3 trick).
attention_softmax_in_fp32falseForce softmax in FP32.

10.4 Kernel fusion flags

ParameterDefaultDescription
bias_gelu_fusiontrueFuse bias + GELU.
cross_entropy_loss_fusionfalseFused cross-entropy + softmax.
cross_entropy_fusion_impl"native"native or te fused CE.
bias_swiglu_fusiontrueFuse bias + SwiGLU.
masked_softmax_fusiontrueFused masked softmax.
no_persist_layer_normfalseNon-persistent LayerNorm mode in TE.
bias_dropout_fusiontrueFuse bias + dropout.
apply_rope_fusiontrueFused RoPE kernels.

10.5 Multi-latent attention (MLA)

ParameterDefaultDescription
multi_latent_attentionfalseEnable MLA blocks instead of standard MHA.
q_lora_ranknullLow-rank query projection rank.
kv_lora_rank32Low-rank KV compression rank.
qk_head_dim128Q/K head dimension for MLA.
qk_pos_emb_head_dim64Positional head dimension for MLA.
v_head_dim128Value head dimension for MLA.
rotary_scaling_factor1.0RoPE scaling inside MLA (distinct from rope_scaling_factor above).
mscale1.0Yarn / scaling m-factor.
mscale_all_dim1.0Yarn scaling on all dims.

10.6 Mixture-of-experts (MoE)

ParameterDefaultDescription
num_expertsnullExperts per MoE layer; null means dense model.
moe_layer_freq1Every Nth layer is MoE (1 = every layer).
moe_ffn_hidden_sizenullExpert FFN hidden size.
moe_shared_expert_overlapfalseShared expert overlaps routing.
moe_shared_expert_intermediate_sizenullShared expert FFN size.
moe_grouped_gemmfalseGrouped GEMM for experts.
moe_router_load_balancing_type"aux_loss"Router balancing (aux_loss, seq_aux_loss, sinkhorn, none).
moe_router_dtypenullRouter activation dtype (fp32, fp64).
moe_router_score_functionsoftmaxsoftmax or sigmoid routing scores.
moe_router_topk2Experts to select per token.
moe_router_pre_softmaxfalseApply softmax before top-k.
moe_router_num_groupsnullGroup-limited routing: number of expert groups.
moe_router_group_topknullGroups to pick before top-k inside groups.
moe_router_topk_scaling_factornullScaling for routing logits.
moe_router_enable_expert_biasfalseLearnable per-expert bias.
moe_router_bias_update_rate1.0e-03Update rate for expert bias.
moe_use_legacy_grouped_gemmfalseLegacy grouped GEMM path.
moe_aux_loss_coeff0.0Auxiliary load-balancing loss weight.
moe_z_loss_coeffnullRouter z-loss coefficient.
moe_input_jitter_epsnullInput jitter for router stability.
moe_token_dispatcher_typeallgatherToken dispatch algorithm (allgather, alltoall, flex, alltoall_seq).
moe_enable_deepepfalseDeepEP-style expert parallelism.
moe_per_layer_loggingfalsePer-layer MoE statistics logging.
moe_expert_capacity_factornullCapacity factor for token dropping / padding.
moe_pad_expert_input_to_capacityfalsePad expert batches to capacity.
moe_token_drop_policyprobsToken dropping policy when over capacity.
moe_extended_tpfalseExtended tensor-parallel for experts.
moe_use_upcyclingfalseExpert upcycling initialization.
moe_permute_fusionfalseFuse token permutation for MoE.
disable_primus_topk_routerfalsePrimus: disable Primus top-k router patch.
moe_router_force_load_balancingfalsePrimus: force load-balanced routing.
use_deprecated_20241209_moe_layerfalsePrimus: legacy MoE layer implementation.
moe_router_force_load_balancing_typeevenPrimus: Control the force load balancing type for the MoE router. Choices: even, uniform.

10.7 Logit softcapping (Primus / Grok-style)

ParameterDefaultDescription
final_logit_softcappingnullSoftcap value for final logits; null disables.
attn_logit_softcappingnullSoftcap for attention logits.
router_logit_softcappingnullSoftcap for MoE router logits.

11. Primus extensions

11.1 Build and compile

ParameterDefaultDescription
disable_compile_dependenciestruePrimus: avoid compiling dependency stacks in the trainer wrapper.

11.2 Primus-Turbo (primus_turbo.yaml)

ParameterDefaultDescription
enable_primus_turbofalseMaster switch for Primus-Turbo integrations. Many sub-features require this plus specific kernels.
use_turbo_attentionfalseTurbo attention implementation.
use_sink_attentionfalseGPT-OSS-style learned sink attention.
sink_sliding_window0Sliding-window size for sink attention (GPT-OSS uses 128).
sink_window_even_layers_onlytrueApply the sliding window only to even layers (GPT-OSS pattern).
use_turbo_gemmfalseActive Turbo GEMM flag for Dense paths.
use_turbo_parallel_linear(removed)Removed—use use_turbo_gemm. Passing this key now raises an assertion error (use_turbo_parallel_linear has been removed; please use use_turbo_gemm instead).
use_turbo_grouped_gemmfalseActive Turbo grouped GEMM flag for MoE paths.
use_turbo_grouped_mlp(removed)Removed—use use_turbo_grouped_gemm. Passing this key now raises an assertion error (use_turbo_grouped_mlp has been removed; please use use_turbo_grouped_gemm instead).
moe_use_fused_router_with_aux_scorefalseFused MoE router with auxiliary scores.
enable_turbo_attention_float8falseFP8 path inside Turbo attention (spacing in YAML is normalized to this key).
use_turbo_deepepfalseTurbo DeepEP expert communication.
turbo_deepep_num_cu32DeepEP compute units / channels.
turbo_deepep_use_comm_streamfalseUse a dedicated communication stream for DeepEP.
turbo_sync_free_moe_stage0Stage selector for sync-free MoE.
use_turbo_fused_act_with_probsfalseFuse activation + probability tensors to remove redundant work.
use_turbo_rms_normfalseTurbo RMSNorm kernels.

11.3 Zero-bubble pipeline (zero_bubble.yaml)

ParameterDefaultDescription
patch_zero_bubblefalseInstall Primus zero-bubble PP patches when true.
debug_scheduler_tablefalsePrint PP scheduler tables (also in primus_pipeline.yaml; last merge wins—defaults match).
enable_zb_runtimetrueUnified runtime for zero-bubble and related schedules.
pre_communication_optimizationfalseIssue a tiny comm before real comm to tune overlap.
zero_bubble_pipeline_timers_start_iter100Start iter for auto-scheduler timers.
zero_bubble_pipeline_timers_end_iter110End iter for auto-scheduler timers.
zero_bubble_max_pending_backwardautoMax pending backward ops (ZB1p vs ZB2p style); auto adapts.
zero_bubble_adaptive_memory_limit_percentile85GPU memory percentile cap for adaptive ZB.
enable_optimizer_post_validationfalsePost-optimizer validation step (needs FSDP path).
enable_exactly_numeric_matchtrueRequire bitwise match in post validation when enabled.
enable_zero_bubbletrueEnable zero-bubble schedule features in the ZB runtime.
zero_bubble_v_schedulefalseZero-bubble “V” schedule without extra memory vs some baselines.
zero_bubble_v_schedule_mem_setuphalfMemory setup variant: half, min, or zb.
enable_1f1b_vfalse1F1B-V schedule variant.
allow_padding_num_layerstrueAllow PP layer padding for divisibility.
profile_memory_iter-1Iteration to profile memory (-1 disables).
interleave_group_size0Interleaved PP group size.
offload_chunk_num0Activation offload chunk count.
offload_time1.0Time budget for offload (scheduler hint).
auto_offload_timetrueAuto-tune offload timing.
offload_overlap_srtrueOverlap save/resume in offload path.
num_seq_splits1Splits along sequence dimension for ZB.
cpu_offloadfalseCPU offload of activations in ZB path.

11.4 Primus pipeline (primus_pipeline.yaml)

ParameterDefaultDescription
patch_primus_pipelinefalseEnable Primus pipeline scheduling patches.
pp_algorithm"1f1b-interleaved"Schedule name (1f1b, 1f1b-interleaved, zero-bubble, zero-bubble-heuristic, zbv-formatted, v-half, v-min).
communication_method"async_p2p"async_p2p or batch_p2p PP transfers.
offloadfalseGeneric PP activation offload toggle in Primus pipeline.
offload_ops""Comma-separated offload targets (attn today; other ops listed in-file are not supported yet).
pp_max_memnullzero-bubble-heuristic only: max activation memory per stage (null = unlimited).
pp_cost_fnullzero-bubble-heuristic only: forward cost per stage (scalar or list; null = default 1000).
pp_cost_bnullzero-bubble-heuristic only: backward cost per stage (scalar or list; null = default 1000).
pp_cost_wnullzero-bubble-heuristic only: weight-grad cost per stage (scalar or list; null = default 1000).

pp_warmup and dump_pp_data are Primus helpers defined in primus_megatron_module.yaml (not primus_pipeline.yaml):

ParameterDefaultDescription
pp_warmupfalsePrimus: warm-up PP stages to reduce first-iteration latency.
dump_pp_datafalsePrimus: dump PP tensors for debugging.

Source: trainer_base.yaml. Names follow Megatron’s grpo_* / rl_* prefixes (there is no rl_grpo single flag in these presets).

ParameterDefaultDescription
perform_rl_stepfalseRun RL / preference optimization steps (GRPO / LangRL integration).
rl_prompts_per_eval32Prompts per RL evaluation pass.
grpo_prompts_per_step32GRPO prompts sampled per training step.
grpo_group_size2Samples per prompt group for GRPO.
grpo_iterations2Inner GRPO iterations.
grpo_clamp_eps_lower0.01PPO-style lower clip epsilon.
grpo_clamp_eps_upper0.01Upper clip epsilon.
grpo_kl_beta0.001KL penalty weight toward reference policy.
grpo_entropy_term_weight0.0Entropy bonus weight.
grpo_filter_groups_with_same_rewardfalseDrop groups with identical rewards.
grpo_default_temperature1.0Default softmax temperature for rollouts.
grpo_default_top_p0Top-p sampling (0 often means disabled / greedy—see Megatron RL docs).
langrl_inference_server_typeinplace_megatronLangRL inference backend.
langrl_inference_server_conversation_templatenullConversation template path / name.
langrl_env_confignullEnvironment / task YAML for LangRL.
rl_offload_optimizer_during_inferencefalseOffload optimizer to CPU during rollout inference.
rl_offload_kv_cache_during_trainingfalseOffload KV cache while training forward runs.
rl_remove_kv_cache_during_trainingfalseDrop KV cache between RL phases to save memory.
rl_reset_cuda_graphsfalseReset CUDA graphs when switching RL phases.
rl_partial_rolloutsfalsePartial sequence rollouts.
rl_inference_logprobs_is_correctionfalseInterpret inference logprobs as IS correction term.
rl_importance_sampling_truncation_coefnullTruncate importance ratios at this value.
rl_calculate_intra_group_similarityfalseLog similarity within GRPO groups.

13. Additional specialized parameters

Source: trainer_base.yaml (remaining domains).

13.1 Vision pretraining

ParameterDefaultDescription
vision_pretrainingfalseEnable vision backbone pretraining.
vision_pretraining_typeclassifyObjective (classify, etc.).
vision_backbone_typevitVision backbone family.
swin_backbone_typetinySwin variant size.
num_classes1000Classification classes.
img_h224Image height.
img_w224Image width.
num_channels3Input channels.
patch_dim16ViT patch size.
classes_fraction1.0Fraction of classes used.
data_per_class_fraction1.0Fraction of data per class.

13.2 RETRO

ParameterDefaultDescription
retro_project_dirnullRETRO project directory with indices.
retro_add_retrieverfalseAdd frozen retriever tower.
retro_cyclic_train_itersnullCyclic iterator length.
retro_encoder_layers2Retriever encoder layers.
retro_encoder_hidden_dropout0.1Retriever dropout.
retro_encoder_attention_dropout0.1Retriever attention dropout.
retro_num_neighbors2Neighbors per query chunk.
retro_num_retrieved_chunks2Chunks concatenated per neighbor set.
retro_attention_gate1Gating between retrieval and LM.
retro_verify_neighbor_counttrueAssert neighbor counts for debugging.

13.3 DINO self-supervised

ParameterDefaultDescription
dino_local_img_size96Local crop size.
dino_local_crops_number10Number of local crops.
dino_head_hidden_size2048Projection head width.
dino_bottleneck_size256Bottleneck dimension.
dino_freeze_last_layer1Freeze last layer epochs.
dino_norm_last_layerfalseNormalize last layer weights.
dino_warmup_teacher_temp0.04Teacher temperature warmup start.
dino_teacher_temp0.07Teacher temperature.
dino_warmup_teacher_temp_epochs30Epochs to warm teacher temperature.

13.4 Biencoder / ICT / retriever utilities

ParameterDefaultDescription
ict_head_sizenullICT projection head width.
biencoder_projection_dim0Biencoder shared projection dimension.
biencoder_shared_query_context_modelfalseShare query/context encoders.
ict_loadnullICT checkpoint path.
bert_loadnullBERT encoder checkpoint for biencoder.
titles_data_pathnullTitles file for ICT datasets.
query_in_block_prob0.1Probability of in-block queries.
use_one_sent_docsfalseSingle-sentence pseudo documents.
evidence_data_pathnullEvidence passages for open-domain QA.
retriever_report_topk_accuracies[]k values for top-k accuracy logging.
retriever_score_scalingfalseScale retriever scores.
block_data_pathnullBlock JSON data for retrieval.
embedding_pathnullPrecomputed embeddings path.
indexer_batch_size128Batch size when building ANN index.
indexer_log_interval1000Indexer progress log interval.

13.5 Straggler detection

ParameterDefaultDescription
log_stragglerfalseLog straggler diagnostics.
disable_straggler_on_startupfalseSkip straggler detection at startup.
straggler_ctrlr_port65535Controller port for straggler service.
straggler_minmax_count1Min/max samples for straggler stats.

13.6 Inference-oriented options

ParameterDefaultDescription
inference_batch_times_seqlen_threshold-1Heuristic threshold tying batch and sequence length.
inference_dynamic_batchingfalseDynamic batching for inference server.
inference_dynamic_batching_buffer_size_gb40.0GPU buffer budget (GB).
inference_dynamic_batching_buffer_guaranteed_fraction0.2Minimum reserved fraction of buffer.
inference_dynamic_batching_buffer_overflow_factornullOverflow growth factor.
inference_dynamic_batching_max_requests_overridenullHard cap on concurrent requests.
inference_dynamic_batching_max_tokens_overridenullHard cap on tokens in flight.
max_tokens_to_oom12000Token limit guard before OOM abort.
output_bert_embeddingsfalseReturn BERT pooled embeddings.
bert_embedder_typemegatronmegatron or huggingface embedder.
flash_decodefalseFlash decode kernels for incremental generation.
enable_cuda_graphfalseCapture CUDA graphs for inference.
cuda_graph_warmup_steps3Warm-up steps before capturing graphs.
external_cuda_graphfalseExternal graph provider hooks.
cuda_graph_scopefullGraph scope (full or attn).
inference_max_requests8Max concurrent requests.
inference_max_seq_length2560Max prefill + decode tokens per request.

13.7 Fault tolerance package and tooling

ParameterDefaultDescription
enable_ft_packagefalseNVIDIA fault-tolerance package hooks.
calc_ft_timeoutsfalseAuto-calculate FT timeouts.
run_workload_inspector_serverfalseRun workload inspector sidecar.

13.8 Heterogeneous layers and process resilience

ParameterDefaultDescription
heterogeneous_layers_config_pathnullJSON describing variable layer widths/types per layer.
heterogeneous_layers_config_encoded_jsonnullInline base64/JSON blob for heterogeneous layers.
inprocess_restartfalseIn-process restart for fault recovery experiments.

13.9 Experimental and rerun controls

ParameterDefaultDescription
enable_experimentalfalseGate experimental Megatron features.
error_injection_rate0Fraction of iterations with injected errors (testing).
error_injection_typetransient_errorcorrect_result, transient_error, or persistent_error.
rerun_modedisableddisabled, validate_results, or report_stats for rerun harness.

  • Megatron-LM argument definitions: megatron/training/arguments.py
  • Primus Megatron presets: primus/configs/modules/megatron/
  • Primus Megatron model presets: primus/configs/models/megatron/