HuggingFace conversion

scripts/convert_checkpoint.py converts between KempnerForge’s DCP format and HuggingFace’s safetensors (or .bin) format. Two directions:

  • dcp-to-hf — export a DCP checkpoint for HF inference, model cards, or pushing to the Hub.

  • hf-to-dcp — import HF pretrained weights (e.g. meta-llama/Llama-3.1-8B) into DCP for continued pretraining or fine-tuning.

Both directions are offline — no distributed training required, runs on a single CPU or GPU.

DCP → HuggingFace

uv run python scripts/convert_checkpoint.py dcp-to-hf \
    --dcp-dir checkpoints/step_10000 \
    --hf-dir exports/my_model \
    --config configs/model/llama_7b.toml

What happens:

  1. Build a bare Transformer(model_config) on CPU — the default random-initialized parameters serve only as target shapes that DCP overwrites on load.

  2. Load the checkpoint into that model with DCP. A pipeline-parallel checkpoint, one with stage subdirectories (pp0/, pp1/, …), is loaded stage by stage; see With PP.

  3. Convert state dict keys from KempnerForge → HF naming.

  4. Cast every tensor to the export dtype (see Dtypes).

  5. Write model.safetensors (or fall back to pytorch_model.bin if the safetensors package isn’t installed) plus a config.json compatible with AutoModelForCausalLM.

exports/my_model/
├── config.json              ← HF model config
└── model.safetensors        ← weights

With tied embeddings the export still holds both model.embed_tokens.weight and lm_head.weight, the head as a copy of the embedding, since safetensors refuses tensors that share memory. config.json sets tie_word_embeddings, so transformers ties the two again when it loads the export.

What transformers can load

transformers builds a dense export as LlamaForCausalLM and an MoE export as MixtralForCausalLM. Both have SwiGLU MLPs or experts and RMSNorm, and neither has a query or key norm, so dcp-to-hf refuses, before it reads the checkpoint, a model with an activation other than "silu", norm_type = "layernorm" or qk_norm = true, and an MoE model with what Mixtral lacks (see MoE). It names each setting; transformers would load such an export with those parts dropped or left random. --no-architecture-check exports such a model anyway, with a warning, for hf-to-dcp to read back (see Resharding).

MoE

An MoE model exports as MixtralForCausalLM, under the names a Mixtral checkpoint uses (see Key mapping); transformers 5 packs each layer’s experts when it loads them. Packed experts (moe_packed_experts) are written as one tensor per expert, like unpacked ones.

A Mixtral model routes with softmax top-k in every layer and has no shared experts, so besides the settings above dcp-to-hf refuses an MoE model with moe_shared_experts > 0, moe_frequency > 1 or a moe_router other than "softmax_topk" (see What transformers can load).

transformers has no expert capacity: the export of a model with moe_capacity_factor > 0 drops no tokens, where KempnerForge drops those past an expert’s capacity in evaluation as in training. dcp-to-hf warns about it.

Dtypes

The export dtype is the first of:

  1. --dtype, when given: bfloat16, float16 or float32.

  2. export_dtype in the [checkpoint] table of the --config TOML: bfloat16 or float32.

  3. bfloat16, that field’s default.

--dtype bfloat16      # wins over export_dtype = "float32" in the TOML
--dtype float16       # e.g. for vLLM; only the flag accepts float16
--dtype float32       # rarely useful; largest files

The script logs the dtype and where it came from, e.g. Export dtype: float32 (from checkpoint.export_dtype), and records it as torch_dtype in the exported config.json, so from_pretrained(..., dtype="auto") loads the weights at the precision they were written in.

At bfloat16 or float16, transformers’ logits can differ from KempnerForge’s at the same precision, enough to change some predicted tokens: it rounds the normalized activations before scaling them by the norm weight, where KempnerForge scales first, and Mixtral’s router takes its softmax in float32, so a token whose top experts nearly tie can route to another one. A float32 export of an MoE model that passes the architecture check gives the same logits while no token passes an expert’s capacity (see MoE).

No optimizer / scheduler / RNG — only weights. If you need those, keep the DCP checkpoint; HF format doesn’t carry them. A schedule_free_adamw checkpoint’s weights are its averaged weights x, the point to evaluate and deploy (see Optimizers); one written before checkpoints held x has the training point y instead.

