xuan-luo's picture
download
raw
10.7 kB
from __future__ import annotations
import copy
import math
import tomllib
import unittest
from pathlib import Path
import torch
from torch import nn
from .attention import reference_attention, segmented_flash_attention, update_rolling_state
from .budget import TARGET_PARAMETERS, budget, ffn_widths
def load(path):
with path.open("rb") as handle:
return tomllib.load(handle)
class ProjectionShell(nn.Module):
"""Shape/name oracle for the r-independent learnable attention structure."""
def __init__(self, roll_dim):
super().__init__()
self.roll_dim = roll_dim # configuration only, never a parameter dimension
self.linear_qkv = nn.Linear(512, 1024, bias=False)
self.linear_proj = nn.Linear(512, 512, bias=False)
class SharedProjectionTestMixin:
ROLL_DIM: int
HERE: Path
BASE: Path
architecture_arguments: object
def test_budget_and_cache(self):
result = budget(self.ROLL_DIM)
self.assertEqual(result["parameters"], TARGET_PARAMETERS)
slots = 64 // self.ROLL_DIM
self.assertEqual(result["rolling_elements_per_token"],
2 * 4 * self.ROLL_DIM * (12 + slots - 1))
self.assertEqual(result["local_ring_elements_per_sequence"], 786432)
self.assertEqual(ffn_widths(), [2166] * 4 + [2165] * 8)
for value in result["contexts"].values():
self.assertEqual(value["total_cache_bytes"],
value["rolling_bytes"] + value["local_ring_bytes"])
def test_recipe_is_inherited_and_isolated(self):
previous = None
for stage in ("2k", "8k", "32k"):
ours = load(self.HERE / f"configs/train_{stage}.toml")
original = load(self.BASE / f"configs/train_{stage}.toml")
self.architecture_arguments(ours)
for section in ("training", "schedule", "optimizer", "checkpoint"):
self.assertEqual(ours[section], original[section])
for field in ("seq_length", "micro_batch_size", "global_batch_size", "num_workers"):
self.assertEqual(ours["data"][field], original["data"][field])
for field in ("train_data_prefix", "valid_data_prefix", "tokenizer_dir"):
self.assertEqual(ours["paths"][field], original["paths"][field])
self.assertEqual(ours["paths"].get("init_checkpoint"), previous)
previous = ours["paths"]["output_dir"]
def test_fixed_recipe_uses_fresh_isolated_outputs(self):
previous = None
for stage in ("2k", "8k", "32k"):
path = self.HERE / f"configs/fixed_train_{stage}.toml"
if not path.exists():
self.skipTest("fixed retraining configs are not present")
ours = load(path)
self.architecture_arguments(ours)
self.assertIn("runs_fixed_20261024", ours["paths"]["output_dir"])
self.assertEqual(ours["paths"].get("init_checkpoint"), previous)
previous = ours["paths"]["output_dir"]
def test_rejects_foreign_checkpoint_and_shape(self):
good = load(self.HERE / "configs/train_2k.toml")
for field, value in (("rolling_state_dim", 64), ("local_window", 127),
("kv_channels", 32)):
bad = copy.deepcopy(good)
bad["model"][field] = value
with self.assertRaises(ValueError): self.architecture_arguments(bad)
good["paths"]["init_checkpoint"] = str(self.BASE / "runs/train_2k/checkpoints")
with self.assertRaises(ValueError): self.architecture_arguments(good)
def test_production_fifo_cross_layer_and_gradients_no_refresh(self):
torch.manual_seed(2)
fresh = [torch.randn(2, 1, 4, 64, requires_grad=True) for _ in range(12)]
state = None
states = []
chunks = None
for layer in range(12):
state = update_rolling_state(state, fresh[layer], self.ROLL_DIM)
states.append(state)
chunks = (list(fresh[layer].split(self.ROLL_DIM, -1)) if chunks is None
else chunks[1:] + [fresh[layer][..., -self.ROLL_DIM:]])
torch.testing.assert_close(state, torch.cat(chunks, -1))
# Layers 5 and 9 (one-indexed) follow exactly the same FIFO update.
self.assertIsNot(states[4], fresh[4])
self.assertIsNot(states[8], fresh[8])
gradients = torch.autograd.grad(sum(x.square().mean() for x in states), fresh)
self.assertTrue(all(torch.isfinite(x).all() for x in gradients))
self.assertTrue(all(x.abs().sum() > 0 for x in gradients))
def test_boundaries_lengths_causality_and_no_duplicate(self):
for length in (127, 128, 129, 130):
qpos = torch.arange(length)[:, None]
kpos = torch.arange(length)[None, :]
causal = kpos <= qpos
local = causal & ((qpos - kpos) < 128)
distant = causal & ((qpos - kpos) >= 128)
self.assertTrue(torch.equal(local ^ distant, causal))
self.assertFalse((local & distant).any())
qpos, kpos = 129, torch.tensor([0, 1, 2])
distance = qpos - kpos
self.assertEqual((distance < 128).tolist(), [False, False, True])
self.assertEqual(distance.tolist(), [129, 128, 127])
torch.manual_seed(4)
tensors = [torch.randn(6, 1, heads, 64, dtype=torch.double)
for heads in (2, 1, 1, 1, 1)]
q, fk, fv, rk, rv = [x.requires_grad_() for x in tensors]
out = reference_attention(q, fk, fv, rk, rv, window=3)
changed = [x.detach().clone() for x in (q, fk, fv, rk, rv)]
for x in changed: x[4:] += 100
out_changed = reference_attention(*changed, window=3)
torch.testing.assert_close(out[:4], out_changed[:4])
def test_shared_softmax_forward_backward_and_empty_segment(self):
torch.manual_seed(7)
q = torch.randn(5, 1, 2, 64, dtype=torch.double, requires_grad=True)
values = [torch.randn(5, 1, 1, 64, dtype=torch.double, requires_grad=True)
for _ in range(4)]
actual = reference_attention(q, *values, window=3)
# Independent construction of the one-softmax definition.
fk, fv, rk, rv = [x.repeat_interleave(2, 2) for x in values]
scores = []
outputs = []
for t in range(5):
keys, vals = [], []
for s in range(t + 1):
local = t - s < 3
keys.append((fk if local else rk)[s])
vals.append((fv if local else rv)[s])
key = torch.stack(keys)
val = torch.stack(vals)
probability = torch.einsum("bhd,sbhd->bhs", q[t], key)
probability = (probability / 8).softmax(-1)
outputs.append(torch.einsum("bhs,sbhd->bhd", probability, val))
expected = torch.stack(outputs)
torch.testing.assert_close(actual, expected)
ga = torch.autograd.grad(actual.square().sum(), (q, *values), retain_graph=True)
ge = torch.autograd.grad(expected.square().sum(), (q, *values))
for a, e in zip(ga, ge): torch.testing.assert_close(a, e)
short = reference_attention(q[:2], *(x[:2] for x in values), window=128)
self.assertTrue(torch.isfinite(short).all())
@unittest.skipUnless(torch.cuda.is_available(), "requires CUDA FlashAttention")
def test_production_segmented_flash_forward_and_all_gradients(self):
"""Regression for the formerly dropped cross-branch LSE Q/K gradient."""
try:
import flash_attn # noqa: F401
except ImportError:
self.skipTest("FlashAttention is unavailable")
torch.manual_seed(17)
shapes = ((9, 1, 2, 64),) + ((9, 1, 1, 64),) * 4
source = [torch.randn(shape, device="cuda", dtype=torch.float16)
for shape in shapes]
actual_inputs = [x.clone().requires_grad_() for x in source]
reference_inputs = [x.clone().requires_grad_() for x in source]
actual = segmented_flash_attention(*actual_inputs, window=4)
expected = reference_attention(*reference_inputs, window=4)
torch.testing.assert_close(actual, expected, atol=3e-3, rtol=3e-3)
upstream = torch.randn_like(actual)
actual_grad = torch.autograd.grad((actual * upstream).sum(), actual_inputs)
expected_grad = torch.autograd.grad((expected * upstream).sum(), reference_inputs)
for got, want in zip(actual_grad, expected_grad):
torch.testing.assert_close(got, want, atol=8e-3, rtol=8e-3)
def test_full_head_rope_long_position(self):
position = torch.tensor([0, 127, 128, 129, 32767], dtype=torch.double)
x = torch.randn(5, 1, 1, 64, dtype=torch.double, requires_grad=True)
inv = 1_000_000 ** (-torch.arange(0, 64, 2, dtype=torch.double) / 64)
angle = torch.outer(position, inv)
angle = torch.cat((angle, angle), -1)[:, None, None]
left, right = x.chunk(2, -1)
rotated = x * angle.cos() + torch.cat((-right, left), -1) * angle.sin()
self.assertEqual(rotated.shape[-1], 64)
self.assertTrue(torch.isfinite(torch.autograd.grad(rotated.sum(), x)[0]).all())
def test_parameter_names_shapes_and_strict_cross_r_load(self):
models = [ProjectionShell(r) for r in (16, 32, 64)]
signatures = [[(name, tuple(value.shape)) for name, value in m.state_dict().items()]
for m in models]
self.assertEqual(signatures[0], signatures[1])
self.assertEqual(signatures[1], signatures[2])
models[2].load_state_dict(models[0].state_dict(), strict=True)
self.assertEqual(models[0].linear_qkv.out_features, 8 * 64 + 2 * 4 * 64)
def test_r64_equals_full_context_gqa_outputs_and_gradients(self):
torch.manual_seed(11)
original = [torch.randn(6, 1, heads, 64, dtype=torch.double)
for heads in (2, 1, 1)]
a = [x.clone().requires_grad_() for x in original]
b = [x.clone().requires_grad_() for x in original]
split = reference_attention(a[0], a[1], a[2], a[1], a[2], window=3)
q, k, v = b
k = k.repeat_interleave(2, 2)
v = v.repeat_interleave(2, 2)
score = torch.einsum("tbhd,sbhd->bhts", q, k) / 8
causal = torch.ones(6, 6, dtype=torch.bool).tril()
full = torch.einsum("bhts,sbhd->tbhd",
score.masked_fill(~causal, -torch.inf).softmax(-1), v)
torch.testing.assert_close(split, full)
ga = torch.autograd.grad(split.square().sum(), a)
gb = torch.autograd.grad(full.square().sum(), b)
for x, y in zip(ga, gb): torch.testing.assert_close(x, y)

Xet Storage Details

Size:
10.7 kB
·
Xet hash:
1c3c5d2c7d646eeefbd6a6845deac4117999e295db2d763a8d4372e739db5465

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.