File size: 3,503 Bytes
91ac3cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
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