With PP

A PP checkpoint holds one DCP index per stage, in pp0/ to pp{n-1}/, and its metadata.json records n as pp (see DCP model § With pipeline parallelism). dcp-to-hf reads each stage’s tensors from that stage’s own index, into the one full model, and writes the same files as for the same weights saved without PP. Before reading any tensor it checks the stages together as it checks a flat checkpoint: for the experts they hold, and for derived buffers they predate, such as the sigmoid router’s FP32 masters (see Key mapping). It refuses, naming the stage directories, a checkpoint in which:

  • a stage directory has no .metadata, because its save did not complete;

  • two stage directories hold the same tensor, as when a stage directory comes from another save;

  • no stage holds a tensor the model has, as when a stage directory is missing from a checkpoint saved before the degree was recorded, or the config is not the one the run trained with.

A PP run never ties the token embedding to the output head (tie_embeddings needs pp = 1), so its stages hold the two separately, and dcp-to-hf refuses a config with tie_embeddings = true for a PP checkpoint. Export it with the config the run trained with. Export at --dtype float32 to keep the weights exact for hf-to-dcp, which is how a PP run’s weights move to another pp (see Resharding § PP).

HuggingFace → DCP

# From a local HF directory
uv run python scripts/convert_checkpoint.py hf-to-dcp \
    --hf-dir /shared/models/llama-3.1-8b \
    --dcp-dir checkpoints/pretrained \
    --config configs/model/llama_8b.toml

# Or from the HF Hub directly
uv run python scripts/convert_checkpoint.py hf-to-dcp \
    --hf-dir meta-llama/Llama-3.1-8B \
    --dcp-dir checkpoints/pretrained \
    --config configs/model/llama_8b.toml

What happens:

  1. Load the HF state dict from the standard weight files at the top of the model, in the order transformers loads them by default: model.safetensors, else the shards model.safetensors.index.json names, and otherwise the same for pytorch_model.bin. An adapter or another variant beside them is left out; there is no variant or subfolder choice, and a config’s transformers_weights is not read.

    • Local dir: those files; a directory with none of these names gives every *.safetensors file, or else every pytorch_model*.bin.

    • HF ID: the same files, each downloaded with huggingface_hub.hf_hub_download or taken from its cache, the shards at the commit their index came from. None of the repository’s code runs and no Hugging Face model is built, and a shard that cannot be had fails the import. A name whose lookup fails without the Hub saying it has no such file, as offline, is passed over like a missing one, and hf_hub_download takes each name from the cache when it cannot reach the Hub, so a cached model imports with HF_HUB_OFFLINE=1. With none of the names had, the error names the first failed lookup and chains its error.

  2. Convert keys HF → KempnerForge naming. The names converted are the ones stored in the files, as Key mapping lists them, Mixtral’s included; any other name is skipped with a warning. A checkpoint with tied embeddings may store no lm_head.weight: the output head then takes the token embedding, whether tie_embeddings is true or false.

  3. model.load_state_dict(converted, strict=False) — missing KF keys (e.g. learned RoPE frequencies) stay at their default init and are logged as warnings.

  4. Write as DCP via dcp.save({"model": model.state_dict()}, ...).

checkpoints/pretrained/
├── .metadata               ← DCP index
└── __*_0.distcp            ← weight shards

Point a training config at this directory via [checkpoint] load_path = "checkpoints/pretrained" and training picks it up like any other DCP checkpoint, as a warm start at step 0. load_path is used while the run’s checkpoint.dir holds no checkpoint; once the run has saved one, a restart resumes from it. A run with PP loads it too: the checkpoint has no pp{N}/ stages, and each stage loads its own layers from the one index (see Resharding § PP).

Key mapping

KempnerForge uses Llama-style naming with a few differences. The main translations:

KempnerForge

HuggingFace

token_embedding.embedding.weight

model.embed_tokens.weight

output_head.proj.weight

lm_head.weight

norm.weight

model.norm.weight

layers.{i}.attention.{q,k,v,o}_proj.weight

model.layers.{i}.self_attn.{q,k,v,o}_proj.weight

layers.{i}.attention_norm.weight

model.layers.{i}.input_layernorm.weight

layers.{i}.mlp_norm.weight

model.layers.{i}.post_attention_layernorm.weight

