File size: 5,986 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 | """Token accounting, optimizer objectives, and resume boundaries."""
from copy import deepcopy
import pytest
import torch
from pat.training import (
TrainingConfig,
backward_loss,
validate_resume_plan,
validate_resume_state,
)
def test_schedule_token_boundaries_and_cooldown():
config = TrainingConfig(tokens=200_000_000)
assert config.stable_end == 140_000_000
assert config.lr_at(0) == config.learning_rate / 100_000_000
assert config.lr_at(50_000_000) == config.learning_rate / 2
assert config.lr_at(100_000_000) == config.learning_rate
assert config.lr_at(140_000_000) == config.learning_rate
assert config.lr_at(170_000_000) == pytest.approx(config.learning_rate * 0.55)
assert config.lr_at(200_000_000) == pytest.approx(config.learning_rate * 0.1)
assert config.lr_at(200_050_000) == config.lr_at(200_000_000)
# Floating point multiplication must not add a spurious cooldown token.
assert TrainingConfig(tokens=100, warmup_tokens=10, decay_fraction=0.14).stable_end == 86
@pytest.mark.parametrize("architecture", ["PAT", "FA"])
def test_distributed_objective_with_unequal_rank_and_microstep_counts(architecture):
# Unequal lexical/valid-target proportions reveal weighting differences
# which equal-sized batches would hide. Entries are [microstep, rank].
lexical = torch.tensor([[3, 7], [11, 5]], dtype=torch.float64)
targets = torch.tensor([[4, 9], [12, 6]], dtype=torch.float64)
coefficients = torch.tensor([[2., 3.], [5., 7.]], dtype=torch.float64)
parameter = torch.tensor(1.25, dtype=torch.float64, requires_grad=True)
global_window_targets = int(targets.sum())
global_window_lexical = int(lexical.sum())
objective = 0.0
for microstep in range(2):
for rank in range(2):
summed_loss = parameter.square() * coefficients[microstep, rank]
loss = backward_loss(
summed_loss, architecture, world_size=2,
local_lexical=int(lexical[microstep, rank]),
global_microbatch_targets=int(targets[microstep].sum()),
global_window_targets=global_window_targets,
global_window_lexical=global_window_lexical,
global_loss_sum=(parameter.square() * coefficients[microstep].sum()).detach(),
)
objective = objective + loss / 2 # DDP gradient mean.
objective.backward()
if architecture == "PAT":
expected_coefficient = coefficients.sum() / targets.sum()
else:
expected_coefficient = sum(
2 * lexical[m, r] * coefficients[m, r] / (targets[m].sum() * lexical.sum())
for m in range(2) for r in range(2)
)
assert parameter.grad == pytest.approx(float(2 * parameter.detach() * expected_coefficient))
@pytest.mark.parametrize("architecture,micro,lexical,window,content,expected_gradient", [
("PAT", 50238, 23228, 98102, 97126, 2.0386942196637392e-05),
("FA", 45244, 23191, 98895, 96952, 2.1147630832274444e-05),
])
def test_backward_preserves_fp32_normalization_order(
architecture, micro, lexical, window, content, expected_gradient,
):
# These unequal-count fixtures distinguish the original two-stage FP32
# gradient from collapsing its algebra into one multiplier by one ULP.
summed_loss = torch.tensor(123456.789, requires_grad=True)
loss = backward_loss(
summed_loss, architecture, world_size=2, local_lexical=lexical,
global_microbatch_targets=micro, global_window_targets=window,
global_window_lexical=content,
global_loss_sum=summed_loss.detach().double() * 2,
)
gradient = torch.autograd.grad(loss, summed_loss)[0]
assert torch.equal(gradient, torch.tensor(expected_gradient))
collapsed = 2 / window if architecture == "PAT" else 4 * lexical / (micro * content)
assert not torch.equal(gradient, torch.tensor(collapsed))
def test_resume_rejects_changed_data_horizon_world_size_and_partial_update():
expected = {
"format": "pat-training-state-1", "data_fingerprint": "train-digest",
"validation_fingerprint": "validation-digest", "world_size": 2,
"training_config": TrainingConfig(tokens=200_000_000, accumulation_steps=2).to_dict(),
}
saved = {**deepcopy(expected), "seen_tokens": 123456, "step": 2,
"epoch": 0, "cursor": 8, "plan_sha256": "batch-plan-digest"}
validate_resume_state(saved, expected)
for field, value in [("data_fingerprint", "different"), ("validation_fingerprint", "different"),
("world_size", 1), ("cursor", 7), ("seen_tokens", -1),
("plan_sha256", None)]:
changed = {**deepcopy(saved), field: value}
with pytest.raises(ValueError):
validate_resume_state(changed, expected)
changed = deepcopy(saved)
changed["training_config"]["tokens"] += 100000000
with pytest.raises(ValueError, match="training_config"):
validate_resume_state(changed, expected)
def test_resume_plan_accepts_epoch_boundary_and_rejects_out_of_bounds_cursor():
# Checkpoints are saved before the end-of-epoch cursor resets. Equal is
# valid; greater would leave the training loop unable to make progress.
state = {"cursor": 12, "plan_sha256": "same-plan"}
validate_resume_plan(state, 12, "same-plan")
with pytest.raises(ValueError, match="exceeds"):
validate_resume_plan(state, 8, "same-plan")
with pytest.raises(ValueError, match="batch order"):
validate_resume_plan(state, 12, "different-plan")
validate_resume_plan({"cursor": 0, "plan_sha256": None}, 12, "new-plan")
@pytest.mark.parametrize("values", [
{"warmup_tokens": 140_000_000}, {"decay_fraction": float("nan")},
{"learning_rate": float("inf")}, {"accumulation_steps": 0},
])
def test_invalid_training_settings_fail_before_training(values):
with pytest.raises(ValueError):
TrainingConfig(tokens=200_000_000, **values)
|