magic-cap1b-data / generation /export_checkpoint.py
leejason2025's picture
Upload generation/export_checkpoint.py with huggingface_hub
cd9c7a5 verified
Raw History Blame Contribute Delete
8.47 kB
"""Export a bergson MAGIC training checkpoint to a HuggingFace model directory.
bergson's MAGIC trainer saves its trajectory as torch distributed-checkpoint
(DCP) directories (`step_N.ckpt/` with `.metadata` + `__0_0.distcp`), written
by `TrainerState.save` in bergson/magic/trainer.py. That state dict is flat:
<param name> e.g. "gpt_neox.embed_in.weight" (trainable params)
<buffer name> e.g. "gpt_neox.rotary_emb.inv_freq"
".batch_index" scalar int64 — number of optimizer updates applied
".cuda_rng_state" / ".cpu_rng_state"
"opt_state/..." flattened optimizer PyTree (Adam moments, step counts)
This tool rebuilds a standard HF model directory from one such checkpoint:
model skeleton from --init-model (the HF dir training started from), weights
from the DCP checkpoint (optimizer/RNG entries stripped), saved fp32 via
save_pretrained, tokenizer files copied from the init dir. The result loads
with plain AutoModelForCausalLM.from_pretrained — no bergson required.
Step semantics (bergson `Trainer.train`): `step_N.ckpt` is saved BEFORE step
N runs, so it holds the state after exactly N optimizer updates. step_0 is
the untrained init; the state bergson's "Baseline loss" is computed at is
ONE update past the last saved checkpoint (see tools/README.md).
By default the export fails if the weights are identical to --init-model
(catches pointing --ckpt at the wrong run). Pass --allow-identical when
exporting step_0.ckpt, which legitimately equals the init model.
Usage:
~/berg-venv/bin/python tools/export_checkpoint.py \
--ckpt pilot/runs/stage100/checkpoints/step_999.ckpt \
--init-model pilot/models/pythia14m-init \
--out /path/to/exported-hf-dir
"""
from __future__ import annotations
import argparse
import shutil
from pathlib import Path
import torch
import torch.distributed.checkpoint as dcp
from torch.distributed.checkpoint import FileSystemReader
from torch.distributed.checkpoint.metadata import TensorStorageMetadata
from transformers import AutoModelForCausalLM, AutoTokenizer
RNG_KEYS = {".batch_index", ".cuda_rng_state", ".cpu_rng_state"}
OPT_PREFIX = "opt_state/"
def read_weight_metadata(ckpt: Path) -> tuple[dict, bool]:
"""Map of model-weight key -> TensorStorageMetadata (shape/dtype), plus
whether the checkpoint carries a .batch_index entry.
Drops optimizer entries (opt_state/...) and RNG/counter entries — only
parameters and buffers belong in the exported model.
"""
meta = FileSystemReader(str(ckpt)).read_metadata().state_dict_metadata
weights = {
k: v
for k, v in meta.items()
if k not in RNG_KEYS
and not k.startswith(OPT_PREFIX)
and isinstance(v, TensorStorageMetadata)
}
if not weights:
raise SystemExit(f"no model weights found in {ckpt} — is this a "
"TrainerState DCP checkpoint (step_N.ckpt)?")
return weights, ".batch_index" in meta
def main() -> None:
ap = argparse.ArgumentParser(
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
)
ap.add_argument("--ckpt", type=Path, required=True,
help="path to a step_N.ckpt DCP directory")
ap.add_argument("--init-model", type=Path, required=True,
help="HF model dir the training run started from")
ap.add_argument("--out", type=Path, required=True,
help="output HF model dir (created/overwritten)")
ap.add_argument("--allow-identical", action="store_true",
help="don't fail when exported weights equal the init "
"model (expected only for step_0.ckpt)")
args = ap.parse_args()
if not (args.ckpt / ".metadata").exists():
raise SystemExit(f"{args.ckpt} has no .metadata file — incomplete or "
"not a DCP checkpoint")
# Skeleton in fp32: architecture/config/buffers from the init dir. bergson
# trained in the same transformers version's module namespace, so the
# checkpoint's param names match this model's named_parameters exactly.
model = AutoModelForCausalLM.from_pretrained(args.init_model,
dtype=torch.float32)
model_params = dict(model.named_parameters(remove_duplicate=False))
model_buffers = dict(model.named_buffers(remove_duplicate=False))
weight_meta, has_batch_index = read_weight_metadata(args.ckpt)
param_keys = [k for k in weight_meta if k in model_params]
buffer_keys = [k for k in weight_meta if k in model_buffers]
unknown = sorted(set(weight_meta) - set(param_keys) - set(buffer_keys))
if unknown:
raise SystemExit(
f"checkpoint keys not present in the --init-model skeleton "
f"(wrong init model, or transformers renamed modules since "
f"training?): {unknown[:10]}{' ...' if len(unknown) > 10 else ''}")
# bergson checkpoints only requires_grad params; on PEFT/partial-freeze
# runs the frozen params legitimately keep their init values.
missing = sorted(set(model_params) - set(param_keys))
if missing:
print(f"note: {len(missing)} model params not in checkpoint — kept at "
f"init values (frozen during training?): {missing[:5]}"
f"{' ...' if len(missing) > 5 else ''}")
# Allocate destination tensors in the checkpoint's own dtype/shape so
# dcp.load never has to cast, then convert to fp32 when copying into the
# model. Loading is single-process (no dist init needed for DCP reads).
request: dict[str, torch.Tensor] = {
k: torch.empty(weight_meta[k].size, dtype=weight_meta[k].properties.dtype)
for k in param_keys + buffer_keys
}
if has_batch_index:
request[".batch_index"] = torch.empty((), dtype=torch.int64)
dcp.load(request, checkpoint_id=str(args.ckpt))
if has_batch_index:
n_updates = int(request.pop(".batch_index"))
print(f"checkpoint batch_index: {n_updates} optimizer updates applied")
# Copy into the model, tracking the delta vs the init weights per tensor
# (before overwriting) so no second full copy of the model is needed.
# "Differs" is judged with torch.equal (exact, NaN-safe): a subtraction-
# based check would call a NaN-poisoned tensor unchanged (NaN > 0 is
# False), hiding a diverged checkpoint. max|delta| is reporting only.
max_delta, n_changed = 0.0, 0
with torch.no_grad():
for k in param_keys:
new = request[k].to(torch.float32)
if not torch.equal(new, model_params[k]):
n_changed += 1
d = (new - model_params[k]).abs()
max_delta = max(max_delta, d[d.isfinite()].max().item()
if d.isfinite().any() else float("inf"))
model_params[k].copy_(new)
for k in buffer_keys:
model_buffers[k].copy_(request[k].to(model_buffers[k].dtype))
print(f"loaded {len(param_keys)} param tensors, {len(buffer_keys)} "
f"buffers; {n_changed}/{len(param_keys)} tensors differ from init "
f"(max |delta| = {max_delta:.6g})")
if n_changed == 0 and not args.allow_identical:
raise SystemExit(
"exported weights are identical to --init-model. That is only "
"expected for step_0.ckpt; otherwise the --ckpt/--init-model "
"pairing is wrong. Pass --allow-identical to export anyway.")
# With tied embeddings both names appear in the checkpoint pointing at the
# same trained tensor; re-tie so save_pretrained's dedup sees shared
# storage. No-op for untied configs (e.g. Pythia).
if getattr(model.config, "tie_word_embeddings", False):
model.tie_weights()
args.out.mkdir(parents=True, exist_ok=True)
model.save_pretrained(args.out, safe_serialization=True)
tokenizer = AutoTokenizer.from_pretrained(args.init_model)
tokenizer.save_pretrained(args.out)
# Older transformers keeps chat templates only in tokenizer_config.json;
# if the init dir shipped a standalone jinja file that the round-trip
# didn't rewrite, carry it over verbatim.
jinja = args.init_model / "chat_template.jinja"
if jinja.exists() and not (args.out / "chat_template.jinja").exists():
shutil.copy2(jinja, args.out)
print(f"exported HF model -> {args.out}")
if __name__ == "__main__":
main()