File size: 6,647 Bytes
643267a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
"""The fixed optimizer, token-clock schedule, and model-family objectives."""

from __future__ import annotations

import math
from dataclasses import asdict, dataclass
from decimal import ROUND_CEILING, Decimal

import torch


@dataclass(frozen=True)
class TrainingConfig:
    tokens: int = 9_520_000_000
    warmup_tokens: int = 100_000_000
    decay_fraction: float = 0.3
    learning_rate: float = 0.00025
    min_lr_ratio: float = 0.1
    weight_decay: float = 0.01
    microbatch_tokens: int = 25000
    accumulation_steps: int = 1
    seed: int = 42
    checkpoint_every: int = 100_000_000
    validate_every: int = 200_000_000

    def __post_init__(self):
        for name in ("tokens", "microbatch_tokens", "accumulation_steps", "checkpoint_every", "validate_every"):
            value = getattr(self, name)
            if type(value) is not int or value <= 0:
                raise ValueError(f"{name} must be a positive integer")
        if type(self.warmup_tokens) is not int or self.warmup_tokens < 0:
            raise ValueError("warmup_tokens must be a nonnegative integer")
        if not 0 < self.decay_fraction < 1:
            raise ValueError("decay_fraction must be between zero and one")
        if self.warmup_tokens >= self.stable_end:
            raise ValueError("Warmup must finish before the decay phase")
        if not math.isfinite(self.learning_rate) or self.learning_rate <= 0:
            raise ValueError("learning_rate must be finite and positive")
        if not 0 < self.min_lr_ratio <= 1 or not 0 <= self.weight_decay < float("inf"):
            raise ValueError("Invalid minimum learning rate or weight decay")

    @property
    def stable_end(self) -> int:
        decay = Decimal(self.tokens) * Decimal(str(float(self.decay_fraction)))
        return self.tokens - int(decay.to_integral_value(rounding=ROUND_CEILING))

    def to_dict(self) -> dict:
        return asdict(self)

    def lr_at(self, seen_tokens: int) -> float:
        """Learning rate BEFORE the update, measured in lexical input tokens."""
        if seen_tokens < self.warmup_tokens:
            ratio = max(1, seen_tokens) / self.warmup_tokens
        elif seen_tokens <= self.stable_end:
            ratio = 1.0
        else:
            progress = min(1.0, (seen_tokens - self.stable_end) / (self.tokens - self.stable_end))
            ratio = self.min_lr_ratio + (1 - self.min_lr_ratio) * (1 + math.cos(math.pi * progress)) / 2
        return self.learning_rate * ratio


def optimizer_for(model, config: TrainingConfig) -> torch.optim.AdamW:
    """Decay matrices; exclude biases, normalization, and learned QK scales."""
    groups: dict[str, list] = {"decay": [], "no_decay": [], "qk_scale": []}
    for name, parameter in model.named_parameters():
        if not parameter.requires_grad:
            continue
        if name.endswith("qk_log_scale"):
            key = "qk_scale"
        elif parameter.ndim == 1 or name.endswith(".bias") or ".norm" in name:
            key = "no_decay"
        else:
            key = "decay"
        groups[key].append(parameter)
    return torch.optim.AdamW(
        [{"params": parameters, "weight_decay": config.weight_decay if name == "decay" else 0.0}
         for name, parameters in groups.items() if parameters],
        lr=config.lr_at(0), betas=(0.9, 0.999), eps=1e-8, fused=True, foreach=False,
    )


def backward_loss(
    loss_sum: torch.Tensor,
    architecture: str,
    *,
    world_size: int,
    local_lexical: int,
    global_microbatch_targets: int,
    global_window_targets: int,
    global_window_lexical: int,
    global_loss_sum: torch.Tensor | None = None,
) -> torch.Tensor:
    """Construct the objective in the released training arithmetic order.

    Normalize each microstep first, then apply its accumulation weight.
    Combining these factors changes FP32 gradients. In distributed training,
    a detached correction displays the global mean while the local gradient
    retains compensation for DDP averaging. The caller supplies the globally
    reduced loss sum in float64 and synchronizes every backward microstep.
    """
    if min(world_size, global_microbatch_targets, global_window_targets, global_window_lexical) <= 0:
        raise ValueError("Every optimizer window must have positive target counts")
    if world_size > 1:
        if global_loss_sum is None:
            raise ValueError("Distributed training requires the global loss sum")
        denominator = loss_sum.new_tensor(global_microbatch_targets).clamp_min(1)
        scaled = loss_sum * float(world_size) / denominator
        global_mean = (
            global_loss_sum.to(dtype=torch.float64)
            / global_loss_sum.new_tensor(global_microbatch_targets, dtype=torch.float64).clamp_min(1)
        ).to(dtype=scaled.dtype)
        normalized = scaled + (global_mean.detach() - scaled.detach())
    else:
        normalized = loss_sum / float(global_microbatch_targets)
    if architecture == "PAT":
        outer = float(global_microbatch_targets) / float(global_window_targets)
    elif architecture == "FA":
        outer = float(world_size) * float(local_lexical) / float(global_window_lexical)
    else:
        raise ValueError("Architecture must be PAT or FA")
    return normalized * outer


def validate_resume_state(restored: dict, expected: dict) -> None:
    """Reject a changed data/optimizer contract or an incomplete update cursor."""
    for field in ("format", "data_fingerprint", "validation_fingerprint", "training_config", "world_size"):
        if restored.get(field) != expected[field]:
            raise ValueError(f"Resume contract differs: {field}")
    for field in ("seen_tokens", "step", "epoch", "cursor"):
        value = restored.get(field)
        if type(value) is not int or value < 0:
            raise ValueError(f"Invalid resume counter: {field}")
    quantum = expected["world_size"] * expected["training_config"]["accumulation_steps"]
    if restored["cursor"] % quantum:
        raise ValueError("Resume cursor is not at a complete optimizer boundary")
    if restored["cursor"] and not isinstance(restored.get("plan_sha256"), str):
        raise ValueError("Resume state is missing its batch-plan identity")


def validate_resume_plan(state: dict, plan_length: int, plan_sha256: str) -> None:
    """Admit a saved cursor only within the regenerated epoch's exact plan."""
    if state["cursor"] > plan_length:
        raise ValueError("Resume cursor exceeds the saved epoch's batch plan")
    if state["cursor"] and state["plan_sha256"] != plan_sha256:
        raise ValueError("Resume batch order differs from the saved plan")