"""第 01 课实测:自回归(AR)逐词串行解码的内存带宽屋脊线墙 vs 块并行(Block Diffusion)吞吐与 1K→64K 显存墙。""" from __future__ import annotations import gc import hashlib import json from typing import Any import torch import torch.nn as nn import torch.nn.functional as F from transformers import AutoModelForCausalLM DENSE_AR_REPO = "Qwen/Qwen2.5-1.5B-Instruct" def compute_config_fingerprint(cfg: dict[str, Any]) -> str: raw = json.dumps(cfg, sort_keys=True, separators=(",", ":")).encode("utf-8") return hashlib.sha256(raw).hexdigest()[:16] def measure_cuda_ms(fn: Any, warmup: int = 8, iters: int = 25) -> float: for _ in range(warmup): fn() torch.cuda.synchronize() start_ev = torch.cuda.Event(enable_timing=True) end_ev = torch.cuda.Event(enable_timing=True) start_ev.record() for _ in range(iters): fn() end_ev.record() torch.cuda.synchronize() return float(start_ev.elapsed_time(end_ev)) / float(iters) def benchmark_block_parallel_roofline(device: torch.device) -> dict[str, Any]: """在真实 Dense 大模型与 GEMM 微基准上对比 B=1 (串行 AR) 到 B=64 (并行块扩散) 的屋脊线利用率。""" # 1. 受控单层 SwiGLU FFN 屋脊线微基准(模拟 3B 激活参数层:d=2048, d_ff=11008, BF16) d_model, d_ff = 2048, 11008 g = torch.Generator(device=device).manual_seed(20260401) w_gate = torch.randn((d_ff, d_model), generator=g, device=device, dtype=torch.bfloat16) * 0.02 w_up = torch.randn((d_ff, d_model), generator=g, device=device, dtype=torch.bfloat16) * 0.02 w_down = torch.randn((d_model, d_ff), generator=g, device=device, dtype=torch.bfloat16) * 0.02 weight_bytes = (w_gate.numel() + w_up.numel() + w_down.numel()) * 2 token_batches = [1, 2, 4, 8, 16, 32, 64, 128, 512] ffn_curve: dict[str, Any] = {} for b_tok in token_batches: x = torch.randn((1, b_tok, d_model), generator=g, device=device, dtype=torch.bfloat16) def run_swiglu() -> torch.Tensor: h = F.silu(F.linear(x, w_gate)) * F.linear(x, w_up) return F.linear(h, w_down) lat_ms = measure_cuda_ms(run_swiglu, warmup=10, iters=40) flops = 6.0 * float(b_tok) * float(d_model) * float(d_ff) io_bytes = float(weight_bytes + x.numel() * 4) arith_intensity = flops / io_bytes achieved_tflops = (flops / (lat_ms * 1e-3)) / 1e12 eff_bw_gbs = (io_bytes / (lat_ms * 1e-3)) / 1e9 ffn_curve[f"tokens_{b_tok}"] = { "parallel_tokens_per_step": b_tok, "latency_ms": round(lat_ms, 4), "arithmetic_intensity_flop_per_byte": round(arith_intensity, 2), "achieved_tflops": round(achieved_tflops, 3), "effective_hbm_bw_gb_s": round(eff_bw_gbs, 2), "throughput_tokens_per_sec": round(b_tok / (lat_ms * 1e-3), 1), } del w_gate, w_up, w_down torch.cuda.empty_cache() # 2. 真实开源模型 Qwen2.5-1.5B-Instruct (BF16):固定 1024 词前缀 KV Cache,对比单步评估 1 词 vs 32 词块 model = AutoModelForCausalLM.from_pretrained( DENSE_AR_REPO, dtype=torch.bfloat16, device_map={"": device}, ) model.eval() param_bytes = sum(p.numel() * p.element_size() for p in model.parameters()) active_params = sum(p.numel() for p in model.parameters()) prefix_len = 1024 torch.manual_seed(42) prefix_ids = torch.randint(100, 5000, (1, prefix_len), device=device) with torch.no_grad(): prefill_out = model(input_ids=prefix_ids, use_cache=True) base_past = prefill_out.past_key_values # Transformers DynamicCache 在 forward 时会原地追加,因此每次克隆轻量张量视图做纯净单步测量 def clone_kv_tuple() -> Any: from transformers.cache_utils import DynamicCache if hasattr(base_past, "key_cache"): c = DynamicCache() for k_t, v_t in zip(base_past.key_cache, base_past.value_cache): c.key_cache.append(k_t.clone()) c.value_cache.append(v_t.clone()) return c if hasattr(base_past, "layers"): c = DynamicCache() for layer in base_past.layers: c.update(layer.keys.clone(), layer.values.clone(), len(c.layers)) return c return tuple((k.clone(), v.clone()) for k, v in base_past) real_llm_steps: dict[str, Any] = {} for step_tokens in [1, 4, 8, 16, 32, 64]: step_ids = torch.randint(100, 5000, (1, step_tokens), device=device) @torch.no_grad() def forward_step() -> None: kv = clone_kv_tuple() _ = model(input_ids=step_ids, past_key_values=kv, use_cache=True) # 单独测克隆开销以便剥离纯前向延迟 clone_ms = measure_cuda_ms(clone_kv_tuple, warmup=5, iters=20) total_ms = measure_cuda_ms(forward_step, warmup=6, iters=18) net_ms = max(total_ms - clone_ms, 0.25) approx_flops = 2.0 * float(active_params) * float(step_tokens) achieved_tflops = (approx_flops / (net_ms * 1e-3)) / 1e12 real_llm_steps[f"block_{step_tokens}"] = { "parallel_tokens": step_tokens, "step_latency_ms": round(net_ms, 3), "raw_token_evals_per_sec": round(step_tokens / (net_ms * 1e-3), 1), "achieved_tflops": round(achieved_tflops, 2), "latency_ratio_vs_ar1": round( net_ms / real_llm_steps["block_1"]["step_latency_ms"], 3 ) if "block_1" in real_llm_steps else 1.0, } b32_free_eval_gain = round( real_llm_steps["block_32"]["raw_token_evals_per_sec"] / real_llm_steps["block_1"]["raw_token_evals_per_sec"], 2, ) assert b32_free_eval_gain > 12.0, f"块并行带宽红利异常偏低: {b32_free_eval_gain}" del model, base_past, prefill_out gc.collect() torch.cuda.empty_cache() return { "swiglu_roofline_microbench": ffn_curve, "real_llm_repo": DENSE_AR_REPO, "real_llm_active_params_b": round(active_params / 1e9, 3), "real_llm_weight_mib": round(param_bytes / float(1024 * 1024), 1), "real_llm_step_scaling_at_1k_prefix": real_llm_steps, "block32_vs_ar1_eval_throughput_gain": b32_free_eval_gain, } def benchmark_context_wall_1k_to_64k(device: torch.device) -> dict[str, Any]: """对比全注意力 (SDPA + KV Cache) 与固定状态线性递推在 1K → 64K 长度下的显存与延迟缩放。""" num_layers_sim = 28 n_q_heads, n_kv_heads, head_dim = 16, 4, 128 # GQA-4 vs GatedDelta 固定矩阵状态 seq_lengths = [1024, 4096, 16384, 32768, 65536] scaling_rows: dict[str, Any] = {} for seq_len in seq_lengths: torch.cuda.empty_cache() torch.cuda.reset_peak_memory_stats(device) base_mem = torch.cuda.memory_allocated(device) # 1) 单层融合因果 SDPA Prefill 延迟(乘 28 层折算整网注意力开销) q = torch.randn((1, n_q_heads, seq_len, head_dim), device=device, dtype=torch.bfloat16) k = torch.randn((1, n_kv_heads, seq_len, head_dim), device=device, dtype=torch.bfloat16) v = torch.randn((1, n_kv_heads, seq_len, head_dim), device=device, dtype=torch.bfloat16) def run_sdpa_prefill() -> torch.Tensor: return F.scaled_dot_product_attention(q, k, v, is_causal=True, enable_gqa=True) iters = 12 if seq_len <= 16384 else 5 prefill_1l_ms = measure_cuda_ms(run_sdpa_prefill, warmup=3, iters=iters) # 2) 单步自回归 Decode 读取全长 KV Cache 延迟 q_dec = torch.randn((1, n_q_heads, 1, head_dim), device=device, dtype=torch.bfloat16) def run_sdpa_decode() -> torch.Tensor: return F.scaled_dot_product_attention(q_dec, k, v, is_causal=False, enable_gqa=True) decode_1l_ms = measure_cuda_ms(run_sdpa_decode, warmup=8, iters=30) kv_1l_bytes = (k.numel() + v.numel()) * 2 kv_28l_mib = (kv_1l_bytes * num_layers_sim) / float(1024 * 1024) # 3) 线性状态层 (Gated DeltaNet: S in [1, H, d_v, d_k]) 单步状态更新延迟与恒定显存 state_s = torch.randn( (1, n_q_heads, head_dim, head_dim), device=device, dtype=torch.float32 ) q_lin = torch.randn((1, n_q_heads, head_dim, 1), device=device, dtype=torch.float32) k_lin = F.normalize( torch.randn((1, n_q_heads, head_dim, 1), device=device, dtype=torch.float32), dim=2 ) v_lin = torch.randn((1, n_q_heads, head_dim, 1), device=device, dtype=torch.float32) def run_gdn_state_step() -> torch.Tensor: retrieved = torch.matmul(state_s, k_lin) s_next = 0.98 * state_s + 0.5 * torch.matmul(v_lin - retrieved, k_lin.transpose(-1, -2)) return torch.matmul(s_next, q_lin) gdn_decode_1l_ms = measure_cuda_ms(run_gdn_state_step, warmup=8, iters=30) gdn_28l_state_mib = (state_s.numel() * 4 * num_layers_sim) / float(1024 * 1024) peak_alloc_mib = (torch.cuda.max_memory_allocated(device) - base_mem) / float(1024 * 1024) scaling_rows[f"ctx_{seq_len}"] = { "seq_len": seq_len, "full_attn_28l_prefill_ms": round(prefill_1l_ms * num_layers_sim, 2), "full_attn_28l_decode_tpot_ms": round(decode_1l_ms * num_layers_sim, 3), "gqa4_28l_kv_cache_mib": round(kv_28l_mib, 2), "mha16_28l_kv_cache_mib": round(kv_28l_mib * 4.0, 2), "gdn_28l_constant_state_mib": round(gdn_28l_state_mib, 2), "gdn_28l_decode_tpot_ms": round(gdn_decode_1l_ms * num_layers_sim, 3), "measured_1l_peak_tensor_mib": round(peak_alloc_mib, 2), } del q, k, v, q_dec, state_s, q_lin, k_lin, v_lin prefill_quad_ratio = round( scaling_rows["ctx_65536"]["full_attn_28l_prefill_ms"] / scaling_rows["ctx_16384"]["full_attn_28l_prefill_ms"], 2, ) assert prefill_quad_ratio > 10.0, f"4x 序列长度下全注意力 Prefill 未体现二次方增长: {prefill_quad_ratio}" return { "sim_28_layer_spec": { "num_layers": num_layers_sim, "n_q_heads": n_q_heads, "n_kv_heads_gqa": n_kv_heads, "head_dim": head_dim, }, "context_scaling_1k_to_64k": scaling_rows, "prefill_64k_vs_16k_time_ratio": prefill_quad_ratio, } def run_roofline_and_kv_audit(device: torch.device) -> dict[str, Any]: spec = {"seed": 20260401, "dense_repo": DENSE_AR_REPO, "max_ctx": 65536} roofline_res = benchmark_block_parallel_roofline(device) ctx_res = benchmark_context_wall_1k_to_64k(device) return { "audit_fingerprint_sha256_16": compute_config_fingerprint(spec), "roofline_ar_vs_block_parallel": roofline_res, "context_wall_1k_to_64k": ctx_res, } if __name__ == "__main__": print(json.dumps(run_roofline_and_kv_audit(torch.device("cuda")), indent=2))