layers.{i}.mlp.{gate,up,down}_proj.weight

model.layers.{i}.mlp.{gate,up,down}_proj.weight

MoE-specific, in Mixtral’s names:

KempnerForge

HuggingFace

layers.{i}.mlp.router.gate.weight

model.layers.{i}.block_sparse_moe.gate.weight

layers.{i}.mlp.experts.{j}.gate_proj.weight

model.layers.{i}.block_sparse_moe.experts.{j}.w1.weight

layers.{i}.mlp.experts.{j}.down_proj.weight

model.layers.{i}.block_sparse_moe.experts.{j}.w2.weight

layers.{i}.mlp.experts.{j}.up_proj.weight

model.layers.{i}.block_sparse_moe.experts.{j}.w3.weight

layers.{i}.mlp.{gate,down,up}_w (packed)

the same w1, w2, w3 of each expert, its slice transposed

hf-to-dcp reads these names, and the ones exports used before them: model.layers.{i}.mlp.gate.weight for the router and model.layers.{i}.mlp.experts.{j}.{gate,up,down}_proj.weight for the experts. It also splits the experts a checkpoint holds packed, as mlp.experts.gate_up_proj and mlp.experts.down_proj, which transformers 5 saves with save_original_format=False and by default saves under the names above. For a model with packed experts it stacks each layer’s experts into gate_w, up_w and down_w. Mixtral has no expert bias or shared experts: dcp-to-hf refuses models with them unless given --no-architecture-check (see MoE), and then writes them as model.layers.{i}.mlp.expert_bias and model.layers.{i}.mlp.shared_experts.*, which hf-to-dcp reads back.

The sigmoid router’s fp32_ema_bits and fp32_bias_bits, FP32 masters of its balancing state held as int32 bit patterns, are not exported. hf-to-dcp derives them from the imported expert_bias and expert_ema, and dcp-to-hf converts a checkpoint saved before they existed (see Aux loss and balancing).

A checkpoint saved with expert parallelism holds every expert under its global index, as one saved without it does (see Expert parallelism § Checkpoints), so dcp-to-hf exports all num_experts of each layer. An EP checkpoint saved before that layout holds one EP rank’s experts of each layer, and dcp-to-hf refuses it with an error that says how many it holds.

The mapping logic is in _kf_to_hf_key and _hf_to_kf_key in convert_checkpoint.py — order-sensitive string replacements (e.g. .attention_norm. handled before .attention. to avoid partial matches).

Generated config.json

For a dense model:

{
  "architectures": ["LlamaForCausalLM"],
  "model_type": "llama",
  "hidden_size": 4096,
  "intermediate_size": 14336,
  "num_hidden_layers": 32,
  "num_attention_heads": 32,
  "num_key_value_heads": 8,
  "head_dim": 128,
  "vocab_size": 128256,
  "max_position_embeddings": 4096,
  "rope_theta": 500000.0,
  "rms_norm_eps": 1e-06,
  "tie_word_embeddings": false,
  "torch_dtype": "bfloat16"
}

torch_dtype is the export dtype, so a float32 or float16 export names that dtype instead of bfloat16.

For MoE the architecture is MixtralForCausalLM, intermediate_size is the width of one expert (computed_expert_ffn_hidden_dim), and three extra fields (num_local_experts, num_experts_per_tok, router_aux_loss_coef) are added.

Not included: tokenizer files. Copy tokenizer.json, tokenizer_config.json, special_tokens_map.json, etc. from the source HF repo separately (they’re not part of the weights).

Limitations

  • One architecture at a time — the converter assumes the model is Llama or Mixtral style. Models with non-standard attention variants (MLA, linear attention) need additional mapping.

  • No optimizer state — HF format doesn’t carry optimizer state, so hf-to-dcp produces a checkpoint with model weights only. Training starts with a fresh optimizer, and with no train_state.pt the step counter, LR schedule and data position start fresh too.

  • Missing keys on hf-to-dcp — the HF model may not have some KempnerForge-specific buffers (e.g. freqs_cis for RoPE). These stay at default init; the warning is informational, not an error.

  • Key renames on dcp-to-hf — if you’ve added custom modules to the model, they’ll land in the HF output under the KempnerForge names (no translation rule). Downstream HF code won’t recognize them.

See also