Buckets:
| #!/usr/bin/env python3 | |
| """Single-GPU tests for the GQA (g=4, head_dim=64) KVPath comparison baseline. | |
| Standard grouped-query attention (no QK-Norm, fused QKV, no repeat_kv -- see | |
| training/gqa/gqa/modeling_gqa.py) -- these tests mostly establish | |
| the ground truth numbers (param count, KV cache size) that | |
| training/kvpath/test_kvpath.py compares KVPath against, plus basic | |
| forward/backward sanity checks and (optionally) a Megatron single-GPU | |
| training smoke test. | |
| 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/gqa/test_gqa.py | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import copy | |
| 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 transformers.cache_utils import DynamicCache | |
| from training.gqa.gqa.configuration_gqa import GQAConfig | |
| from training.gqa.gqa.modeling_gqa import GQAForCausalLM | |
| DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu") | |
| # --------------------------------------------------------------------------- | |
| # Spec numbers (section 6 of the task): GQA g=4, head_dim=64, inter=2048. | |
| # No QK-Norm: GQAAttention never constructs q_norm/k_norm at all (see | |
| # modeling_gqa.py), which removes 2*64=128 params/layer (1536 over 12 layers) | |
| # relative to what stock Qwen3Attention's total would have been. | |
| # --------------------------------------------------------------------------- | |
| EXPECTED_PER_LAYER_ATTN_PARAMS = 786_432 | |
| EXPECTED_TOTAL_PARAMS = 98_710_016 | |
| EXPECTED_CACHE_VALS_PER_TOKEN = 6144 | |
| def make_full_config(vocab_size: int = 50304) -> GQAConfig: | |
| """The exact spec-matched config (used only for the param-count checks).""" | |
| return GQAConfig( | |
| vocab_size=vocab_size, | |
| hidden_size=512, | |
| intermediate_size=2048, | |
| num_hidden_layers=12, | |
| num_attention_heads=8, | |
| num_key_value_heads=4, | |
| head_dim=64, | |
| 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, | |
| ) | |
| def make_small_config(vocab_size: int = 256) -> GQAConfig: | |
| """A cheap config for functional (forward/backward/cache/decode) tests.""" | |
| return GQAConfig( | |
| vocab_size=vocab_size, | |
| hidden_size=512, | |
| intermediate_size=2048, | |
| num_hidden_layers=12, | |
| num_attention_heads=8, | |
| num_key_value_heads=4, | |
| head_dim=64, | |
| max_position_embeddings=512, | |
| rms_norm_eps=1e-6, | |
| rope_theta=1_000_000.0, | |
| tie_word_embeddings=False, | |
| attention_bias=False, | |
| attention_dropout=0.0, | |
| ) | |
| def check_param_counts(config: GQAConfig) -> int: | |
| model = GQAForCausalLM(config) | |
| layer0 = model.model.layers[0].self_attn | |
| assert not hasattr(layer0, "q_norm"), "GQAAttention must never construct q_norm" | |
| assert not hasattr(layer0, "k_norm"), "GQAAttention must never construct k_norm" | |
| per_layer = layer0.qkv_proj.weight.numel() + layer0.o_proj.weight.numel() | |
| assert per_layer == EXPECTED_PER_LAYER_ATTN_PARAMS, per_layer | |
| total = sum(p.numel() for p in model.parameters()) | |
| assert total == EXPECTED_TOTAL_PARAMS, total | |
| print(f"[gqa] per-layer attention params = {per_layer:,} (expected 786,432)") | |
| print(f"[gqa] total params = {total:,} (expected {EXPECTED_TOTAL_PARAMS:,}, no QK-Norm)") | |
| return total | |
| def check_cache_vals_per_token(config: GQAConfig, device: torch.device) -> None: | |
| model = GQAForCausalLM(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 = DynamicCache(config=config) | |
| out = model(input_ids=input_ids, past_key_values=cache, use_cache=True) | |
| cache = out.past_key_values | |
| allocated = sum( | |
| layer.keys.numel() + layer.values.numel() | |
| for layer in cache.layers | |
| if getattr(layer, "is_initialized", False) | |
| ) | |
| per_token = allocated / ctx | |
| assert per_token == EXPECTED_CACHE_VALS_PER_TOKEN, (ctx, per_token) | |
| print(f"[gqa] ctx={ctx}: cache vals/token = {per_token:.1f} (expected 6144)") | |
| def check_prefill_vs_decode(config: GQAConfig, device: torch.device, dtype: torch.dtype) -> None: | |
| torch.manual_seed(0) | |
| model = GQAForCausalLM(config).to(device=device, dtype=dtype).eval() | |
| batch, seq_len = 2, 37 | |
| 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 = DynamicCache(config=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() | |
| atol = 2e-2 if dtype == torch.bfloat16 else 1e-4 | |
| max_diff = diff.max().item() | |
| print(f"[gqa] prefill-vs-decode ({dtype}): max|diff|={max_diff:.6f} (atol={atol})") | |
| assert max_diff <= atol, f"prefill vs decode logits mismatch: max diff {max_diff} > {atol}" | |
| def check_forward_backward(config: GQAConfig, device: torch.device) -> None: | |
| torch.manual_seed(0) | |
| model = GQAForCausalLM(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 p in model.parameters(): | |
| if p.grad is not None: | |
| assert torch.isfinite(p.grad).all() | |
| optimizer.step() | |
| losses.append(loss.item()) | |
| print(f"[gqa] overfit loss: {losses[0]:.4f} -> {losses[-1]:.4f}") | |
| assert losses[-1] < losses[0] * 0.6, losses | |
| def check_backend(config: GQAConfig, device: torch.device) -> None: | |
| model = GQAForCausalLM(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) | |
| # GQAAttention is a single, permanent fused/no-repeat_kv eager | |
| # implementation (see modeling_gqa.py) -- no SDPA/flash dispatch to probe. | |
| print("[gqa] fused QKV + no-repeat_kv eager attend (no SDPA/flash dispatch)") | |
| def main() -> None: | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--skip-megatron", action="store_true") | |
| args = parser.parse_args() | |
| print(f"Device: {DEVICE}") | |
| full_config = make_full_config() | |
| check_param_counts(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) | |
| if not args.skip_megatron: | |
| from training.kvpath.test_kvpath import run_megatron_smoke_test | |
| run_megatron_smoke_test( | |
| ROOT / "training" / "gqa" / "config.toml", label="gqa" | |
| ) | |
| print("\nAll gqa tests passed.") | |
| if __name__ == "__main__": | |
| main() | |
Xet Storage Details
- Size:
- 8.02 kB
- Xet hash:
- 984da7eed913027ae14c16e9e24ab18bbc729eed135188f91d2b2351d622f511
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.