xuan-luo/temp / training /kvpath /test_kvpath.py
xuan-luo's picture
download
raw
17.6 kB
#!/usr/bin/env python3
"""Single-GPU tests for KVPath (and, via training/gqa, its GQA baseline).
Covers task section 5 (1-8):
1. Parameter-count self-check (exact numbers from task section 6)
2. Group structure (anchors: q_delta_base_proj; followers: q_delta_proj; no QK-Norm)
3. KV-cache size at ctx=128 and ctx=1024, both must equal 6144 vals/token
4. Prefill vs. incremental-decode logits must match (the key correctness test)
5. Forward+backward: no NaN/Inf; a tiny overfit run must clearly reduce loss
6. Print the actual SDPA attention backend selected for head_dim=160
7. Megatron single-GPU smoke test: init checkpoint + 20 training steps, loss down
8. KVPath vs. GQA total parameter count must differ by <= 0.01%
Run (auto-picks the most idle GPU):
GPU=$(nvidia-smi --query-gpu=index,memory.used --format=csv,noheader,nounits \\
| sort -t, -k2 -n | head -1 | cut -d, -f1)
CUDA_VISIBLE_DEVICES=$GPU python training/kvpath/test_kvpath.py
"""
from __future__ import annotations
import argparse
import copy
import os
import re
import shlex
import subprocess
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
import torch
from training.kvpath.kvpath.configuration_kvpath import KVPathConfig
from training.kvpath.kvpath.modeling_kvpath import KVPathCache, KVPathForCausalLM
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# ---------------------------------------------------------------------------
# Spec numbers (task section 6): KVPath, inter=1536.
# ---------------------------------------------------------------------------
EXPECTED_Q_DELTA_PARAMS = 786_432 # follower fused [q|δk|δv]
EXPECTED_Q_DELTA_BASE_PARAMS = 1_310_720 # anchor fused [q|δk|δv|bk|bv]
EXPECTED_O_PARAMS = 655_360
EXPECTED_FOLLOWER_ATTN_PARAMS = 1_441_792
EXPECTED_ANCHOR_ATTN_PARAMS = 1_966_080
EXPECTED_TOTAL_ATTN_PARAMS = 18_874_368
# No QK-Norm (see modeling_kvpath.py): removing q_norm (RMSNorm(160), all 12
# layers) and k_norm (RMSNorm(128), 3 anchors only) drops 12*160 + 3*128 =
# 2,304 params off the with-norm total of 98,712,320, giving 98,710,016. The
# GQA baseline (training/gqa/gqa/modeling_gqa.py::GQAAttention,
# which never constructs q_norm/k_norm at all) loses 2*64*12 = 1,536 params
# the same way, landing at the *same* 98,710,016 --
# once both variants drop QK-Norm, their totals are exactly equal (the
# ffn_hidden_size tuning that used to offset the norm-size gap now overshoots
# by exactly that gap, in KVPath's favor, canceling it exactly).
EXPECTED_TOTAL_PARAMS = 98_710_016
EXPECTED_CACHE_VALS_PER_TOKEN = 6144
EXPECTED_GQA_TOTAL_PARAMS = 98_710_016
MAX_PARAM_DIFF_RATIO = 0.0001 # 0.01%
def make_full_config(vocab_size: int = 50304) -> KVPathConfig:
"""The exact spec-matched config (used only for the param-count checks)."""
return KVPathConfig(
vocab_size=vocab_size,
hidden_size=512,
intermediate_size=1536,
num_hidden_layers=12,
num_attention_heads=8,
num_key_value_heads=4,
max_position_embeddings=4096,
rms_norm_eps=1e-6,
rope_theta=1_000_000.0,
tie_word_embeddings=False,
attention_bias=False,
attention_dropout=0.0,
kvpath_group_size=4,
kvpath_rank=32,
kvpath_base_head_dim=128,
)
def make_small_config(vocab_size: int = 256, max_position_embeddings: int = 512) -> KVPathConfig:
"""A cheap config for functional (forward/backward/cache/decode) tests."""
return KVPathConfig(
vocab_size=vocab_size,
hidden_size=512,
intermediate_size=1536,
num_hidden_layers=12,
num_attention_heads=8,
num_key_value_heads=4,
max_position_embeddings=max_position_embeddings,
rms_norm_eps=1e-6,
rope_theta=1_000_000.0,
tie_word_embeddings=False,
attention_bias=False,
attention_dropout=0.0,
kvpath_group_size=4,
kvpath_rank=32,
kvpath_base_head_dim=128,
)
# ---------------------------------------------------------------------------
# 1. Parameter-count self-check
# ---------------------------------------------------------------------------
def check_param_counts(config: KVPathConfig) -> int:
model = KVPathForCausalLM(config)
layers = model.model.layers
anchor = layers[0].self_attn
follower = layers[1].self_attn
assert anchor.is_anchor and not follower.is_anchor
q_delta = follower.q_delta_proj.weight.numel()
o = follower.o_proj.weight.numel()
q_delta_base = anchor.q_delta_base_proj.weight.numel()
assert q_delta == EXPECTED_Q_DELTA_PARAMS, q_delta
assert o == EXPECTED_O_PARAMS, o
assert q_delta_base == EXPECTED_Q_DELTA_BASE_PARAMS, q_delta_base
follower_attn = q_delta + o
anchor_attn = q_delta_base + o
assert follower_attn == EXPECTED_FOLLOWER_ATTN_PARAMS, follower_attn
assert anchor_attn == EXPECTED_ANCHOR_ATTN_PARAMS, anchor_attn
num_anchor_layers = config.num_hidden_layers // config.kvpath_group_size
num_follower_layers = config.num_hidden_layers - num_anchor_layers
total_attn = num_anchor_layers * anchor_attn + num_follower_layers * follower_attn
assert total_attn == EXPECTED_TOTAL_ATTN_PARAMS, total_attn
total_params = sum(p.numel() for p in model.parameters())
assert total_params == EXPECTED_TOTAL_PARAMS, total_params
print(f"[kvpath] follower attention params = {follower_attn:,} (expected 1,441,792)")
print(f"[kvpath] anchor attention params = {anchor_attn:,} (expected 1,966,080)")
print(f"[kvpath] 12-layer attention total = {total_attn:,} (expected 18,874,368)")
print(f"[kvpath] total params = {total_params:,} (expected {EXPECTED_TOTAL_PARAMS:,}, no QK-Norm)")
return total_params
# ---------------------------------------------------------------------------
# 2. Group structure
# ---------------------------------------------------------------------------
def check_group_structure(config: KVPathConfig) -> None:
model = KVPathForCausalLM(config)
for idx, layer in enumerate(model.model.layers):
attn = layer.self_attn
is_anchor = idx % config.kvpath_group_size == 0
assert attn.is_anchor == is_anchor, idx
# No QK-Norm anywhere (see modeling_kvpath.py): neither anchors nor
# followers should own a q_norm/k_norm module at all.
assert not hasattr(attn, "q_norm"), idx
assert not hasattr(attn, "k_norm"), idx
if is_anchor:
assert hasattr(attn, "q_delta_base_proj"), idx
assert not hasattr(attn, "q_delta_proj"), idx
else:
assert hasattr(attn, "q_delta_proj"), idx
assert not hasattr(attn, "q_delta_base_proj"), idx
print(
"[kvpath] group structure OK: anchors own q_delta_base_proj, followers own "
"q_delta_proj, no layer has q_norm/k_norm (no QK-Norm)"
)
# ---------------------------------------------------------------------------
# 3. KV-cache size, independent of context length
# ---------------------------------------------------------------------------
def check_cache_vals_per_token(config: KVPathConfig, device: torch.device) -> None:
model = KVPathForCausalLM(config).to(device=device, dtype=torch.bfloat16).eval()
for ctx in (128, 1024):
input_ids = torch.randint(0, config.vocab_size, (1, ctx), device=device)
with torch.no_grad():
cache = KVPathCache(config)
out = model(input_ids=input_ids, past_key_values=cache, use_cache=True)
stats = out.past_key_values.cache_statistics()
per_token = stats["allocated_elements_per_token"]
assert per_token == EXPECTED_CACHE_VALS_PER_TOKEN, (ctx, stats)
print(f"[kvpath] ctx={ctx}: cache vals/token = {per_token:.1f} (expected 6144, no window growth)")
# ---------------------------------------------------------------------------
# 4. Prefill vs. incremental decode must match exactly
# ---------------------------------------------------------------------------
def check_prefill_vs_decode(config: KVPathConfig, device: torch.device, dtype: torch.dtype) -> None:
torch.manual_seed(0)
model = KVPathForCausalLM(config).to(device=device, dtype=dtype).eval()
batch, seq_len = 2, 37 # not a multiple of group_size, on purpose
input_ids = torch.randint(0, config.vocab_size, (batch, seq_len), device=device)
with torch.no_grad():
prefill_logits = model(input_ids=input_ids, use_cache=False).logits
with torch.no_grad():
cache = KVPathCache(config)
decode_chunks = []
for t in range(seq_len):
out = model(input_ids=input_ids[:, t : t + 1], past_key_values=cache, use_cache=True)
cache = out.past_key_values
decode_chunks.append(out.logits)
decode_logits = torch.cat(decode_chunks, dim=1)
assert prefill_logits.shape == decode_logits.shape
diff = (prefill_logits.float() - decode_logits.float()).abs()
assert torch.isfinite(diff).all(), "non-finite logits in prefill/decode comparison"
atol = 2e-2 if dtype == torch.bfloat16 else 1e-4
max_diff = diff.max().item()
mean_diff = diff.mean().item()
print(
f"[kvpath] prefill-vs-decode ({dtype}): max|diff|={max_diff:.6f} "
f"mean|diff|={mean_diff:.6f} (atol={atol})"
)
assert max_diff <= atol, f"prefill vs decode logits mismatch: max diff {max_diff} > {atol}"
# Cross-check with argmax agreement, a coarser but very telling signal. Only
# enforced in fp32: with an untrained random model in bf16, many vocab
# logits sit within bf16's rounding noise of each other, so a few argmax
# flips are expected even though the underlying logits already satisfy the
# atol=2e-2 allclose bound above (the actual pass/fail criterion).
agree = (prefill_logits.argmax(-1) == decode_logits.argmax(-1)).float().mean().item()
print(f"[kvpath] prefill-vs-decode argmax agreement = {agree:.4f}")
if dtype == torch.float32:
assert agree >= 0.99
# ---------------------------------------------------------------------------
# 5. Forward + backward sanity, and a tiny overfit run
# ---------------------------------------------------------------------------
def check_forward_backward(config: KVPathConfig, device: torch.device) -> None:
torch.manual_seed(0)
model = KVPathForCausalLM(config).to(device=device, dtype=torch.float32)
model.train()
batch, seq_len = 2, 32
input_ids = torch.randint(0, config.vocab_size, (batch, seq_len), device=device)
optimizer = torch.optim.AdamW(model.parameters(), lr=3e-3)
losses = []
for _ in range(60):
optimizer.zero_grad()
out = model(input_ids=input_ids, labels=input_ids)
loss = out.loss
assert torch.isfinite(loss), loss
loss.backward()
for name, p in model.named_parameters():
if p.grad is not None:
assert torch.isfinite(p.grad).all(), f"non-finite grad in {name}"
optimizer.step()
losses.append(loss.item())
print(f"[kvpath] overfit loss: {losses[0]:.4f} -> {losses[-1]:.4f}")
assert losses[-1] < losses[0] * 0.6, losses
# ---------------------------------------------------------------------------
# 6. Backend note: KVPathAttention is a single, permanent split-score
# implementation (fused projections + manual matmul/softmax) -- there is no
# SDPA/ALL_ATTENTION_FUNCTIONS dispatch to probe here, unlike a stock HF
# attention class. This is a deliberate, deterministic choice (see
# modeling_kvpath.py's module docstring), not a fallback.
# ---------------------------------------------------------------------------
def check_backend(config: KVPathConfig, device: torch.device) -> None:
model = KVPathForCausalLM(config).to(device=device, dtype=torch.bfloat16).eval()
input_ids = torch.randint(0, config.vocab_size, (1, 64), device=device)
with torch.no_grad():
model(input_ids=input_ids)
print(
f"[kvpath] head_dim={config.head_dim}: pure eager split-score attend "
"(no SDPA/flash dispatch; see modeling_kvpath.py)"
)
# ---------------------------------------------------------------------------
# 7. Megatron single-GPU smoke test (init checkpoint + short training run)
# ---------------------------------------------------------------------------
_LOSS_RE = re.compile(r"iteration\s+(\d+)\s*/\s*\d+.*?lm loss:\s*([0-9.eE+-]+)")
def _make_smoke_config(config_path: Path, train_iters: int) -> dict:
from utils.megatron_launcher import load_config
config = copy.deepcopy(load_config(config_path))
config["launcher"]["nnodes"] = 1
config["launcher"]["nproc_per_node"] = 1
config["data"]["micro_batch_size"] = 2
config["data"]["global_batch_size"] = 2
config["training"]["train_iters"] = train_iters
config["training"]["eval_interval"] = train_iters + 1
config["training"]["save_interval"] = train_iters
config["training"]["log_interval"] = 1
config["schedule"]["lr_warmup_iters"] = 0
return config
def run_megatron_smoke_test(
config_path: Path, *, label: str, train_iters: int = 20, master_port: int = 6199
) -> None:
"""Init-checkpoint + short single-GPU training run; asserts loss goes down."""
from utils.megatron_launcher import build_train_command, validate_config
from utils.paths import resolve
from utils.save_init_checkpoint import _build_command as build_init_command
config = _make_smoke_config(config_path, train_iters)
optimizer = validate_config(config, None)
env = os.environ.copy()
env["PYTHONPATH"] = os.pathsep.join(
part for part in (str(ROOT), str(resolve(config["paths"]["megatron_repo"])), env.get("PYTHONPATH"))
if part
)
env["CUDA_DEVICE_MAX_CONNECTIONS"] = "1"
init_command = build_init_command(config, nproc=1, master_port=master_port)
print(f"[{label}] init checkpoint:\n" + shlex.join(init_command))
subprocess.run(init_command, cwd=ROOT, env=env, check=True)
init_dir = resolve(config["paths"]["init_checkpoint"])
marker = init_dir / "latest_checkpointed_iteration.txt"
assert marker.exists(), f"[{label}] init checkpoint was not created at {init_dir}"
train_command = build_train_command(
config,
optimizer,
extra_megatron_args=["--finetune", "--no-load-optim", "--no-load-rng"],
python_executable=sys.executable,
load_dir=init_dir,
)
print(f"[{label}] train (smoke, {train_iters} steps):\n" + shlex.join(train_command))
proc = subprocess.run(
train_command, cwd=ROOT, env=env, check=True, capture_output=True, text=True
)
log = proc.stdout + "\n" + proc.stderr
losses = [(int(it), float(loss)) for it, loss in _LOSS_RE.findall(log)]
if not losses:
tail = "\n".join(log.splitlines()[-60:])
raise AssertionError(f"[{label}] no 'lm loss' lines found in Megatron output; tail:\n{tail}")
losses.sort()
print(f"[{label}] Megatron smoke-test lm loss trace: {losses}")
first_loss = losses[0][1]
last_loss = losses[-1][1]
assert all(torch.isfinite(torch.tensor(v)) for _, v in losses), losses
assert last_loss < first_loss, (
f"[{label}] Megatron smoke-test loss did not decrease: {first_loss} -> {last_loss}"
)
print(f"[{label}] Megatron smoke test OK: loss {first_loss:.4f} -> {last_loss:.4f} over {train_iters} steps")
# ---------------------------------------------------------------------------
# 8. KVPath vs. GQA total parameter count parity
# ---------------------------------------------------------------------------
def check_param_parity(kvpath_total: int, gqa_total: int | None = None) -> None:
if gqa_total is None:
from training.gqa.test_gqa import check_param_counts as check_gqa
from training.gqa.test_gqa import make_full_config as make_gqa_full_config
gqa_total = check_gqa(make_gqa_full_config())
assert gqa_total == EXPECTED_GQA_TOTAL_PARAMS, gqa_total
diff = abs(kvpath_total - gqa_total)
ratio = diff / gqa_total
print(
f"[parity] KVPath total={kvpath_total:,} GQA total={gqa_total:,} "
f"diff={diff:,} ({ratio:.6%})"
)
assert ratio <= MAX_PARAM_DIFF_RATIO, (kvpath_total, gqa_total, ratio)
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--skip-megatron", action="store_true", help="skip the (slow) Megatron smoke test")
parser.add_argument("--megatron-train-iters", type=int, default=20)
args = parser.parse_args()
print(f"Device: {DEVICE}")
full_config = make_full_config()
kvpath_total = check_param_counts(full_config)
check_group_structure(full_config)
small_config = make_small_config()
check_cache_vals_per_token(small_config, DEVICE)
check_prefill_vs_decode(copy.deepcopy(small_config), DEVICE, torch.float32)
if DEVICE.type == "cuda":
check_prefill_vs_decode(copy.deepcopy(small_config), DEVICE, torch.bfloat16)
check_forward_backward(copy.deepcopy(small_config), DEVICE)
check_backend(small_config, DEVICE)
check_param_parity(kvpath_total)
if not args.skip_megatron:
run_megatron_smoke_test(
ROOT / "training" / "kvpath" / "config.toml",
label="kvpath",
train_iters=args.megatron_train_iters,
)
print("\nAll kvpath tests passed.")
if __name__ == "__main__":
main()

Xet Storage Details

Size:
17.6 kB
·
Xet hash:
ede849ae6b9d3e10d6235c446e3bf773237e1ef07863f40b73f717bab5ff133a

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