KAWK50M-Project / kawk50m /checkpoint.py
Infinity08's picture
Add files using upload-large-folder tool
91ac3cc verified
Raw History Blame Contribute Delete
3.5 kB
from __future__ import annotations
import json
import os
import random
import uuid
from pathlib import Path
from typing import Any
import numpy as np
import torch
def resolve_checkpoint(resume: str | Path, output_dir: str | Path) -> Path:
if str(resume).lower() != "latest":
path = Path(resume)
else:
latest_file = Path(output_dir) / "latest_checkpoint.txt"
if not latest_file.is_file():
raise FileNotFoundError(
f"Cannot resume latest: {latest_file} does not exist"
)
stored = latest_file.read_text(encoding="utf-8").strip()
path = Path(stored)
if not path.is_absolute():
path = Path(output_dir) / path
if not (path / "model").is_dir() or not (path / "trainer_state.pt").is_file():
raise FileNotFoundError(f"Invalid checkpoint directory: {path}")
return path.resolve()
def capture_rng_state() -> dict[str, Any]:
state: dict[str, Any] = {
"python": random.getstate(),
"numpy": np.random.get_state(),
"torch": torch.get_rng_state(),
}
if torch.cuda.is_available():
state["cuda"] = torch.cuda.get_rng_state_all()
return state
def restore_rng_state(state: dict[str, Any]) -> None:
random.setstate(state["python"])
np.random.set_state(state["numpy"])
torch.set_rng_state(state["torch"])
if torch.cuda.is_available() and "cuda" in state:
torch.cuda.set_rng_state_all(state["cuda"])
def load_training_state(path: Path) -> dict[str, Any]:
try:
return torch.load(path, map_location="cpu", weights_only=False)
except TypeError:
return torch.load(path, map_location="cpu")
def save_checkpoint(
*,
output_dir: Path,
step: int,
model: Any,
tokenizer: Any,
optimizer: torch.optim.Optimizer,
scheduler: Any,
training_config: dict[str, Any],
world_size: int,
) -> Path:
output_dir.mkdir(parents=True, exist_ok=True)
final_path = output_dir / f"checkpoint-{step:08d}"
if final_path.exists():
return final_path
temporary_path = output_dir / f".checkpoint-{step:08d}-{uuid.uuid4().hex}.tmp"
temporary_path.mkdir(parents=False, exist_ok=False)
try:
model.save_pretrained(
temporary_path / "model",
safe_serialization=True,
max_shard_size="2GB",
)
tokenizer.save_pretrained(temporary_path / "tokenizer")
state = {
"step": step,
"world_size": world_size,
"optimizer": optimizer.state_dict(),
"scheduler": scheduler.state_dict(),
"rng": capture_rng_state(),
"training_config": training_config,
}
torch.save(state, temporary_path / "trainer_state.pt")
with (temporary_path / "state_summary.json").open(
"w", encoding="utf-8"
) as handle:
json.dump(
{"step": step, "world_size": world_size},
handle,
ensure_ascii=False,
indent=2,
)
handle.write("\n")
os.replace(temporary_path, final_path)
except BaseException:
# Preserve a failed temporary checkpoint for inspection rather than deleting it.
raise
latest_temp = output_dir / ".latest_checkpoint.tmp"
latest_temp.write_text(final_path.name + "\n", encoding="utf-8")
os.replace(latest_temp, output_dir / "latest_checkpoint.txt")
return final_path