"""Draft-head GEMV microbenchmark for session H: the lm_head projection alone, BF16 vs vLLM 0.33.0's quantized copies. Builds the heads exactly as the server does: a ParallelLMHead in BF16 (the target's head; UnquantizedEmbeddingMethod, i.e. F.linear on cuBLAS), and the drafter's copies from vllm.model_executor.layers.quantization.online.lm_head .quantized_lm_head_copy ("fp8": Fp8PtpcOnlineLinearMethod, per-row weights and per-token activations; "nvfp4": _LMHeadNvfp4Method, weight-only W4A16 via init_nvfp4_linear_kernel(use_a16=True)). Times quant_method.apply(head, x) at M rows (M = concurrency: each draft step projects one hidden state per request), one call captured in a CUDA graph and replayed `--reps` times between CUDA events, median of `--trials`. The weights (0.3-1.3 GB) are far larger than L2, so every replay reads them from DRAM (the PR's "cold L2" condition holds by size). The setup mirrors tests/v1/worker/test_gpu_draft_lm_head.py @ v0.33.0 (single-rank distributed init, a default VllmConfig, and the model dtype the online FP8 method reads). Shapes: 248320 x 2048 (Qwen3.6-35B-A3B, the model we serve) and 248320 x 2560 (the PR's Qwen3.8-Flash-Next head, to check our numbers against the PR's kernel table). Run on an idle GPU (session-h.sh runs it after SGLang and the speech server are stopped). """ import argparse import json import os import statistics import tempfile from types import SimpleNamespace import torch p = argparse.ArgumentParser() p.add_argument("--shapes", default="248320x2048,248320x2560") p.add_argument("--ms", default="1,2,3,4,8,16") p.add_argument("--formats", default="bf16,fp8,nvfp4") p.add_argument("--weights", default="", help="safetensors file holding lm_head.weight (used where the shape matches)") p.add_argument("--reps", type=int, default=100) p.add_argument("--trials", type=int, default=3) p.add_argument("--out", required=True) a = p.parse_args() import vllm # noqa: E402 import vllm.model_executor.layers.quantization.online.fp8 as online_fp8 # noqa: E402 from vllm.config import VllmConfig, set_current_vllm_config # noqa: E402 from vllm.distributed import ( # noqa: E402 cleanup_dist_env_and_memory, init_distributed_environment, initialize_model_parallel, ) from vllm.model_executor.layers.quantization.online.lm_head import quantized_lm_head_copy # noqa: E402 from vllm.model_executor.layers.vocab_parallel_embedding import ParallelLMHead # noqa: E402 from vllm.utils.torch_utils import set_default_torch_dtype # noqa: E402 # As in the unit test: the online FP8 method reads the model dtype from the current config. online_fp8.get_current_vllm_config = lambda: SimpleNamespace(model_config=SimpleNamespace(dtype=torch.bfloat16)) def kernel_names(method) -> list[str]: names = [] for k, v in vars(method).items(): n = type(v).__name__ if "Kernel" in n or "kernel" in k.lower() or "linear" in k.lower(): names.append(f"{k}={n}") return names or [type(method).__name__] def nbytes(module) -> int: ts = dict(module.named_parameters(recurse=False)) | dict(module.named_buffers(recurse=False)) return sum(t.numel() * t.element_size() for k, t in ts.items() if k != "workspace") def time_graph(fn, x) -> list[float]: s = torch.cuda.Stream() s.wait_stream(torch.cuda.current_stream()) with torch.cuda.stream(s): for _ in range(3): fn(x) torch.cuda.current_stream().wait_stream(s) torch.cuda.synchronize() g = torch.cuda.CUDAGraph() with torch.cuda.graph(g): fn(x) g.replay() torch.cuda.synchronize() out = [] for _ in range(a.trials): t0, t1 = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True) t0.record() for _ in range(a.reps): g.replay() t1.record() torch.cuda.synchronize() out.append(t0.elapsed_time(t1) / a.reps) del g return out result = {"vllm": vllm.__version__, "torch": torch.__version__, "device": torch.cuda.get_device_name(0), "capability": list(torch.cuda.get_device_capability(0)), "reps": a.reps, "trials": a.trials, "shapes": {}} fd, tmp = tempfile.mkstemp() os.close(fd) ms = [int(m) for m in a.ms.split(",")] try: with set_current_vllm_config(VllmConfig()): init_distributed_environment(world_size=1, rank=0, distributed_init_method=f"file://{tmp}", local_rank=0, backend="nccl") initialize_model_parallel(1, 1) for shape in a.shapes.split(","): vocab, hidden = (int(v) for v in shape.split("x")) with set_default_torch_dtype(torch.bfloat16), torch.device("cuda"): head = ParallelLMHead(vocab, hidden, params_dtype=torch.bfloat16, disable_tp=True) src = "random N(0, 0.02)" if a.weights: from safetensors import safe_open with safe_open(a.weights, framework="pt", device="cuda") as f: if "lm_head.weight" in f.keys() and tuple(f.get_slice("lm_head.weight").get_shape()) == (vocab, hidden): head.weight.data.copy_(f.get_tensor("lm_head.weight")) src = f"lm_head.weight from {os.path.basename(a.weights)}" if src.startswith("random"): head.weight.data.normal_(0.0, 0.02) entry = {"weights": src} for fmt in a.formats.split(","): rec = {} try: mod = head if fmt == "bf16" else quantized_lm_head_copy(head, fmt) rec["kernel"] = kernel_names(mod.quant_method) rec["weight_bytes"] = nbytes(mod) def fn(x, mod=mod): return mod.quant_method.apply(mod, x) rec["ms"], rec["trials_ms"], rec["GBps"] = {}, {}, {} for m in ms: x = torch.randn(m, hidden, device="cuda", dtype=torch.bfloat16) t = time_graph(fn, x) med = statistics.median(t) rec["ms"][m], rec["trials_ms"][m] = round(med, 4), [round(v, 4) for v in t] rec["GBps"][m] = round(rec["weight_bytes"] / med / 1e6, 1) if mod is not head: del mod except Exception as e: # noqa: BLE001 - recorded, the other formats still run rec["error"] = repr(e)[:500] entry[fmt] = rec print(f"{shape} {fmt}: {rec.get('ms', rec.get('error'))}", flush=True) torch.cuda.empty_cache() result["shapes"][shape] = entry del head torch.cuda.empty_cache() finally: with open(a.out, "w") as f: json.dump(result, f, indent=1) cleanup_dist_env_and_memory() os.unlink(tmp)