From 3d334c33698f70ceb16a8dc33fe69c851cb11178 Mon Sep 17 00:00:00 2001 From: Antoine Buttier Date: Sun, 1 Nov 2026 18:21:25 +0100 Subject: [PATCH 1/3] Track the vLLM comparison scripts in bench/ref The race scripts lived in a gitignored bench/ref/ and were lost; they are rebuilt and tracked now. The venv, the W8A16 model copies and the results stay ignored. - Race: 1 s warm-up before timing (a single warm-up request left the GPU clock at 900-1600 MHz, which made 1-token latencies multimodal on both engines); INT8 weights and KV options (vLLM through a W8A16 compressed-tensors copy quantized as quantize_int8, and int8_per_token_head). - Speculative decoding on bench/speculative.jl's chat prompts, same token ids on both engines: plain, n-gram and DFlash, in BF16 and INT8. - run_all.sh reruns everything into results//; requirements.txt pins the vLLM env. - performance.md: refreshed BF16 race and new INT8 and speculative comparison (2026-11-01), with the setup they ran in. Co-Authored-By: Claude Opus 5.5 --- .gitignore | 4 +- CLAUDE.md | 1 + bench/ref/README.md | 29 ++++++ bench/ref/alternate.py | 122 ++++++++++++++++++++++ bench/ref/make_w8a16.py | 92 +++++++++++++++++ bench/ref/requirements.txt | 201 ++++++++++++++++++++++++++++++++++++ bench/ref/run_all.sh | 42 ++++++++ bench/ref/spec_prompts.jl | 26 +++++ bench/ref/spec_prompts.json | 1 + bench/ref/tileinfer_race.jl | 72 +++++++++++++ bench/ref/tileinfer_spec.jl | 77 ++++++++++++++ bench/ref/vllm_race.py | 97 +++++++++++++++++ bench/ref/vllm_spec.py | 111 ++++++++++++++++++++ docs/src/performance.md | 150 +++++++++++++++++++-------- 14 files changed, 980 insertions(+), 45 deletions(-) create mode 100644 bench/ref/README.md create mode 100644 bench/ref/alternate.py create mode 100644 bench/ref/make_w8a16.py create mode 100644 bench/ref/requirements.txt create mode 100755 bench/ref/run_all.sh create mode 100644 bench/ref/spec_prompts.jl create mode 100644 bench/ref/spec_prompts.json create mode 100644 bench/ref/tileinfer_race.jl create mode 100644 bench/ref/tileinfer_spec.jl create mode 100644 bench/ref/vllm_race.py create mode 100644 bench/ref/vllm_spec.py diff --git a/.gitignore b/.gitignore index 8c0ebd1..8fce973 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,8 @@ LocalPreferences.toml bench/results/ *.cov coverage/ -bench/ref/ +bench/ref/.venv/ +bench/ref/models/ __pycache__/ docs/build/ +bench/ref/results/ diff --git a/CLAUDE.md b/CLAUDE.md index 4d94bca..c657ea1 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -23,6 +23,7 @@ julia --project=bench bench/speculative.jl [--model REPO] [--draft REPO] [--dfla ncu --profile-from-start off --set full -c 1 -o bench/results/NAME \ julia --project=bench bench/profile.jl --model Qwen/Qwen3-0.6B Qwen3-0.6B/ops/linear_down/decode/tile # one kernel under Nsight Compute python3 bench/ncu_summary.py bench/results/NAME.ncu-repz [--compare OLD.ncu-repz] # compact report +bench/ref/run_all.sh [DATE] # race + INT8 + speculative decoding against vLLM into bench/ref/results/DATE/, ~2.5 h (setup: bench/ref/README.md) julia --project=bench bench/codegen/run.jl [filters] # cuTile codegen probes and kernel census, ~11 min julia --project=docs docs/make.jl # documentation site into docs/build/, ~15 s, no GPU needed ``` diff --git a/bench/ref/README.md b/bench/ref/README.md new file mode 100644 index 0000000..b1bc75d --- /dev/null +++ b/bench/ref/README.md @@ -0,0 +1,29 @@ +# Comparison with vLLM + +TileInfer against vLLM 0.31 on the same machine and the same token ids. Results and their +discussion, with the setup they came from: "Comparison with vLLM" in +[docs/src/performance.md](../../docs/src/performance.md). Runs write their JSON into +`results//` (not tracked). + +| File | What it does | +|---|---| +| `tileinfer_race.jl`, `vllm_race.py` | The race: 512-token prompt, 256 greedy tokens; latency of 1 and of 256 tokens, medians after a 1 s warm-up | +| `alternate.py` | Runs the two races in alternating fresh processes (ABBA, 3 rounds) and pools their trials; `--weights int8`, `--kv int8` | +| `make_w8a16.py` | A W8A16 compressed-tensors copy of a checkpoint, quantized as TileInfer's `quantize_int8`, for vLLM's INT8 runs (into `models/`, not tracked) | +| `spec_prompts.jl` → `spec_prompts.json` | `bench/speculative.jl`'s chat prompts as token ids, shared by both engines | +| `tileinfer_spec.jl`, `vllm_spec.py` | Greedy replies to those prompts with plain decoding, n-gram or DFlash, in BF16 or INT8 | +| `run_all.sh` | Everything above into `results//` (~2.5 h) | + +Setup (the environment is not tracked; `requirements.txt` pins the one the documented results came from): + +```sh +uv venv --python 3.12 bench/ref/.venv +uv pip install --python bench/ref/.venv/bin/python -r bench/ref/requirements.txt +bench/ref/.venv/bin/python bench/ref/make_w8a16.py Qwen/Qwen3-0.6B # and Qwen/Qwen3-4B +bench/ref/run_all.sh +``` + +vLLM's torch.compile finds `nvcc` in the pip-installed CUDA toolkit (no system toolkit +needed), and FlashInfer's sampler is disabled because its JIT build fails against it. +The vLLM scripts run offline from the Hugging Face cache, so pull the models first +(`julia --project -m TileInfer pull ...`, or `huggingface-cli download`). diff --git a/bench/ref/alternate.py b/bench/ref/alternate.py new file mode 100644 index 0000000..8005b88 --- /dev/null +++ b/bench/ref/alternate.py @@ -0,0 +1,122 @@ +"""Alternate the vLLM and TileInfer races so that drift in GPU clocks or desktop load hits +both engines alike, then summarize each engine over all its runs. + + python3 bench/ref/alternate.py [--model REPO] [--rounds 3] [--trials 10] [--prompt-len 512] [--gen 256] + [--weights bf16|int8] [--kv bf16|int8] + [--out bench/results/race-alternate.json] + +Round r runs vLLM then TileInfer when r is odd, TileInfer then vLLM when r is even (ABBA), +each in a fresh process via vllm_race.py / tileinfer_race.jl, which record every trial and +report medians (timings are heavy-tailed). The summary pools every trial of an engine +across rounds and reports medians as the primary result, with the minimum and the +quartiles. Before every run it records the other GPU processes and the SM clock, so a +disturbed run can be spotted afterwards. +""" + +import argparse +import json +import os +import statistics +import subprocess +import tempfile +import time + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(os.path.dirname(HERE)) +JULIA = os.environ.get("JULIA", os.path.expanduser("~/.juliaup/bin/julia")) + + +def gpu_state(): + apps = subprocess.run(["nvidia-smi", "--query-compute-apps=pid,process_name,used_memory", + "--format=csv,noheader"], capture_output=True, text=True).stdout + clock = subprocess.run(["nvidia-smi", "--query-gpu=clocks.sm,utilization.gpu", "--format=csv,noheader"], + capture_output=True, text=True).stdout.strip() + names = [line.split(",")[1].strip().split()[0].split("/")[-1] for line in apps.splitlines() if line.strip()] + return {"other_processes": names, "sm_clock_util": clock} + + +def vllm_model(a): + if a.weights == "bf16": + return a.model + path = os.path.join(HERE, "models", a.model.split("/")[-1] + "-w8a16") + if not os.path.isdir(path): + raise SystemExit(f"{path} missing: run bench/ref/make_w8a16.py {a.model}") + return path + + +def run_vllm(a): + with tempfile.NamedTemporaryFile(suffix=".json", delete=False) as f: + out = f.name + subprocess.run([os.path.join(HERE, ".venv", "bin", "python"), os.path.join(HERE, "vllm_race.py"), + "--model", vllm_model(a), "--kv-cache-dtype", "int8_per_token_head" if a.kv == "int8" else "auto", + "--prompt-len", str(a.prompt_len), "--gen", str(a.gen), + "--trials", str(a.trials), "--out", out], + check=True, cwd=ROOT, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + with open(out) as f: + res = json.load(f) + os.remove(out) + return res + + +def run_tileinfer(a): + proc = subprocess.run([JULIA, "--project=bench", os.path.join(HERE, "tileinfer_race.jl"), a.model, + str(a.prompt_len), str(a.gen), "tile", str(a.trials), a.weights, a.kv], + check=True, cwd=ROOT, capture_output=True, text=True) + return json.loads(proc.stdout[proc.stdout.index("{"):]) + + +def summary(values): + q1, median, q3 = statistics.quantiles(values, n=4) + return {"n": len(values), "min": min(values), "q1": q1, "median": median, "q3": q3, "max": max(values)} + + +def main(): + p = argparse.ArgumentParser() + p.add_argument("--model", default="Qwen/Qwen3-0.6B") + p.add_argument("--rounds", type=int, default=3) + p.add_argument("--trials", type=int, default=10) + p.add_argument("--prompt-len", type=int, default=512) + p.add_argument("--gen", type=int, default=256) + p.add_argument("--weights", default="bf16", choices=["bf16", "int8"], + help="int8: TileInfer quantize = :int8, vLLM the W8A16 copy from make_w8a16.py") + p.add_argument("--kv", default="bf16", choices=["bf16", "int8"], + help="int8: TileInfer Int8Pages, vLLM kv_cache_dtype = int8_per_token_head") + p.add_argument("--out", default=os.path.join(ROOT, "bench", "results", "race-alternate.json")) + a = p.parse_args() + + engines = {"vllm": run_vllm, "tileinfer": run_tileinfer} + runs = [] + for r in range(1, a.rounds + 1): + order = ["vllm", "tileinfer"] if r % 2 else ["tileinfer", "vllm"] + for name in order: + state = gpu_state() + t = time.time() + res = engines[name](a) + runs.append({"round": r, "engine": name, "gpu_before": state, "wall_s": time.time() - t, **res}) + print(f"round {r} {name:9s} median: decode {res['decode_tok_s']:6.1f} tok/s " + f"prefill {res['prefill_ms']:6.2f} ms e2e {res['e2e_s']:.4f} s " + f"(min-based: prefill {res['prefill_ms_min']:6.2f} ms) " + f"first tokens {res['first_tokens'][:4]} [{state['sm_clock_util']}; " + f"{', '.join(state['other_processes'])}]", flush=True) + + # Pool every trial of an engine across its runs. Decode comes from the pooled medians: + # (median latency(gen) - median latency(1)) / (gen - 1). + result = {"config": vars(a), "runs": runs, "summary": {}} + print(f"\nall trials pooled ({a.rounds} runs x {a.trials} trials per engine); median [q1, q3], min") + for name in engines: + mine = [x for x in runs if x["engine"] == name] + pre = summary([1e3 * t for x in mine for t in x["trials_prefill_s"]]) + e2e = summary([t for x in mine for t in x["trials_e2e_s"]]) + decode_ms = 1e3 * (e2e["median"] - pre["median"] / 1e3) / (a.gen - 1) + result["summary"][name] = {"prefill_ms": pre, "e2e_s": e2e, "decode_ms_per_tok": decode_ms, + "decode_tok_s": 1e3 / decode_ms} + print(f"{name:10s} prefill {pre['median']:6.2f} ms [{pre['q1']:6.2f}, {pre['q3']:6.2f}], min {pre['min']:6.2f}" + f" e2e {e2e['median']:.4f} s [{e2e['q1']:.4f}, {e2e['q3']:.4f}], min {e2e['min']:.4f}" + f" decode {decode_ms:.3f} ms/tok = {1e3 / decode_ms:5.1f} tok/s") + with open(a.out, "w") as f: + json.dump(result, f, indent=2) + print(f"saved {a.out}") + + +if __name__ == "__main__": + main() diff --git a/bench/ref/make_w8a16.py b/bench/ref/make_w8a16.py new file mode 100644 index 0000000..1282e66 --- /dev/null +++ b/bench/ref/make_w8a16.py @@ -0,0 +1,92 @@ +"""Write a W8A16 compressed-tensors copy of a Hugging Face checkpoint for vLLM, quantized +exactly as TileInfer's `quantize_int8`: every linear weight (and the lm_head, untied from +the embedding) as Int8 with one symmetric scale per output channel, max |W[j, :]| / 127, +rounded to nearest and clamped to [-127, 127]. The embedding stays in BFloat16. vLLM runs +it with its Marlin W8A16 kernels (`pack-quantized`, 8 bits, channel strategy). + + bench/ref/.venv/bin/python bench/ref/make_w8a16.py Qwen/Qwen3-0.6B [--out DIR] + +Default output: bench/ref/models/-w8a16. +""" + +import argparse +import glob +import json +import os +import shutil + +import torch +from compressed_tensors.compressors.pack_quantized.helpers import pack_to_int32 +from safetensors import safe_open +from safetensors.torch import save_file + +HERE = os.path.dirname(os.path.abspath(__file__)) +LINEAR = ("q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj") + + +def quantize(w): + """(out, in) BFloat16 -> packed Int8 (out, in / 4) as int32 and (out, 1) scales.""" + w = w.float() + absmax = w.abs().amax(dim=1, keepdim=True) + scale = torch.where(absmax > 0, absmax / 127, torch.ones_like(absmax)) + q = torch.clamp(torch.round(w / scale), -127, 127).to(torch.int8) + return pack_to_int32(q, 8), scale.to(torch.bfloat16) + + +def main(): + p = argparse.ArgumentParser() + p.add_argument("model") + p.add_argument("--out", default=None) + a = p.parse_args() + org, name = a.model.split("/") + snaps = glob.glob(os.path.expanduser(f"~/.cache/huggingface/hub/models--{org}--{name}/snapshots/*")) + src = max(snaps, key=os.path.getmtime) + out = a.out or os.path.join(HERE, "models", a.model.split("/")[-1] + "-w8a16") + os.makedirs(out, exist_ok=True) + + tensors = {} + for f in sorted(glob.glob(os.path.join(src, "*.safetensors"))): + with safe_open(f, "pt") as st: + for k in st.keys(): + tensors[k] = st.get_tensor(k) + if "lm_head.weight" not in tensors: + tensors["lm_head.weight"] = tensors["model.embed_tokens.weight"].clone() + + result = {} + for k, w in tensors.items(): + name = k.removesuffix(".weight") + if k.endswith(".weight") and (name.split(".")[-1] in LINEAR or name == "lm_head"): + packed, scale = quantize(w) + result[name + ".weight_packed"] = packed + result[name + ".weight_scale"] = scale + result[name + ".weight_shape"] = torch.tensor(list(w.shape), dtype=torch.int32) + else: + result[k] = w.contiguous() + save_file(result, os.path.join(out, "model.safetensors"), metadata={"format": "pt"}) + + with open(os.path.join(src, "config.json")) as f: + cfg = json.load(f) + cfg["tie_word_embeddings"] = False + cfg["quantization_config"] = { + "quant_method": "compressed-tensors", + "format": "pack-quantized", + "quantization_status": "compressed", + "ignore": [], + "config_groups": {"group_0": { + "targets": ["Linear", "lm_head"], + "format": "pack-quantized", + "weights": {"num_bits": 8, "type": "int", "symmetric": True, "strategy": "channel", + "dynamic": False, "group_size": None, "observer": "minmax"}, + "input_activations": None, "output_activations": None, + }}, + } + with open(os.path.join(out, "config.json"), "w") as f: + json.dump(cfg, f, indent=2) + for f in os.listdir(src): + if f.startswith("tokenizer") or f in ("generation_config.json", "vocab.json", "merges.txt"): + shutil.copy(os.path.join(src, f), out) + print(out) + + +if __name__ == "__main__": + main() diff --git a/bench/ref/requirements.txt b/bench/ref/requirements.txt new file mode 100644 index 0000000..97ce87f --- /dev/null +++ b/bench/ref/requirements.txt @@ -0,0 +1,201 @@ +# The environment the 2026-11-01 comparison ran in (uv pip freeze of bench/ref/.venv, Python 3.12). +# uv venv --python 3.12 bench/ref/.venv && uv pip install --python bench/ref/.venv/bin/python -r bench/ref/requirements.txt +agent-detector==2.0.0 +aiohappyeyeballs==2.7.1 +aiohttp==3.14.5 +aiosignal==1.4.0 +annotated-doc==0.0.5 +annotated-types==0.8.0 +anthropic==2.3.0 +anyio==4.15.1 +apache-tvm-ffi==0.1.11 +astor==0.8.1 +attrs==26.1.0 +blake3==1.0.11 +cachetools==7.2.6 +cbor2==6.1.5 +certifi==2026.10.23 +cffi==2.1.1 +charset-normalizer==3.5.2 +click==8.5.0 +cloudpickle==3.1.2 +compressed-tensors==0.17.0 +cryptography==50.0.2 +cuda-bindings==13.4.4 +cuda-core==1.2.2 +cuda-pathfinder==1.8.4 +cuda-python==13.4.4 +cuda-tile==1.7.0 +cuda-toolkit==13.0.3.0 +depyf==0.20.0 +detect-installer==0.2.1 +dill==0.4.1 +dnspython==2.9.0 +docstring-parser==0.18.0 +einops==0.8.2 +email-validator==2.3.0 +fastapi==0.136.3 +fastapi-cli==0.0.32 +fastapi-cloud-cli==0.26.0 +fastar==0.12.0 +fastsafetensors==0.5.0 +filelock==4.2.4 +flashinfer-python==0.7.0.post1 +frozenlist==1.8.0 +fsspec==2026.9.0 +googleapis-common-protos==1.76.0 +grpcio==1.85.0 +h11==0.16.0 +hf-xet==1.7.0 +httpcore==1.0.9 +httpcore2==2.16.0 +httptools==0.9.0 +httpx==0.28.1 +httpx2==2.16.0 +huggingface-hub==1.33.0 +humming-kernels==0.1.16 +idna==3.20 +ijson==3.6.0 +instanttensor==0.2.2 +interegular==0.3.3 +jinja2==3.1.6 +jiter==0.18.0 +jmespath==1.1.0 +jsonschema==4.26.0 +jsonschema-specifications==2025.9.1 +lark==1.2.2 +llguidance==1.7.6 +llvmlite==0.47.0 +lm-format-enforcer==0.11.3 +loguru==0.7.3 +markdown-it-py==4.2.0 +markupsafe==3.0.4 +mcp==2.3.0 +mcp-types==2.3.0 +mdurl==0.1.2 +mistral-common==1.12.0 +ml-dtypes==0.6.0 +model-hosting-container-standards==0.1.16 +mpmath==1.3.0 +msgspec==0.22.0 +multidict==7.2.1 +nccl-extensions==0.1.0 +nccl4py==0.6.0 +networkx==3.7 +ninja==1.13.2 +numba==0.65.0 +numpy==2.3.5 +nvidia-cublas==13.1.1.3 +nvidia-cuda-cccl==13.3.4.3.1 +nvidia-cuda-crt==13.4.92 +nvidia-cuda-cupti==13.0.85 +nvidia-cuda-nvcc==13.4.92 +nvidia-cuda-nvdisasm==13.4.92 +nvidia-cuda-nvrtc==13.0.88 +nvidia-cuda-runtime==13.0.96 +nvidia-cudnn-cu13==9.20.0.48 +nvidia-cudnn-frontend==1.31.0 +nvidia-cufft==12.0.0.61 +nvidia-cufile==1.15.1.6 +nvidia-curand==10.4.0.35 +nvidia-cusolver==12.0.4.66 +nvidia-cusparse==12.6.3.3 +nvidia-cusparselt-cu13==0.8.1 +nvidia-cutlass-dsl==4.7.1 +nvidia-cutlass-dsl-libs-base==4.7.1 +nvidia-cutlass-dsl-libs-core==4.7.1 +nvidia-cutlass-dsl-libs-cu12==4.7.1 +nvidia-cutlass-dsl-libs-cu13==4.7.1 +nvidia-ml-py==13.615.71 +nvidia-nccl-cu13==2.29.7 +nvidia-nvjitlink==13.4.92 +nvidia-nvshmem-cu13==3.4.5 +nvidia-nvtx==13.0.85 +nvidia-nvvm==13.4.92 +nvtx==0.2.15 +openai==3.40.0 +opencv-python-headless==5.0.0.93 +opentelemetry-api==1.45.1 +opentelemetry-exporter-http-transport==0.66b1 +opentelemetry-exporter-otlp==1.45.1 +opentelemetry-exporter-otlp-common==0.66b1 +opentelemetry-exporter-otlp-proto-common==1.45.1 +opentelemetry-exporter-otlp-proto-grpc==1.45.1 +opentelemetry-exporter-otlp-proto-http==1.45.1 +opentelemetry-proto==1.45.1 +opentelemetry-sdk==1.45.1 +opentelemetry-semantic-conventions==0.66b1 +opentelemetry-semantic-conventions-ai==0.5.1 +oss-harmony==0.0.11 +outlines-core==0.2.14 +packaging==26.3 +partial-json-parser==0.2.1.1.post7 +pillow==13.0.0 +prometheus-client==0.26.0 +prometheus-fastapi-instrumentator==8.1.0 +propcache==0.5.4 +protobuf==7.36.1 +psutil==7.2.2 +py-cpuinfo==9.0.0 +pybase64==1.5.1 +pycountry==26.2.16 +pycparser==3.12 +pydantic==2.14.1 +pydantic-core==2.50.1 +pydantic-extra-types==2.11.1 +pydantic-settings==2.16.1 +pygments==2.21.0 +pyjwt==2.15.1 +pynvvideocodec==2.0.4 +python-dotenv==1.2.4 +python-json-logger==4.2.0 +python-multipart==0.0.32 +pyyaml==6.0.3 +pyzmq==27.2.0 +quack-kernels==0.6.5 +referencing==0.37.0 +regex==2026.9.29 +requests==2.34.2 +rich==15.0.0 +rich-toolkit==0.20.6 +rignore==0.8.1 +rpds-py==2026.9.1 +safetensors==0.8.0 +sentencepiece==0.2.2 +sentry-sdk==2.73.0 +setproctitle==1.3.8 +setuptools==80.10.2 +shellingham==1.5.4 +six==1.17.0 +sniffio==1.3.1 +sse-starlette==3.6.0 +starlette==1.10.0 +supervisor==4.3.0 +sympy==1.14.0 +tabulate==0.10.0 +tiktoken==0.14.0 +tilelang==0.1.12 +tokenizers==0.23.3 +tokenspeed-mla==0.1.8 +tokenspeed-triton==3.9.10.post20261008 +torch==2.13.0 +torch-c-dlpack-ext==0.1.5 +torchaudio==2.11.0 +torchcodec==0.17.0 +torchvision==0.28.0 +tqdm==4.70.1 +transformers==5.17.0 +triton==3.7.1 +truststore==0.10.5 +typer==0.27.3 +typing-extensions==4.16.0 +typing-inspection==0.4.4 +urllib3==2.8.0 +uvicorn==0.54.0 +uvloop==0.23.0 +vllm==0.31.0 +watchfiles==1.3.0 +websockets==17.3 +xgrammar==0.2.7 +yarl==1.25.1 +z3-solver==4.15.4.0 diff --git a/bench/ref/run_all.sh b/bench/ref/run_all.sh new file mode 100755 index 0000000..16e8141 --- /dev/null +++ b/bench/ref/run_all.sh @@ -0,0 +1,42 @@ +#!/usr/bin/env bash +# The whole vLLM comparison into bench/ref/results// (~2.5 h): the race on both models +# in BF16 and with INT8 weights and/or KV (alternate.py), then the speculative-decoding runs +# on the chat prompts (tileinfer_spec.jl / vllm_spec.py, the engines alternating). +# +# bench/ref/run_all.sh [date] # needs bench/ref/.venv and the W8A16 copies (make_w8a16.py) +set -u +cd "$(dirname "$0")/../.." +JULIA=${JULIA:-~/.juliaup/bin/julia} +D=bench/ref/results/${1:-$(date +%F)} +mkdir -p "$D/spec" + +for m in Qwen3-0.6B Qwen3-4B; do + for cfg in "bf16 bf16 bf16" "int8 bf16 int8-weights" "bf16 int8 int8-kv" "int8 int8 int8-weights-kv"; do + set -- $cfg + echo "=== race $m $3" + python3 -u bench/ref/alternate.py --model Qwen/$m --rounds 3 --trials 10 --weights $1 --kv $2 \ + --out "$D/race-$m-$3.json" 2>&1 | grep -v '^ [0-9]' + done +done + +i=0 +spec() { # model method k weights kv + local tag="$(basename $1)-$2$3-w$4-kv$5" order="vllm tileinfer" + i=$((i + 1)); [ $((i % 2)) = 0 ] && order="tileinfer vllm" + for e in $order; do + echo "=== spec $e $tag" + if [ $e = vllm ]; then + bench/ref/.venv/bin/python bench/ref/vllm_spec.py "$@" > "$D/spec/$e-$tag.json" 2> "$D/spec/$e-$tag.err" + else + $JULIA --project=bench bench/ref/tileinfer_spec.jl "$@" > "$D/spec/$e-$tag.json" 2> "$D/spec/$e-$tag.err" + fi + echo "exit $?"; grep -E ' out [0-9]+ decode' "$D/spec/$e-$tag.err" + done +} +for wk in "bf16 bf16" "int8 int8"; do + spec Qwen/Qwen3-4B plain 0 $wk + spec Qwen/Qwen3-4B dflash 7 $wk + spec Qwen/Qwen3-4B dflash 15 $wk + spec Qwen/Qwen3-0.6B plain 0 $wk + spec Qwen/Qwen3-0.6B ngram 4 $wk +done diff --git a/bench/ref/spec_prompts.jl b/bench/ref/spec_prompts.jl new file mode 100644 index 0000000..af85f02 --- /dev/null +++ b/bench/ref/spec_prompts.jl @@ -0,0 +1,26 @@ +# Export bench/speculative.jl's chat prompts as token ids (chat template applied, thinking +# off) with the model's stop ids, so that vllm_spec.py and tileinfer_spec.jl feed both +# engines the same tokens. Qwen3-0.6B and Qwen3-4B share the tokenizer. +# +# julia --project=bench bench/ref/spec_prompts.jl [model] > bench/ref/spec_prompts.json + +using TileInfer, JSON +using TileInfer: ChatMessage, chat_prompt, encode, generation_defaults, load_config, load_tokenizer, model_dir + +# Only the `const` definitions of bench/speculative.jl (CODE, LONG_DOCUMENT, PROMPTS), not its main. +const SPEC = joinpath(@__DIR__, "..", "speculative.jl") +const SRC = replace(read(SPEC, String), "@__DIR__" => repr(dirname(abspath(SPEC)))) +for ex in Meta.parseall(SRC; filename = SPEC).args + ex isa Expr && ex.head === :const && Core.eval(Main, ex) +end + +dir = model_dir(get(ARGS, 1, "Qwen/Qwen3-4B")) +cfg = load_config(dir) +tok = load_tokenizer(dir) +_, stop_ids = generation_defaults(dir, cfg) +prompts = [Dict("name" => name, + "ids" => encode(tok, chat_prompt(cfg.model_type, [ChatMessage("user", text)]; enable_thinking = false); + add_special_tokens = false)) + for (name, text) in PROMPTS] +JSON.print(stdout, Dict("stop_ids" => collect(stop_ids), "prompts" => prompts)) +println() diff --git a/bench/ref/spec_prompts.json b/bench/ref/spec_prompts.json new file mode 100644 index 0000000..fb7a747 --- /dev/null +++ b/bench/ref/spec_prompts.json @@ -0,0 +1 @@ +{"prompts":[{"ids":[151644,872,198,88757,279,3890,1565,82,63,311,1565,4475,63,323,1565,81,63,311,1565,12445,63,304,419,39294,729,13,17841,448,279,2480,2038,1172,382,1688,79994,20011,10297,88,11,856,11,289,11,17986,340,262,369,502,304,24745,2075,11,220,17,340,286,274,284,7168,18584,1313,2075,1171,286,369,600,304,24745,2075,11,220,16,340,310,274,1421,856,989,11,502,90304,17,198,286,835,198,286,435,284,220,16,608,17946,1141,608,1379,2075,11,220,16,8,488,17986,340,286,369,600,304,24745,2075,11,220,16,340,310,379,989,11,502,60,284,856,989,11,502,60,353,435,353,289,989,921,286,835,198,262,835,198,262,470,379,198,408,198,151645,198,151644,77091,198,151667,271,151668,271],"name":"rename"},{"ids":[151644,872,198,2212,264,4629,917,323,264,3980,389,1817,6337,311,419,39294,729,13,17841,448,279,2480,2038,1172,382,1688,79994,20011,10297,88,11,856,11,289,11,17986,340,262,369,502,304,24745,2075,11,220,17,340,286,274,284,7168,18584,1313,2075,1171,286,369,600,304,24745,2075,11,220,16,340,310,274,1421,856,989,11,502,90304,17,198,286,835,198,286,435,284,220,16,608,17946,1141,608,1379,2075,11,220,16,8,488,17986,340,286,369,600,304,24745,2075,11,220,16,340,310,379,989,11,502,60,284,856,989,11,502,60,353,435,353,289,989,921,286,835,198,262,835,198,262,470,379,198,408,198,151645,198,151644,77091,198,151667,271,151668,271],"name":"document"},{"ids":[151644,872,198,840,20772,1246,264,5175,2415,13469,47353,11,448,458,3110,13,151645,198,151644,77091,198,151667,271,151668,271],"name":"explain"},{"ids":[151644,872,198,7985,264,2805,3364,911,264,326,57909,53416,879,13719,264,14888,5662,389,279,11321,13,151645,198,151644,77091,198,151667,271,151668,271],"name":"story"},{"ids":[151644,872,198,88757,1565,1712,19486,63,311,1565,8304,19486,63,6814,419,39294,1034,13,17841,448,279,2480,1034,1172,382,2,49990,279,4637,7354,315,825,1614,389,825,84648,6500,13,362,3019,315,264,2421,11211,320,18196,11,323,198,2,65736,22901,2937,8,374,11626,438,264,54809,4771,25,279,1156,3019,315,1817,3950,198,2,1760,8473,62373,11,892,1367,3658,1181,63515,11,323,374,1221,17006,26,2937,7354,315,429,198,2,1760,1172,8135,862,11127,1119,279,3019,594,1099,27389,323,34485,279,4771,11,825,198,2,7050,4518,315,3968,20,19,15,13,93326,7354,320,30552,483,8,1598,62373,448,27389,315,862,1828,624,4956,2,362,17006,4771,9982,279,3671,14230,315,279,14324,11,279,6500,33139,323,279,1099,198,2,27389,11,323,279,63515,1349,1449,817,29208,897,320,3365,11,9892,11,15711,11,2504,1965,340,2,504,1846,27389,11,773,432,26558,2697,438,1293,438,279,22259,1558,382,1,33951,315,705,311,419,1657,11211,525,17006,304,54809,38999,10040,1024,8334,58360,18681,50,284,220,23,271,30473,2036,16603,3073,8304,76025,532,262,27389,486,8304,36219,76025,532,262,4771,486,32658,90,23780,11289,31291,727,84,11212,10216,532,408,271,7129,262,4903,19486,7635,11,6500,26,38999,284,11554,14738,82,7635,37187,4390,25925,7354,315,1565,2528,63,389,1565,9360,7808,448,54809,38999,369,7354,315,705,311,198,3,10586,58360,18681,50,11211,979,1565,86186,28587,6452,7354,448,1565,13435,10297,41736,11,12981,11,14151,8,18639,7129,30473,2036,4903,19486,76025,27014,27,25,20732,10994,76025,2137,34,27,25,47,3279,82707,8233,76025,11248,262,733,1614,486,44,198,262,733,6500,486,34,198,262,733,38999,486,11233,198,262,733,7354,486,13448,90,1072,11289,80228,8304,76025,11248,262,733,10146,22731,486,13448,90,28681,90,1072,11,18777,2137,8610,92,256,671,25429,8304,76025,92,553,3950,1760,323,63592,6,2804,11,1490,1565,12446,0,3989,262,733,41799,486,3323,66048,414,671,3671,24892,1584,11,1490,1565,13611,6458,0,3989,262,733,3950,486,44819,3781,90,1072,18,17,92,257,671,279,3950,48876,553,264,3019,14319,29208,9471,198,262,15301,486,8610,503,671,50194,34656,11,3465,389,1156,990,198,262,733,10047,26091,486,3781,90,1072,92,262,671,13617,6693,16275,7354,2506,11,1490,1565,12552,30468,0,3989,262,1537,11946,486,8610,4293,671,14822,36219,315,279,5535,4637,476,10146,3019,345,262,1537,4906,486,1072,1698,671,323,279,2309,315,1181,1156,3950,198,408,271,1688,4903,19486,7635,486,20732,10994,76025,2137,6500,486,47,3279,82707,8233,76025,2440,3824,38999,486,11233,284,11554,14738,82,7635,37187,593,1380,314,51,532,262,38999,1009,753,77709,14738,82,7635,37187,8,6561,286,2510,7,9171,1454,445,8525,68442,11781,7635,37187,7705,7354,4157,387,17006,304,54809,38999,5455,262,470,4903,19486,7635,11,6500,11,38999,11,29126,90,1072,11289,80228,8304,76025,3417,1507,29126,90,28681,90,1072,11,18777,2137,8610,92,1507,9660,66048,7635,5423,77457,2368,1326,5180,26462,3781,90,1072,18,17,25547,16135,11,220,16,701,4302,11,1333,12995,4302,11,220,15,340,408,271,7129,262,7283,30468,10297,41736,11,13617,692,8078,1449,2937,3019,2506,279,32147,4269,1283,1565,44198,63,320,16,5980,8,304,1181,27389,1248,63,11981,7808,369,458,468,1890,867,44096,1046,26,279,5535,3019,594,27389,525,1565,41736,9110,11946,28587,89636,279,198,43203,3073,7354,979,279,13617,2297,624,7129,1688,7283,30468,10297,81,486,1712,19486,11,13617,340,262,435,5849,2200,26091,621,13617,1009,470,435,198,262,2975,10297,81,5849,2200,26091,11,13617,340,262,4287,10297,81,58746,340,262,4287,10297,81,27520,22731,340,262,435,57733,284,4302,198,262,435,9110,11946,284,4302,198,262,470,435,198,408,271,7129,262,4637,10297,41736,11,12981,11,14151,8,1464,26462,6689,90,5442,18,17,630,83148,13435,0,80709,5957,1097,8,1526,1565,41736,44622,279,60788,320,86847,11,220,16,8,315,279,1537,3950,13,1752,2805,198,24080,807,3887,304,279,3019,594,1099,27389,323,525,59173,553,279,1790,3019,315,279,198,24063,3084,11,773,1349,1105,1573,4303,2441,3019,624,7129,1688,4637,10297,81,486,1712,19486,11,12981,486,14076,11,14151,486,15949,3781,90,27,25,3486,3518,262,308,284,3084,43448,340,262,308,861,220,15,1369,2510,7,9171,1454,445,13435,0,3880,518,3245,825,3950,5455,262,435,9110,4906,284,3084,34820,340,262,421,308,861,8334,58360,18681,50,198,286,451,20457,55,58462,9669,330,30552,483,1,3161,198,310,293,284,14822,36219,2601,3192,11,435,20087,11,308,26,435,5849,2200,26091,340,310,10549,11946,10297,65,11,435,3192,11,435,20087,11,12981,11,14151,340,310,1598,11946,10297,81,3192,11,435,20087,11,293,340,286,835,198,286,8737,10297,13262,59549,11,14151,340,286,435,9110,11946,284,293,198,286,470,293,1665,1199,198,262,835,198,262,3019,284,633,0,5065,1464,16603,3073,8304,7,8304,36219,2601,3192,11,435,20087,11,308,26,435,5849,2200,26091,701,4302,701,435,58746,11,308,340,262,435,9110,11946,284,3019,948,20342,198,262,451,20457,55,58462,9669,330,6120,11127,1,10549,11946,10297,9520,948,20342,11,435,3192,11,435,20087,11,12981,11,14151,340,262,421,3019,10763,4376,4302,198,286,451,20457,55,58462,9669,330,265,1363,3019,1,54809,36452,38436,10763,340,262,770,198,286,451,20457,55,58462,9669,330,68,1409,3019,1,1598,11946,10297,81,3192,11,435,20087,11,3019,948,20342,340,286,421,435,10763,82,198,310,671,21566,279,37075,2041,4303,1105,25,279,23541,3019,2669,1521,624,310,3019,10763,284,451,20457,55,58462,9669,330,45070,3019,1,3161,198,394,54809,1858,42251,3025,31291,60523,5065,1464,1598,11946,10297,81,3192,11,435,20087,11,3019,948,20342,5929,310,835,198,286,835,198,262,835,198,262,8737,10297,13262,59549,11,14151,340,262,470,3019,948,20342,1665,1199,198,408,271,1,2833,315,17006,54809,38999,320,13435,323,10146,7354,568,698,2413,14738,82,2601,486,1712,19486,8,4035,262,1760,1141,1464,274,10763,4376,4302,11,2750,2601,58746,593,488,1760,1141,1464,274,10763,4376,4302,11,2750,2601,27520,22731,4390,2,12448,3714,3700,448,279,3468,825,3019,4815,279,22670,53923,4956,2,9043,7289,315,3019,27389,24609,13,576,3019,389,738,595,10469,1181,3950,389,279,3671,198,2,28654,13611,6458,0,63,448,279,22259,594,41799,8,7678,1119,279,14151,315,738,220,18,481,595,11,323,1119,198,2,1565,73225,58,18,481,595,60,63,304,3468,1448,5677,4938,13,2055,279,3468,646,7050,279,3019,429,59506,264,198,2,3950,1573,5290,432,25,1393,279,22670,8473,429,3019,11,279,3468,46936,369,279,3681,198,2,825,11,15804,1181,3950,11,12341,369,264,2936,3950,323,23045,432,13,576,22670,902,5021,877,642,198,2,1948,7354,382,30473,2036,50194,34656,76025,532,262,27389,486,6408,6061,90,17,11,8304,36219,76025,11248,262,38999,486,3781,90,32658,90,23780,11289,31291,727,84,11212,10216,11248,262,17846,486,44819,3781,90,1072,18,17,92,688,671,3468,1448,5677,25,17846,6732,60,374,279,3950,304,27389,6732,936,3365,198,262,17846,12848,486,3781,90,1072,18,17,532,262,2814,486,6408,6061,90,17,11289,84,1556,92,688,671,12433,1283,279,3019,389,1817,738,198,408,271,1688,16895,45187,2601,486,1712,19486,76025,5410,1380,314,51,532,262,435,57733,2049,4302,1369,470,435,57733,486,32564,34656,76025,532,262,17846,284,26462,1857,90,1072,18,17,11,16,11289,31291,29840,10642,25547,16135,11,220,17,340,262,1031,3848,284,320,8304,36219,2601,3192,11,435,20087,11,220,16,701,14822,36219,2601,3192,11,435,20087,11,220,16,1171,262,435,57733,284,50194,34656,76025,25547,5909,82,11,508,41212,11,4302,1125,17846,11,19860,38550,38192,11,17846,1326,9699,320,44819,1556,1507,26462,1556,12145,262,470,435,57733,198,408,271,2,19143,279,3950,315,1565,839,1199,63,1119,738,595,320,1199,14151,323,17846,9446,4292,13611,45514,10297,81,486,1712,19486,11,281,486,32564,34656,11,595,11,60788,8,4035,262,6077,6458,10297,81,3192,37187,11,281,948,20342,6732,936,3365,11,1651,1295,744,28812,11,595,57071,701,60788,11,435,514,34501,692,1688,1598,620,81079,1589,11946,10297,81,486,1712,19486,11,281,486,32564,34656,11,595,340,262,293,284,281,948,20342,6732,921,262,3019,368,284,320,6108,11946,10297,81,3192,11,435,20087,11,293,1215,6077,45514,10297,81,11,281,11,220,18,481,595,11,293,1665,1199,1171,262,421,281,10763,82,6732,60,2049,4302,198,286,451,20457,55,58462,9669,330,68,1409,3019,1,3019,741,286,281,10763,82,6732,60,284,451,20457,55,58462,9669,330,45070,3019,1,54809,1858,42251,3025,31291,60523,38436,1171,262,770,198,286,451,20457,55,58462,9669,330,265,1363,3019,1,54809,36452,1295,10763,82,6732,2546,262,835,198,262,3255,1295,31802,6732,2546,408,271,7129,262,6923,620,81079,1589,10297,41736,11,12981,11,14151,26,1932,5921,28838,11,2936,8077,11,389,6458,8,1464,4196,90,1072,630,83148,19366,0,80709,5957,1097,8,448,279,22259,594,41799,320,746,432,448,40518,9716,72812,0,80709,5957,1097,6965,51501,301,1589,773,429,279,3468,8473,825,3019,4815,279,22670,13,43140,264,22259,448,54809,38999,624,7129,1688,6923,620,81079,1589,10297,81,486,1712,19486,11,12981,486,14076,11,14151,486,15949,3781,90,27,25,3486,2440,6526,1932,5921,28838,486,3486,11,2936,8077,11,389,6458,284,4302,340,262,435,10763,82,1369,2510,7,9171,1454,445,51501,301,1589,47116,3880,54809,38999,5455,262,281,284,16895,45187,2601,340,262,7907,284,1333,19536,262,1932,5921,28838,861,220,15,1369,470,7907,198,262,60788,284,4637,10297,81,11,12981,11,14151,340,262,6077,45514,10297,81,11,281,11,220,16,11,60788,340,262,5527,284,26462,1556,741,262,3255,7,2307,8,503,671,279,1156,3950,11,304,738,220,16,198,262,595,284,220,16,999,671,279,738,6693,14151,3331,279,1790,3950,311,1349,198,262,1393,830,198,286,803,284,3084,3268,10543,8,488,220,16,366,1932,5921,28838,262,671,686,264,3950,1795,419,825,5267,286,421,803,2549,671,1598,279,3950,1573,14063,432,198,310,451,20457,55,58462,9669,330,6120,11127,1,10549,11946,10297,79,948,20342,6732,1125,435,3192,11,435,20087,11,12981,11,4302,340,310,1598,620,81079,1589,11946,10297,81,11,281,11,595,340,310,4484,10297,13262,59549,11,481,16,8,262,671,10199,304,3685,198,286,835,198,286,451,20457,55,58462,9669,330,11489,369,3950,1,63799,7,2307,340,286,877,284,1333,1295,744,28812,12848,6732,2546,286,803,1009,320,13262,59549,57208,60,284,877,340,286,421,877,304,2936,8077,198,310,421,803,1698,671,279,2936,3950,3937,1526,279,1614,25,5943,432,1549,198,394,63799,741,394,56772,10297,81,20087,11,12981,11,3084,34820,8,481,220,16,340,310,835,198,310,1438,198,286,835,198,286,4484,10297,16187,11,877,340,286,389,6458,2049,4302,1369,389,6458,3724,340,286,803,1369,1438,198,286,5527,11,595,284,281,31802,6732,1125,220,18,481,595,198,262,835,198,262,470,7907,198,408,198,151645,198,151644,77091,198,151667,271,151668,271],"name":"long-edit"},{"ids":[151644,872,198,840,20772,1246,419,39294,1034,27627,979,311,12322,264,54809,4771,323,979,311,34485,825,382,2,49990,279,4637,7354,315,825,1614,389,825,84648,6500,13,362,3019,315,264,2421,11211,320,18196,11,323,198,2,65736,22901,2937,8,374,11626,438,264,54809,4771,25,279,1156,3019,315,1817,3950,198,2,1760,8473,62373,11,892,1367,3658,1181,63515,11,323,374,1221,17006,26,2937,7354,315,429,198,2,1760,1172,8135,862,11127,1119,279,3019,594,1099,27389,323,34485,279,4771,11,825,198,2,7050,4518,315,3968,20,19,15,13,93326,7354,320,30552,483,8,1598,62373,448,27389,315,862,1828,624,4956,2,362,17006,4771,9982,279,3671,14230,315,279,14324,11,279,6500,33139,323,279,1099,198,2,27389,11,323,279,63515,1349,1449,817,29208,897,320,3365,11,9892,11,15711,11,2504,1965,340,2,504,1846,27389,11,773,432,26558,2697,438,1293,438,279,22259,1558,382,1,33951,315,705,311,419,1657,11211,525,17006,304,54809,38999,10040,1024,8334,58360,18681,50,284,220,23,271,30473,2036,16603,3073,8304,76025,532,262,27389,486,8304,36219,76025,532,262,4771,486,32658,90,23780,11289,31291,727,84,11212,10216,532,408,271,7129,262,4903,19486,7635,11,6500,26,38999,284,11554,14738,82,7635,37187,4390,25925,7354,315,1565,2528,63,389,1565,9360,7808,448,54809,38999,369,7354,315,705,311,198,3,10586,58360,18681,50,11211,979,1565,86186,28587,6452,7354,448,1565,13435,10297,41736,11,12981,11,14151,8,18639,7129,30473,2036,4903,19486,76025,27014,27,25,20732,10994,76025,2137,34,27,25,47,3279,82707,8233,76025,11248,262,733,1614,486,44,198,262,733,6500,486,34,198,262,733,38999,486,11233,198,262,733,7354,486,13448,90,1072,11289,80228,8304,76025,11248,262,733,10146,22731,486,13448,90,28681,90,1072,11,18777,2137,8610,92,256,671,25429,8304,76025,92,553,3950,1760,323,63592,6,2804,11,1490,1565,12446,0,3989,262,733,41799,486,3323,66048,414,671,3671,24892,1584,11,1490,1565,13611,6458,0,3989,262,733,3950,486,44819,3781,90,1072,18,17,92,257,671,279,3950,48876,553,264,3019,14319,29208,9471,198,262,15301,486,8610,503,671,50194,34656,11,3465,389,1156,990,198,262,733,10047,26091,486,3781,90,1072,92,262,671,13617,6693,16275,7354,2506,11,1490,1565,12552,30468,0,3989,262,1537,11946,486,8610,4293,671,14822,36219,315,279,5535,4637,476,10146,3019,345,262,1537,4906,486,1072,1698,671,323,279,2309,315,1181,1156,3950,198,408,271,1688,4903,19486,7635,486,20732,10994,76025,2137,6500,486,47,3279,82707,8233,76025,2440,3824,38999,486,11233,284,11554,14738,82,7635,37187,593,1380,314,51,532,262,38999,1009,753,77709,14738,82,7635,37187,8,6561,286,2510,7,9171,1454,445,8525,68442,11781,7635,37187,7705,7354,4157,387,17006,304,54809,38999,5455,262,470,4903,19486,7635,11,6500,11,38999,11,29126,90,1072,11289,80228,8304,76025,3417,1507,29126,90,28681,90,1072,11,18777,2137,8610,92,1507,9660,66048,7635,5423,77457,2368,1326,5180,26462,3781,90,1072,18,17,25547,16135,11,220,16,701,4302,11,1333,12995,4302,11,220,15,340,408,271,7129,262,7283,30468,10297,41736,11,13617,692,8078,1449,2937,3019,2506,279,32147,4269,1283,1565,44198,63,320,16,5980,8,304,1181,27389,1248,63,11981,7808,369,458,468,1890,867,44096,1046,26,279,5535,3019,594,27389,525,1565,41736,9110,11946,28587,89636,279,198,43203,3073,7354,979,279,13617,2297,624,7129,1688,7283,30468,10297,81,486,1712,19486,11,13617,340,262,435,5849,2200,26091,621,13617,1009,470,435,198,262,2975,10297,81,5849,2200,26091,11,13617,340,262,4287,10297,81,58746,340,262,4287,10297,81,27520,22731,340,262,435,57733,284,4302,198,262,435,9110,11946,284,4302,198,262,470,435,198,408,271,7129,262,4637,10297,41736,11,12981,11,14151,8,1464,26462,6689,90,5442,18,17,630,83148,13435,0,80709,5957,1097,8,1526,1565,41736,44622,279,60788,320,86847,11,220,16,8,315,279,1537,3950,13,1752,2805,198,24080,807,3887,304,279,3019,594,1099,27389,323,525,59173,553,279,1790,3019,315,279,198,24063,3084,11,773,1349,1105,1573,4303,2441,3019,624,7129,1688,4637,10297,81,486,1712,19486,11,12981,486,14076,11,14151,486,15949,3781,90,27,25,3486,3518,262,308,284,3084,43448,340,262,308,861,220,15,1369,2510,7,9171,1454,445,13435,0,3880,518,3245,825,3950,5455,262,435,9110,4906,284,3084,34820,340,262,421,308,861,8334,58360,18681,50,198,286,451,20457,55,58462,9669,330,30552,483,1,3161,198,310,293,284,14822,36219,2601,3192,11,435,20087,11,308,26,435,5849,2200,26091,340,310,10549,11946,10297,65,11,435,3192,11,435,20087,11,12981,11,14151,340,310,1598,11946,10297,81,3192,11,435,20087,11,293,340,286,835,198,286,8737,10297,13262,59549,11,14151,340,286,435,9110,11946,284,293,198,286,470,293,1665,1199,198,262,835,198,262,3019,284,633,0,5065,1464,16603,3073,8304,7,8304,36219,2601,3192,11,435,20087,11,308,26,435,5849,2200,26091,701,4302,701,435,58746,11,308,340,262,435,9110,11946,284,3019,948,20342,198,262,451,20457,55,58462,9669,330,6120,11127,1,10549,11946,10297,9520,948,20342,11,435,3192,11,435,20087,11,12981,11,14151,340,262,421,3019,10763,4376,4302,198,286,451,20457,55,58462,9669,330,265,1363,3019,1,54809,36452,38436,10763,340,262,770,198,286,451,20457,55,58462,9669,330,68,1409,3019,1,1598,11946,10297,81,3192,11,435,20087,11,3019,948,20342,340,286,421,435,10763,82,198,310,671,21566,279,37075,2041,4303,1105,25,279,23541,3019,2669,1521,624,310,3019,10763,284,451,20457,55,58462,9669,330,45070,3019,1,3161,198,394,54809,1858,42251,3025,31291,60523,5065,1464,1598,11946,10297,81,3192,11,435,20087,11,3019,948,20342,5929,310,835,198,286,835,198,262,835,198,262,8737,10297,13262,59549,11,14151,340,262,470,3019,948,20342,1665,1199,198,408,271,1,2833,315,17006,54809,38999,320,13435,323,10146,7354,568,698,2413,14738,82,2601,486,1712,19486,8,4035,262,1760,1141,1464,274,10763,4376,4302,11,2750,2601,58746,593,488,1760,1141,1464,274,10763,4376,4302,11,2750,2601,27520,22731,4390,2,12448,3714,3700,448,279,3468,825,3019,4815,279,22670,53923,4956,2,9043,7289,315,3019,27389,24609,13,576,3019,389,738,595,10469,1181,3950,389,279,3671,198,2,28654,13611,6458,0,63,448,279,22259,594,41799,8,7678,1119,279,14151,315,738,220,18,481,595,11,323,1119,198,2,1565,73225,58,18,481,595,60,63,304,3468,1448,5677,4938,13,2055,279,3468,646,7050,279,3019,429,59506,264,198,2,3950,1573,5290,432,25,1393,279,22670,8473,429,3019,11,279,3468,46936,369,279,3681,198,2,825,11,15804,1181,3950,11,12341,369,264,2936,3950,323,23045,432,13,576,22670,902,5021,877,642,198,2,1948,7354,382,30473,2036,50194,34656,76025,532,262,27389,486,6408,6061,90,17,11,8304,36219,76025,11248,262,38999,486,3781,90,32658,90,23780,11289,31291,727,84,11212,10216,11248,262,17846,486,44819,3781,90,1072,18,17,92,688,671,3468,1448,5677,25,17846,6732,60,374,279,3950,304,27389,6732,936,3365,198,262,17846,12848,486,3781,90,1072,18,17,532,262,2814,486,6408,6061,90,17,11289,84,1556,92,688,671,12433,1283,279,3019,389,1817,738,198,408,271,1688,16895,45187,2601,486,1712,19486,76025,5410,1380,314,51,532,262,435,57733,2049,4302,1369,470,435,57733,486,32564,34656,76025,532,262,17846,284,26462,1857,90,1072,18,17,11,16,11289,31291,29840,10642,25547,16135,11,220,17,340,262,1031,3848,284,320,8304,36219,2601,3192,11,435,20087,11,220,16,701,14822,36219,2601,3192,11,435,20087,11,220,16,1171,262,435,57733,284,50194,34656,76025,25547,5909,82,11,508,41212,11,4302,1125,17846,11,19860,38550,38192,11,17846,1326,9699,320,44819,1556,1507,26462,1556,12145,262,470,435,57733,198,408,271,2,19143,279,3950,315,1565,839,1199,63,1119,738,595,320,1199,14151,323,17846,9446,4292,13611,45514,10297,81,486,1712,19486,11,281,486,32564,34656,11,595,11,60788,8,4035,262,6077,6458,10297,81,3192,37187,11,281,948,20342,6732,936,3365,11,1651,1295,744,28812,11,595,57071,701,60788,11,435,514,34501,692,1688,1598,620,81079,1589,11946,10297,81,486,1712,19486,11,281,486,32564,34656,11,595,340,262,293,284,281,948,20342,6732,921,262,3019,368,284,320,6108,11946,10297,81,3192,11,435,20087,11,293,1215,6077,45514,10297,81,11,281,11,220,18,481,595,11,293,1665,1199,1171,262,421,281,10763,82,6732,60,2049,4302,198,286,451,20457,55,58462,9669,330,68,1409,3019,1,3019,741,286,281,10763,82,6732,60,284,451,20457,55,58462,9669,330,45070,3019,1,54809,1858,42251,3025,31291,60523,38436,1171,262,770,198,286,451,20457,55,58462,9669,330,265,1363,3019,1,54809,36452,1295,10763,82,6732,2546,262,835,198,262,3255,1295,31802,6732,2546,408,271,7129,262,6923,620,81079,1589,10297,41736,11,12981,11,14151,26,1932,5921,28838,11,2936,8077,11,389,6458,8,1464,4196,90,1072,630,83148,19366,0,80709,5957,1097,8,448,279,22259,594,41799,320,746,432,448,40518,9716,72812,0,80709,5957,1097,6965,51501,301,1589,773,429,279,3468,8473,825,3019,4815,279,22670,13,43140,264,22259,448,54809,38999,624,7129,1688,6923,620,81079,1589,10297,81,486,1712,19486,11,12981,486,14076,11,14151,486,15949,3781,90,27,25,3486,2440,6526,1932,5921,28838,486,3486,11,2936,8077,11,389,6458,284,4302,340,262,435,10763,82,1369,2510,7,9171,1454,445,51501,301,1589,47116,3880,54809,38999,5455,262,281,284,16895,45187,2601,340,262,7907,284,1333,19536,262,1932,5921,28838,861,220,15,1369,470,7907,198,262,60788,284,4637,10297,81,11,12981,11,14151,340,262,6077,45514,10297,81,11,281,11,220,16,11,60788,340,262,5527,284,26462,1556,741,262,3255,7,2307,8,503,671,279,1156,3950,11,304,738,220,16,198,262,595,284,220,16,999,671,279,738,6693,14151,3331,279,1790,3950,311,1349,198,262,1393,830,198,286,803,284,3084,3268,10543,8,488,220,16,366,1932,5921,28838,262,671,686,264,3950,1795,419,825,5267,286,421,803,2549,671,1598,279,3950,1573,14063,432,198,310,451,20457,55,58462,9669,330,6120,11127,1,10549,11946,10297,79,948,20342,6732,1125,435,3192,11,435,20087,11,12981,11,4302,340,310,1598,620,81079,1589,11946,10297,81,11,281,11,595,340,310,4484,10297,13262,59549,11,481,16,8,262,671,10199,304,3685,198,286,835,198,286,451,20457,55,58462,9669,330,11489,369,3950,1,63799,7,2307,340,286,877,284,1333,1295,744,28812,12848,6732,2546,286,803,1009,320,13262,59549,57208,60,284,877,340,286,421,877,304,2936,8077,198,310,421,803,1698,671,279,2936,3950,3937,1526,279,1614,25,5943,432,1549,198,394,63799,741,394,56772,10297,81,20087,11,12981,11,3084,34820,8,481,220,16,340,310,835,198,310,1438,198,286,835,198,286,4484,10297,16187,11,877,340,286,389,6458,2049,4302,1369,389,6458,3724,340,286,803,1369,1438,198,286,5527,11,595,284,281,31802,6732,1125,220,18,481,595,198,262,835,198,262,470,7907,198,408,198,151645,198,151644,77091,198,151667,271,151668,271],"name":"long-explain"}],"stop_ids":[151645,151643]} diff --git a/bench/ref/tileinfer_race.jl b/bench/ref/tileinfer_race.jl new file mode 100644 index 0000000..c8ffeaa --- /dev/null +++ b/bench/ref/tileinfer_race.jl @@ -0,0 +1,72 @@ +# TileInfer side of the end-to-end drag race; same workload and output as vllm_race.py. +# +# julia --project=bench bench/ref/tileinfer_race.jl [model] [prompt_len] [gen] [backend] [trials] [weights] [kv] +# +# `weights` and `kv` are bf16 (default) or int8 (`load_model(...; quantize = :int8)`, +# `PagedKVCache(...; quantize = :int8)`). +# +# Prefill = latency of generate(max_new_tokens = 1); decode tok/s = (gen - 1) / +# (latency(gen) - latency(1)). Each latency is the median over `trials` after a 1 s warm-up +# (timings are heavy-tailed); every trial is recorded, with the minimum-based numbers +# alongside. EOS is ignored. + +using TileInfer, CUDA, JSON + +median(v) = (s = sort(v); n = length(s); isodd(n) ? s[(n + 1) ÷ 2] : (s[n ÷ 2] + s[n ÷ 2 + 1]) / 2) + +model_name = get(ARGS, 1, "Qwen/Qwen3-0.6B") +prompt_len = parse(Int, get(ARGS, 2, "512")) +gen = parse(Int, get(ARGS, 3, "256")) +backend = get(ARGS, 4, "tile") == "ref" ? TileInfer.RefBackend() : TileInfer.TileBackend() +trials = parse(Int, get(ARGS, 5, "10")) +weights = get(ARGS, 6, "bf16") +kv = get(ARGS, 7, "bf16") +quant(s) = s == "int8" ? :int8 : (s == "bf16" ? nothing : error("unknown dtype $s")) + +model = TileInfer.load_model(model_name; backend, max_len = prompt_len + gen + 16, quantize = quant(weights)) +ids = [1000 + (7919 * i) % 140000 for i in 0:prompt_len-1] # same ids as vllm_race.py + +# One cache and runner for all trials, so decode graphs are captured once during warm-up +# (as vLLM does at startup) rather than inside every timed run. +cache = TileInfer.PagedKVCache(model; max_tokens = prompt_len + gen, quantize = quant(kv)) +runner = TileInfer.ModelRunner(model, cache) + +function latency(n) + function run() + seq = TileInfer.new_sequence(cache) + toks = TileInfer.generate!(runner, seq, ids; max_new_tokens = n, stop_ids = Int[]) + TileInfer.release!(cache, seq) + return toks + end + # Warm-up: compile, then keep the GPU busy for a second so its clock has ramped up + # (from idle, a 10 ms request runs at 900-1600 MHz and takes 2-3x longer). + t0 = time_ns() + run() + while time_ns() - t0 < 1e9 + run() + end + CUDA.synchronize() + times, toks = Float64[], Int[] + for _ in 1:trials + t = time_ns() + toks = run() + CUDA.synchronize() + push!(times, (time_ns() - t) / 1e9) + end + @assert length(toks) == n + return times, toks +end + +times1, _ = latency(1) +timesn, toks = latency(gen) +metrics(t1, tn, suffix = "") = Dict( + "prefill_ms" * suffix => 1e3 * t1, "prefill_tok_s" * suffix => prompt_len / t1, + "decode_ms_per_tok" * suffix => 1e3 * (tn - t1) / (gen - 1), "decode_tok_s" * suffix => (gen - 1) / (tn - t1), + "e2e_s" * suffix => tn) +res = merge(Dict( + "engine" => "tileinfer", "backend" => string(typeof(backend)), "graphs" => runner.graphs, "model" => model_name, + "dtype" => "bfloat16", "weights" => weights, "kv" => kv, "prompt_len" => prompt_len, "gen" => gen, "trials" => trials, "statistic" => "median", + "trials_prefill_s" => times1, "trials_e2e_s" => timesn, "first_tokens" => toks[1:min(16, end)]), + metrics(median(times1), median(timesn)), metrics(minimum(times1), minimum(timesn), "_min")) +JSON.print(stdout, res, 2) +println() diff --git a/bench/ref/tileinfer_spec.jl b/bench/ref/tileinfer_spec.jl new file mode 100644 index 0000000..894773b --- /dev/null +++ b/bench/ref/tileinfer_spec.jl @@ -0,0 +1,77 @@ +# TileInfer side of the speculative-decoding comparison; same workload and output as +# vllm_spec.py. Greedy replies of up to `gen` tokens (stopping at EOS) to the prompts of +# spec_prompts.json, with one configuration: +# +# julia --project=bench bench/ref/tileinfer_spec.jl model method k weights kv [gen] [trials] +# +# method: plain, ngram (NgramProposer, n-grams of 3 down to 1) or dflash (z-lab drafter +# for Qwen3-4B); weights and kv: bf16 or int8. Per prompt, after a 1 s warm-up (compiles, +# captures the graphs, ramps the GPU clock up): median latency of the reply and of a +# 1-token request over `trials`; decode tok/s = (n - 1) / (latency(n) - latency(1)), so +# the drafter's prefill, wherever an engine does it, counts once in either term. + +using TileInfer, CUDA, JSON +using TileInfer: DFlashProposer, NgramProposer, SpecStats, load_dflash + +median(v) = (s = sort(v); n = length(s); isodd(n) ? s[(n + 1) ÷ 2] : (s[n ÷ 2] + s[n ÷ 2 + 1]) / 2) +quant(s) = s == "int8" ? :int8 : (s == "bf16" ? nothing : error("unknown dtype $s")) + +model_name, method = ARGS[1], ARGS[2] +k = parse(Int, ARGS[3]) +weights, kv = ARGS[4], ARGS[5] +gen = parse(Int, get(ARGS, 6, "256")) +trials = parse(Int, get(ARGS, 7, "5")) + +spec = JSON.parsefile(joinpath(@__DIR__, "spec_prompts.json")) +stop_ids = Int.(spec["stop_ids"]) +prompts = [(p["name"], Int.(p["ids"])) for p in spec["prompts"]] +max_tokens = 256 * cld(maximum(length(last(p)) for p in prompts) + gen + 64, 256) + +model = TileInfer.load_model(model_name; backend = TileBackend(), max_len = max_tokens, quantize = quant(weights)) +cache = TileInfer.PagedKVCache(model; max_tokens, quantize = quant(kv)) +runner = TileInfer.ModelRunner(model, cache) +proposer = method == "plain" ? nothing : + method == "ngram" ? NgramProposer(; k) : + method == "dflash" ? DFlashProposer(load_dflash("z-lab/Qwen3-4B-DFlash-b16", model; max_len = max_tokens); k, max_tokens) : + error("unknown method $method") + +function run(ids, n) + seq = TileInfer.new_sequence(cache) + stats = SpecStats() + t = time_ns() + out = TileInfer.generate!(runner, seq, ids; max_new_tokens = n, stop_ids, speculative = proposer, spec_stats = stats) + CUDA.synchronize() + dt = (time_ns() - t) / 1e9 + TileInfer.release!(cache, seq) + return dt, out, stats +end + +results = [] +for (name, ids) in prompts + t0 = time_ns() + run(ids, gen); run(ids, 1) + while time_ns() - t0 < 1e9 + run(ids, 1) + end + tn = Float64[]; t1 = Float64[] + out, stats = Int[], SpecStats() + for _ in 1:trials + dt, out, stats = run(ids, gen) + push!(tn, dt) + push!(t1, run(ids, 1)[1]) + end + n = length(out) + r = Dict("prompt" => name, "prompt_len" => length(ids), "out" => n, + "e2e_s" => median(tn), "prefill_ms" => 1e3 * median(t1), + "decode_tok_s" => (n - 1) / (median(tn) - median(t1)), + "trials_e2e_s" => tn, "trials_prefill_s" => t1, "first_tokens" => out[1:min(16, end)]) + if proposer !== nothing + r["steps"] = stats.steps + r["tokens_per_step"] = n / stats.steps + end + push!(results, r) + println(stderr, rpad(name, 13), " out ", n, " decode ", round(r["decode_tok_s"], digits = 1), " tok/s") +end +JSON.print(stdout, Dict("engine" => "tileinfer", "model" => model_name, "method" => method, "k" => k, + "weights" => weights, "kv" => kv, "gen" => gen, "trials" => trials, "results" => results), 2) +println() diff --git a/bench/ref/vllm_race.py b/bench/ref/vllm_race.py new file mode 100644 index 0000000..82eb3ad --- /dev/null +++ b/bench/ref/vllm_race.py @@ -0,0 +1,97 @@ +"""vLLM side of the end-to-end drag race: single sequence, greedy, fixed lengths. + + bench/ref/.venv/bin/python bench/ref/vllm_race.py [--model Qwen/Qwen3-0.6B] + [--prompt-len 512] [--gen 256] [--trials 5] [--eager] [--out bench/results/vllm.json] + +Prefill time = latency of a request with max_tokens = 1 (prompt forward + 1 sample). +Decode tok/s = (gen - 1) / (latency(gen) - latency(1)). +Each latency is the median over `--trials` runs after a 1 s warm-up: the GPU also drives the +desktop, so timings are heavy-tailed and a few congested trials should not move the +result. Every trial is recorded, with the minimum-based numbers alongside. Prefix caching +is off so every trial re-prefills. +""" + +import argparse +import json +import os +import statistics +import time + +os.environ.setdefault("VLLM_CONFIGURE_LOGGING", "0") +os.environ.setdefault("HF_HUB_OFFLINE", "1") # every model is in the local cache +# No system CUDA toolkit: torch.compile finds nvcc in the pip-installed nvidia/cu13 package. +import nvidia # noqa: E402 + +_cu = os.path.join(nvidia.__path__[0], "cu13") +os.environ.setdefault("CUDA_HOME", _cu) +os.environ["PATH"] = os.path.join(_cu, "bin") + os.pathsep + os.environ["PATH"] +# FlashInfer's JIT sampler fails to build against that nvcc (CCCL header mismatch); greedy +# decoding does not need it. +os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0") + +from vllm import LLM, SamplingParams # noqa: E402 +from vllm.inputs import TokensPrompt # noqa: E402 + + +def main(): + p = argparse.ArgumentParser() + p.add_argument("--model", default="Qwen/Qwen3-0.6B") + p.add_argument("--dtype", default="bfloat16") + p.add_argument("--prompt-len", type=int, default=512) + p.add_argument("--gen", type=int, default=256) + p.add_argument("--trials", type=int, default=10) + p.add_argument("--eager", action="store_true", help="no CUDA graphs / torch.compile") + p.add_argument("--gpu-mem", type=float, default=0.6) + p.add_argument("--kv-cache-dtype", default="auto", help="e.g. int8_per_token_head") + p.add_argument("--out", default=None) + a = p.parse_args() + + llm = LLM(model=a.model, dtype=a.dtype, max_model_len=a.prompt_len + a.gen + 16, + max_num_seqs=1, enable_prefix_caching=False, enforce_eager=a.eager, + gpu_memory_utilization=a.gpu_mem, seed=0, + kv_cache_dtype=a.kv_cache_dtype) + # Deterministic ordinary-token prompt ids, same recipe as bench/ref/tileinfer_race.jl. + ids = [1000 + (7919 * i) % 140000 for i in range(a.prompt_len)] + prompt = TokensPrompt(prompt_token_ids=ids) + + def latency(n): + sp = SamplingParams(temperature=0.0, max_tokens=n, min_tokens=n, ignore_eos=True) + # Warm-up: keep the GPU busy for a second so its clock has ramped up (from idle, + # a 10 ms request runs at 900-1600 MHz and takes 2-3x longer). + t0 = time.perf_counter() + llm.generate([prompt], sp, use_tqdm=False) + while time.perf_counter() - t0 < 1.0: + llm.generate([prompt], sp, use_tqdm=False) + times = [] + for _ in range(a.trials): + t = time.perf_counter() + out = llm.generate([prompt], sp, use_tqdm=False) + times.append(time.perf_counter() - t) + assert len(out[0].outputs[0].token_ids) == n + return times, list(out[0].outputs[0].token_ids) + + times1, _ = latency(1) + timesn, toks = latency(a.gen) + + def metrics(t1, tn, suffix=""): + return { + "prefill_ms" + suffix: 1e3 * t1, "prefill_tok_s" + suffix: a.prompt_len / t1, + "decode_ms_per_tok" + suffix: 1e3 * (tn - t1) / (a.gen - 1), + "decode_tok_s" + suffix: (a.gen - 1) / (tn - t1), "e2e_s" + suffix: tn, + } + + res = { + "engine": "vllm", "eager": a.eager, "kv_cache_dtype": a.kv_cache_dtype, "model": a.model, "dtype": a.dtype, + "prompt_len": a.prompt_len, "gen": a.gen, "trials": a.trials, "statistic": "median", + **metrics(statistics.median(times1), statistics.median(timesn)), + **metrics(min(times1), min(timesn), "_min"), + "trials_prefill_s": times1, "trials_e2e_s": timesn, "first_tokens": toks[:16], + } + print(json.dumps(res, indent=2)) + if a.out: + with open(a.out, "w") as f: + json.dump(res, f, indent=2) + + +if __name__ == "__main__": + main() diff --git a/bench/ref/vllm_spec.py b/bench/ref/vllm_spec.py new file mode 100644 index 0000000..26192b6 --- /dev/null +++ b/bench/ref/vllm_spec.py @@ -0,0 +1,111 @@ +"""vLLM side of the speculative-decoding comparison; same workload, metric and output as +tileinfer_spec.jl (greedy replies of up to `gen` tokens, stopping at EOS, to the prompts of +spec_prompts.json). + + bench/ref/.venv/bin/python bench/ref/vllm_spec.py MODEL METHOD K WEIGHTS KV [--gen 256] [--trials 5] + +METHOD: plain, ngram (prompt lookup, n-grams of 3 down to 1) or dflash +(z-lab/Qwen3-4B-DFlash-b16); WEIGHTS int8 runs the W8A16 copy from make_w8a16.py; KV int8 +is kv_cache_dtype = int8_per_token_head. Prefix caching is off. +""" + +import argparse +import json +import os +import statistics +import sys +import time + +os.environ.setdefault("VLLM_CONFIGURE_LOGGING", "0") +os.environ.setdefault("HF_HUB_OFFLINE", "1") # every model is in the local cache +import nvidia # noqa: E402 + +_cu = os.path.join(nvidia.__path__[0], "cu13") +os.environ.setdefault("CUDA_HOME", _cu) +os.environ["PATH"] = os.path.join(_cu, "bin") + os.pathsep + os.environ["PATH"] +os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0") + +from vllm import LLM, SamplingParams # noqa: E402 +from vllm.inputs import TokensPrompt # noqa: E402 + +HERE = os.path.dirname(os.path.abspath(__file__)) + + +def spec_counters(llm): + """Cumulative (verify steps with drafts, accepted drafts) from vLLM's metrics.""" + drafts = accepted = 0 + for m in llm.get_metrics(): + if m.name == "vllm:spec_decode_num_drafts": + drafts += m.value + elif m.name == "vllm:spec_decode_num_accepted_tokens": + accepted += m.value + return drafts, accepted + + +def main(): + p = argparse.ArgumentParser() + p.add_argument("model") + p.add_argument("method", choices=["plain", "ngram", "dflash"]) + p.add_argument("k", type=int) + p.add_argument("weights", choices=["bf16", "int8"]) + p.add_argument("kv", choices=["bf16", "int8"]) + p.add_argument("--gen", type=int, default=256) + p.add_argument("--trials", type=int, default=5) + p.add_argument("--gpu-mem", type=float, default=0.75) + a = p.parse_args() + + with open(os.path.join(HERE, "spec_prompts.json")) as f: + spec = json.load(f) + max_tokens = 256 * -(-(max(len(x["ids"]) for x in spec["prompts"]) + a.gen + 64) // 256) + model = a.model if a.weights == "bf16" else os.path.join(HERE, "models", a.model.split("/")[-1] + "-w8a16") + speculative = None + if a.method == "ngram": + speculative = {"method": "ngram", "num_speculative_tokens": a.k, + "prompt_lookup_max": 3, "prompt_lookup_min": 1} + elif a.method == "dflash": + speculative = {"method": "dflash", "model": "z-lab/Qwen3-4B-DFlash-b16", "num_speculative_tokens": a.k} + llm = LLM(model=model, dtype="bfloat16", max_model_len=max_tokens, max_num_seqs=1, + enable_prefix_caching=False, gpu_memory_utilization=a.gpu_mem, seed=0, + kv_cache_dtype="int8_per_token_head" if a.kv == "int8" else "auto", + speculative_config=speculative, disable_log_stats=False) + + def run(ids, n): + sp = SamplingParams(temperature=0.0, max_tokens=n, stop_token_ids=spec["stop_ids"]) + t = time.perf_counter() + out = llm.generate([TokensPrompt(prompt_token_ids=ids)], sp, use_tqdm=False) + return time.perf_counter() - t, list(out[0].outputs[0].token_ids) + + results = [] + for pr in spec["prompts"]: + ids = pr["ids"] + t0 = time.perf_counter() + run(ids, a.gen) + run(ids, 1) + while time.perf_counter() - t0 < 1.0: + run(ids, 1) + tn, t1 = [], [] + for _ in range(a.trials): + before = spec_counters(llm) + dt, out = run(ids, a.gen) + after = spec_counters(llm) + tn.append(dt) + t1.append(run(ids, 1)[0]) + # vLLM's output excludes the stop token, like TileInfer's. + out = [t for t in out if t not in spec["stop_ids"]] + n = len(out) + e2e, pre = statistics.median(tn), statistics.median(t1) + r = {"prompt": pr["name"], "prompt_len": len(ids), "out": n, "e2e_s": e2e, "prefill_ms": 1e3 * pre, + "decode_tok_s": (n - 1) / (e2e - pre), "trials_e2e_s": tn, "trials_prefill_s": t1, + "first_tokens": out[:16]} + if speculative is not None: + steps = after[0] - before[0] + r["steps"] = steps + r["tokens_per_step"] = n / steps if steps else None + results.append(r) + print(f"{pr['name']:13s} out {n} decode {r['decode_tok_s']:.1f} tok/s", file=sys.stderr, flush=True) + print(json.dumps({"engine": "vllm", "model": a.model, "method": a.method, "k": a.k, "weights": a.weights, + "kv": a.kv, "gen": a.gen, "trials": a.trials, "results": results}, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/docs/src/performance.md b/docs/src/performance.md index 05cdd55..4f0e43f 100644 --- a/docs/src/performance.md +++ b/docs/src/performance.md @@ -17,10 +17,13 @@ with the reason, so they are not retried blindly. gaps between steps disappearing; `_sampled` uses the model's recommended sampling (Qwen3: temperature 0.6, top-k 20, top-p 0.95), which is what `tileinfer run`/`chat` do. - `model/prefill{64,512}/`: a 64- or 512-token prompt in one step. -- **End-to-end race** (`bench/ref/tileinfer_race.jl`, `bench/ref/vllm_race.py`): 512-token - prompt, 256 greedy tokens, prefill = latency of generating 1 token, decode = - (256 − 1) / (latency(256) − latency(1)). Same prompt ids and the same first tokens on both - engines. +- **End-to-end race** (`bench/ref/tileinfer_race.jl`, `bench/ref/vllm_race.py`, alternated by + `bench/ref/alternate.py`): 512-token prompt, 256 greedy tokens, prefill = latency of + generating 1 token, decode = (256 − 1) / (latency(256) − latency(1)), medians over trials + after a 1 s warm-up. Same prompt ids and the same first tokens on both engines. vLLM runs + from `bench/ref/.venv` (pinned in `bench/ref/requirements.txt`); `bench/ref/run_all.sh` + reruns the whole comparison into `bench/ref/results//`, which is not tracked (setup in + `bench/ref/README.md`). - **Kernel breakdowns**: `CUDA.@profile trace = true` over 20 generated tokens, summing kernel durations per name (the tracer adds ~5 % to wall time). Since 2026-10-29 `bench/breakdown.jl` does this for decode and prefill steps of both models, per kernel role. @@ -59,8 +62,9 @@ History on Qwen3-0.6B: | GEMM occupancy | 2.46 ms (sampled) | 407 | 8.8 ms | 58k | two GEMM blocks per SM on large grids (4B prefill 512: 1.06×) | | M7 (speculative decoding) | 2.49 ms (sampled) | 402 | 8.85 ms | 58k | plain decoding unchanged (re-measured); n-gram, draft-model, EAGLE-3, DFlash proposers and p/q verification on top | -From M3: decode 15.7× faster, prefill 8.5×. Race: **418 tok/s decode, 53k tok/s prefill**, -3.6 % faster end to end than vLLM on the same machine (see the end). +From M3: decode 15.7× faster, prefill 8.5×. Race against vLLM on the same machine +(2026-11-01, see "Comparison with vLLM"): **3.3 % faster end to end** on Qwen3-0.6B +(416 vs 402 tok/s decode, 9.7 vs 10.1 ms for a 512-token prefill), a tie on Qwen3-4B. ## M4: cuTile kernels (2026-10-27) @@ -161,45 +165,103 @@ Prefill GEMM tiling for few tokens, and two ideas that did not pay on the 4080S: ## Comparison with vLLM (same machine, `bench/ref`) -`bench/ref/alternate.py`, 2026-10-28: 3 rounds alternating the engines (ABBA order), each a -fresh process recording 10 trials of each latency after a warm-up; 30 trials per engine -pooled. 512-token prompt, 256 greedy tokens, the same first tokens on both engines. Medians -are the primary statistic (timings are heavy-tailed), with the interquartile range. +Setup of every run below (2026-11-01): RTX 4080 SUPER, which also drove the desktop +(compositor, VS Code and Discord on the GPU); TileInfer at commit 8528c2e on Julia 1.13.3; +vLLM 0.31.0 with torch 2.13.0 (`bench/ref/requirements.txt`) with CUDA graphs and +torch.compile; BF16 unless noted, prefix caching off and one sequence at a time. -| Median [q1, q3] | vLLM 0.31 (CUDA graphs + torch.compile) | TileInfer perf branch | | -|---|---|---|---| -| **End to end** (latency of 256 tokens) | **0.6432 s** [0.6428, 0.6437] | **0.6200 s** [0.6196, 0.6202] | **3.6 % faster** | -| 1-token request ("prefill") | 25.4 ms [24.7, 41.5] | 9.77 ms [9.74, 10.05] | | -| Decode = (e2e − 1-token) / 255 | 2.42 ms/tok (413 tok/s) | 2.39 ms/tok (418 tok/s) | | - -End to end is the robust comparison. vLLM's 1-token latency is multimodal, with clusters at -~11, ~25 and ~40–47 ms within the same process (sorted trials of one run: 10.8, 11.0, 11.1, -11.1, 11.5, 28.4, 46.8, 47.2, 47.5, 47.9 ms), while its 256-token latency varies by under -1 ms. So the extra 15–35 ms are per-request overhead that the 256-token request does not pay -in full, not prefill compute. Its fast mode (~11 ms) is the best estimate of vLLM's prefill, -so the subtraction above overstates its decode speed: with 11 ms, vLLM decodes at 2.48 ms/tok -(403 tok/s), as in the earlier 10-trial runs that hit the fast mode. TileInfer's timings are -unimodal (prefill IQR 0.3 ms). - -Earlier single runs: vLLM `--eager` 172 tok/s decode / 39k tok/s prefill; TileInfer M6 -343 tok/s / 40k tok/s (e2e 0.755 s). - -### Qwen3-4B (2026-10-28) - -Same protocol (`alternate.py --model Qwen/Qwen3-4B`, 30 trials per engine), the first run of -TileInfer on this model: no kernel changes, and the same first tokens as vLLM. +`bench/ref/alternate.py`: 3 rounds alternating the engines +(ABBA order), each a fresh process that warms up for 1 s, then records 10 trials of each +latency; 30 trials per engine pooled. 512-token prompt, 256 greedy tokens, the same first +tokens on both engines. Medians are the primary statistic (timings are heavy-tailed), with +the interquartile range. -| Median [q1, q3] | vLLM 0.31 | TileInfer perf branch | | -|---|---|---|---| -| **End to end** (latency of 256 tokens) | **3.3013 s** [3.3008, 3.3019] | **3.3062 s** [3.3061, 3.3068] | 0.15 % slower | -| 1-token request ("prefill") | 48.0 ms [46.7, 50.4] | 53.2 ms [49.7, 57.8] | ≈ 10 % slower | -| Decode = (e2e − 1-token) / 255 | 12.76 ms/tok (78.4 tok/s) | 12.76 ms/tok (78.4 tok/s) | tie | - -At 4B both engines decode at ~87 % of the bandwidth roofline (8.1 GB of weights and KV per -token ≈ 11.1 ms, 90 tok/s): the per-kernel overheads that separated them at 0.6B are small -next to 220 MB of weights per layer. Prefill is compute-bound here, where TileInfer's GEMM -is the gap (0.87–0.92× cuBLAS at n = 512, measured in "Two models" below); its prefill also -has a wider spread (one run at 58 ms). +| Median [q1, q3] | Qwen3-0.6B: vLLM | Qwen3-0.6B: TileInfer | Qwen3-4B: vLLM | Qwen3-4B: TileInfer | +|---|---|---|---|---| +| **End to end** (latency of 256 tokens) | **0.6439 s** [0.6419, 0.6476] | **0.6227 s** [0.6203, 0.6263] | **3.328 s** [3.296, 3.350] | **3.309 s** [3.300, 3.318] | +| 1-token request ("prefill") | 10.1 ms [9.9, 10.3] | 9.7 ms [9.6, 12.8] | 46.6 ms [45.5, 46.8] | 47.0 ms [45.4, 49.0] | +| Decode = (e2e − 1-token) / 255 | 2.49 ms/tok (402 tok/s) | 2.40 ms/tok (416 tok/s) | 12.87 ms/tok (77.7 tok/s) | 12.79 ms/tok (78.2 tok/s) | + +On 0.6B TileInfer is **3.3 % faster end to end** (3.6 % on 2026-10-28), from fewer, fused +kernels per step. On 4B the engines tie: TileInfer's median is 0.6 % lower, but vLLM's +fastest round matches it (minimum 3.295 s vs 3.299 s), and both decode at ~87 % of the +bandwidth roofline (8.1 GB of weights and KV per token ≈ 11.1 ms, 90 tok/s), where the +per-kernel overheads that separate them at 0.6B are small next to 220 MB of weights per +layer. The 4B prefill gap of 2026-10-28 (53.2 vs 48.0 ms, ≈ 10 %, from GEMMs at 0.87–0.92× +cuBLAS) is closed, by the GEMM occupancy change and the per-shape tiles since. + +**Warm the GPU before timing short requests.** Until 2026-10-31 the race warmed up with a +single request. The GPU then runs the first ~0.2 s at 900–1,600 MHz instead of 2,775 MHz, +so a 10 ms request took 16–40 ms; the 256-token request lasts long enough to ramp the +clock and was not affected. That is what the 2026-10-28 run took for vLLM per-request +overhead (1-token clusters at ~11, ~25 and ~45 ms); with the 1 s warm-up its 1-token +latency is unimodal. On 0.6B the same change moved TileInfer's 1-token median from 27.8 to +9.7 ms and vLLM's from 31.8 to 10.1 ms (the same race, +run before the change). + +TileInfer has 1–3 slow 1-token trials per process (20–70 ms, and one of 200–250 ms in +every run, on both models), which widen its q3; vLLM has none. A traced repeat showed one +such trial spending 31 ms in GC and 37 ms compiling, so they are host-side pauses in Julia, +not GPU time. + +Earlier runs (2026-10-28, single warm-up request): 0.6B e2e 0.6200 s vs vLLM 0.6432 s, +4B 3.3062 s vs 3.3013 s, prefill 53.2 vs 48.0 ms. Single runs before that: vLLM `--eager` +172 tok/s decode / 39k tok/s prefill; TileInfer M6 343 tok/s / 40k tok/s (e2e 0.755 s). + +### With INT8 and speculative decoding (2026-11-01) + +**INT8.** TileInfer's `quantize = :int8` against the same quantization in vLLM: a W8A16 +compressed-tensors copy of each checkpoint (`bench/ref/make_w8a16.py`: TileInfer's per-channel +scales `max |W| / 127`, every linear and the untied `lm_head`; the embedding stays in BF16), +which vLLM runs with its Marlin kernels. INT8 KV is TileInfer's `Int8Pages` against vLLM's +`kv_cache_dtype = int8_per_token_head`, which moves vLLM to its Triton attention backend. +Same race (`alternate.py --weights int8 --kv int8`), e2e medians over 30 trials per engine: + +| Latency of 256 tokens | 0.6B vLLM | 0.6B TileInfer | 4B vLLM | 4B TileInfer | +|---|---|---|---|---| +| BF16 (above) | 0.644 s | **0.623 s** (−3.3 %) | 3.328 s | 3.309 s (tie) | +| INT8 weights | 0.532 s | **0.503 s** (−5.5 %) | 1.880 s | 1.884 s (tie) | +| INT8 KV | 0.622 s | 0.625 s (tie) | **3.264 s** | 3.307 s (+1.3 %) | +| INT8 weights + KV | 0.474 s | 0.470 s (tie) | **1.837 s** | 1.871 s (+1.8 %) | + +Decode with both: 553 vs 555 tok/s on 0.6B, 143 vs 140 tok/s on 4B. vLLM gains more from +INT8 KV than the KV bytes explain (0.6B: −11 % against TileInfer's −6.6 %), probably from the +backend switch; not profiled. With INT8 weights the first tokens can differ between the +engines (vLLM stores the scales in BF16, TileInfer in Float32). + +**Speculative decoding, best configuration per engine.** `bench/ref/tileinfer_spec.jl` and +`bench/ref/vllm_spec.py` on `bench/speculative.jl`'s six chat prompts (token ids exported by +`bench/ref/spec_prompts.jl`, so both engines get the same tokens), greedy, up to 256 tokens +stopping at EOS, median of 5 trials after a 1 s warm-up; decode = (n − 1) / (latency(n) − +latency(1)). Each engine ran plain, DFlash k = 7 and k = 15 (4B), n-gram k = 4 (0.6B), each in +BF16 and with INT8 weights + KV; the table keeps each engine's fastest per prompt. On 4B +it is DFlash k = 15 with INT8 for both engines, except TileInfer's k = 7 on long-explain. + +| Qwen3-4B | vLLM tok/s (× its BF16 plain) | TileInfer tok/s (× its BF16 plain) | TileInfer / vLLM | tokens per step vLLM / TileInfer | +|---|---|---|---|---| +| rename | 1,150 (14.7×) | 947 (12.2×) | 0.82 | 11.0 / 10.0 | +| document | 385 (4.9×) | 379 (4.9×) | 0.98 | 3.9 / 4.0 | +| explain | 322 (4.1×) | 290 (3.7×) | 0.90 | 3.2 / 3.0 | +| story | 255 (3.2×) | 219 (2.8×) | 0.86 | 2.5 / 2.3 | +| long-edit (2.2k) | 494 (6.5×) | **698 (9.2×)** | **1.41** | 8.0 / 8.3 | +| long-explain (2.2k) | 158 (2.1×) | **270 (3.5×)** | **1.70** | 2.6 / 3.0 | + +Acceptance is about the same on both engines, so the differences are step costs. On short +prompts vLLM's DFlash steps are cheaper: in BF16 on rename both take 10 steps for 110 tokens, +at 731 vs 558 tok/s (TileInfer's step is ~3.2 ms drafting + 13.3 ms verifying 16 tokens, see +"DFlash drafting"), and its plain INT8 decode is ~4 % faster at these short contexts (145 vs +139 tok/s; a tie at 768 positions in the race). At 2.2k positions vLLM's DFlash gains little +(long-explain: 158 tok/s against 134 plain), while TileInfer's keeps its speedup; where vLLM +loses that time is not profiled. + +On Qwen3-0.6B (no DFlash drafter) the comparison is noisier: with INT8, greedy replies differ +in length between the engines on two prompts, and TileInfer's reply to long-edit ends after +5 tokens. Where the replies match: n-gram helps TileInfer most on copying (rename: 1,725 vs +1,236 tok/s, n-gram + INT8 on both), vLLM's plain INT8 decode is 7 % faster at short contexts +(606 vs 563 tok/s on explain), and on long-explain TileInfer's n-gram + INT8 reaches 588 tok/s +against vLLM's best of 469 (plain INT8). vLLM's n-gram slows open text down (story, BF16: 298 +tok/s against 405 plain), TileInfer's is neutral there (413 vs 428). vLLM counts only the steps +that had drafts, so its n-gram tokens per step are not comparable and are left out. ## Two models in the benchmark suite (2026-10-29) @@ -259,7 +321,7 @@ halves them). Attention is latency-bound at 38 % of DRAM for both (one page per - **At n = 512 every GEMM is behind cuBLAS** (82–105 TFLOP/s for cuBLAS on 4B vs 72–96 for ours). On 4B the four GEMMs are 1,188 µs per layer, 42.8 ms of the 47.6 ms prefill; at - cuBLAS speed they would be 37.8 ms, which is the ~10 % prefill gap to vLLM in the race. + cuBLAS speed they would be 37.8 ms, which was the ~10 % prefill gap to vLLM in the 2026-10-28 race. - **0.6B down at n = 512 (0.77×)**: `gemm_config` picks 64 × 128 tiles, i.e. 64 blocks for 80 SMs, each looping over K = 3,072. An under-filled GPU with a long K loop is the case where split-K (or stream-K) pays, unlike the n ≤ 64 shapes where split-K lost (see "Per-shape GEMM tiles"). From 34450eac4701e1f3003e3f6f3384b4a1c737509d Mon Sep 17 00:00:00 2001 From: Antoine Buttier Date: Sun, 1 Nov 2026 19:00:26 +0100 Subject: [PATCH 2/3] Docs: performance page by feature instead of a dated log - One section per feature (decode step, device sampling, prefill GEMMs, verify attention, INT8 weights, INT8 KV cache, speculative decoding), each with its results, the findings no table shows, and the variants not kept. - No dates, branch names or milestone history (the roadmap has it); explanations already in the architecture, KV cache, attention, speculative and cuTile pages are linked instead of repeated. - The vLLM comparison at the end, followed by one table of what is left to gain. - Summary, step breakdowns, prefill GEMMs vs cuBLAS and INT8 prefill re-measured. - Page renamed "Results by feature"; links and headline numbers updated. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 2 +- docs/make.jl | 4 +- docs/src/index.md | 8 +- docs/src/performance.md | 1117 +++++++++++++-------------------------- docs/src/roadmap.md | 12 +- docs/src/speculative.md | 6 +- 6 files changed, 382 insertions(+), 767 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index c657ea1..55d79cf 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -29,7 +29,7 @@ julia --project=docs docs/make.jl # documentation site into d ``` Profiling workflow, model-step costs and how to read the summary: [docs/src/profiling.md](docs/src/profiling.md). -What each milestone and optimization gained, including what did not pan out: [docs/src/performance.md](docs/src/performance.md). +What each feature gains, what did not pan out, and what is left to gain: [docs/src/performance.md](docs/src/performance.md). To tune a kernel, profile it before and after a change and read `ncu_summary.py --compare` rather than raw `ncu` output (`ncu` is in /usr/local/NVIDIA-Nsight-Compute). Take timings from bench/run.jl: `ncu` serializes kernels and locks clocks. diff --git a/docs/make.jl b/docs/make.jl index 5119c6f..6dcdcd2 100644 --- a/docs/make.jl +++ b/docs/make.jl @@ -15,7 +15,7 @@ makedocs(; prettyurls = get(ENV, "CI", nothing) == "true", canonical = "https://antoinebut.github.io/TileInfer.jl", edit_link = "main", - size_threshold_warn = 200 * 1024, # the performance log is a long page + size_threshold_warn = 200 * 1024, # the performance page is long size_threshold = 400 * 1024, ), pages = [ @@ -29,7 +29,7 @@ makedocs(; ], "History and roadmap" => "roadmap.md", "Performance" => [ - "Performance log" => "performance.md", + "Results by feature" => "performance.md", "Profiling" => "profiling.md", "cuTile design choices" => "cutile_design.md", ], diff --git a/docs/src/index.md b/docs/src/index.md index 8f05738..24f92a9 100644 --- a/docs/src/index.md +++ b/docs/src/index.md @@ -27,9 +27,9 @@ Julia. - **Tooling**: a `tileinfer` command line, per-op and end-to-end benchmarks, and Nsight Compute profiling scripts. -On Qwen3-4B, decode runs at 77 tok/s (86 % of the memory-bandwidth roofline) and prefill -at 11k tok/s. The [Performance log](performance.md) has the numbers for each step, including -the optimizations that did not pan out. +On Qwen3-4B, decode runs at 79 tok/s (88 % of the memory-bandwidth roofline) and prefill +at 11k tok/s. [Results by feature](performance.md) has the numbers for each feature, including +the variants that did not pan out. ## Where to go next @@ -40,7 +40,7 @@ the optimizations that did not pan out. their own. - [History and roadmap](roadmap.md): where the project stands, the milestones that got it there, and what comes next. -- [Performance log](performance.md), [Profiling](profiling.md) and +- [Results by feature](performance.md), [Profiling](profiling.md) and [cuTile design choices](cutile_design.md): what each optimization gained, how kernels are measured, and the codegen rules learned along the way. - [Public API](api.md) and [Internals](internals.md): docstrings for the code itself. diff --git a/docs/src/performance.md b/docs/src/performance.md index 4f0e43f..5cab120 100644 --- a/docs/src/performance.md +++ b/docs/src/performance.md @@ -1,852 +1,467 @@ -# Performance log - -What each milestone and each optimization bought, in BF16 on the RTX 4080 SUPER (736 GB/s): -on Qwen3-0.6B up to the per-shape GEMM tiles, and on both Qwen3-0.6B and Qwen3-4B from then on (see "Two -models"). Newest last. Numbers that informed a decision but did not pan out are kept, -with the reason, so they are not retried blindly. - -## How things are measured - -- **`bench/run.jl`** (see CLAUDE.md), minimum time over samples, `--seconds 2` for - decisions; expect ±3–5 % between runs at the model level (the GPU also drives the desktop). - Keys start with the model (`Qwen3-4B/model/...`) since 2026-10-29; earlier keys were 0.6B. - - `model/decode_ctx1024/`: one eager decode step after 1,023 cached positions, synced. - - `model/decode_graph_ctx1024/tile`: the same step replayed from a CUDA graph (M6+), synced. - - `model/generate64[_unpipelined|_sampled]_ctx1024/tile`: 64 tokens after 1,023 positions, - per token (perf branch). Greedy pipelined overlaps host and GPU, so only it shows the - gaps between steps disappearing; `_sampled` uses the model's recommended sampling - (Qwen3: temperature 0.6, top-k 20, top-p 0.95), which is what `tileinfer run`/`chat` do. - - `model/prefill{64,512}/`: a 64- or 512-token prompt in one step. -- **End-to-end race** (`bench/ref/tileinfer_race.jl`, `bench/ref/vllm_race.py`, alternated by - `bench/ref/alternate.py`): 512-token prompt, 256 greedy tokens, prefill = latency of - generating 1 token, decode = (256 − 1) / (latency(256) − latency(1)), medians over trials - after a 1 s warm-up. Same prompt ids and the same first tokens on both engines. vLLM runs - from `bench/ref/.venv` (pinned in `bench/ref/requirements.txt`); `bench/ref/run_all.sh` - reruns the whole comparison into `bench/ref/results//`, which is not tracked (setup in - `bench/ref/README.md`). -- **Kernel breakdowns**: `CUDA.@profile trace = true` over 20 generated tokens, summing - kernel durations per name (the tracer adds ~5 % to wall time). Since 2026-10-29 - `bench/breakdown.jl` does this for decode and prefill steps of both models, per kernel role. -- **Roofline for decode at 1,024 positions**: Qwen3-0.6B reads 1.19 GB of weights + 117 MB - of KV cache per token ≈ 1.78 ms, i.e. ~560 tok/s; Qwen3-4B 8.04 GB + 151 MB ≈ 11.1 ms, - ~90 tok/s. +# Performance + +What each feature of the engine gains, measured on the RTX 4080 SUPER (736 GB/s), in +BFloat16 unless noted, on Qwen3-0.6B and Qwen3-4B. How the features work is described in +[Architecture](architecture.md), [KV cache](kv_cache.md), [Attention kernels](attention.md) +and [Speculative decoding](speculative.md); the order they were built in is in +[History and roadmap](roadmap.md). Variants that were measured and not kept are listed +under each feature, with the measurement, so they are not retried blindly. What is left to +gain is collected at the end. + +## How it is measured + +- **`bench/run.jl`** (see CLAUDE.md): minimum time over samples, `--seconds 2`; expect + ±3–5 % between runs at the model level (the GPU also drives the desktop). Model benchmarks: + - `decode_ctx1024` / `decode_graph_ctx1024`: one decode step after 1,023 cached positions, + eager or replayed from a CUDA graph, synchronized; + - `generate64[_unpipelined|_sampled]_ctx1024`: 64 tokens after 1,023 positions, per token; + pipelined greedy, greedy step by step, and the model's recommended sampling (Qwen3: + temperature 0.6, top-k 20, top-p 0.95), pipelined; + - `prefill64`, `prefill512`: a prompt in one step. + The % of roofline counts every weight array once, the embedding table included. +- **`bench/breakdown.jl`**: GPU time per kernel inside real steps (decode replayed from + graphs), by role (see [Profiling](profiling.md)). +- **`bench/speculative.jl`**: 256-token chat replies to fixed prompts; decode tok/s from the + first new token to the last; best of 3. +- **The vLLM race** (`bench/ref/`, see its README): fresh processes alternating the two + engines, medians of every trial after a 1 s warm-up. Without the warm-up, the GPU runs the + first ~0.2 s at 900–1,600 MHz instead of 2,775 MHz, and a 10 ms request takes 16–40 ms. +- **Decode roofline at 1,024 positions**: Qwen3-0.6B reads 1.19 GB of weights + 117 MB of + KV cache per token, 1.78 ms (~560 tok/s); Qwen3-4B 8.04 GB + 151 MB, 11.1 ms (~90 tok/s). ## Summary -Current, both models (2026-10-30, e765381, `bench/run.jl --filter /model/ --seconds 2`, -baseline `summary-2026-10-30`; decode after 1,023 cached positions, per token of 64): +`bench/run.jl --seconds 2`, decode after 1,023 cached positions, per token of 64: | | Qwen3-0.6B | Qwen3-4B | |---|---|---| -| Decode, greedy pipelined | 2.53 ms, **395 tok/s** (70 % of roofline) | 12.97 ms, **77.1 tok/s** (86 %) | -| Decode, sampled (Qwen3 defaults, pipelined) | 2.49 ms, 402 tok/s | 12.86 ms, 77.8 tok/s | -| Decode, greedy step by step / eager step | 2.58 / 2.72 ms | 13.11 / 13.15 ms | -| Prefill 64 tokens | 2.75 ms, 23k tok/s | 14.6 ms, 4.4k tok/s | -| Prefill 512 tokens | 8.85 ms, **58k tok/s** (69 TFLOP/s) | 45.3 ms, **11.3k tok/s** (91 TFLOP/s) | -| Speculative decoding, best proposer (4B: DFlash k = 15, sampled) | — | 1.8× (story) to 3.2× (document) on open prompts, 8.4× on a code rename: 140–660 tok/s | +| Decode, greedy pipelined | 2.44 ms, **409 tok/s** (73 % of roofline) | 12.70 ms, **78.7 tok/s** (88 %) | +| Decode, sampled, pipelined | 2.45 ms, 408 tok/s | 12.72 ms, 78.6 tok/s | +| Decode, greedy step by step / graph step / eager step | 2.57 / 2.51 / 2.77 ms | 12.82 / 12.77 / 13.06 ms | +| Prefill 64 tokens | 2.73 ms, 23k tok/s | 14.5 ms, 4.4k tok/s | +| Prefill 512 tokens | 8.82 ms, **58k tok/s** (69 TFLOP/s) | 45.0 ms, **11.4k tok/s** (91 TFLOP/s) | +| Decode, INT8 weights | 1.85 ms, **542 tok/s** | 7.21 ms, **139 tok/s** | +| Prefill 64 / 512, INT8 weights | 2.49 / 8.69 ms (26k / 59k tok/s) | 9.49 / 46.1 ms (6.7k / 11.1k tok/s) | +| Speculative decoding (DFlash, k = 15, greedy) | — | 1.9× to 3.0× on open prompts, 8.5× on a code edit | -0.6B greedy decode reads 2–3 % slower than the 2.44 ms of 2026-10-29, within the run-to-run -spread (the sampled run, the same kernels plus sampling, measured 2.49 ms). The M8 target -(≥ 80 % of the decode roofline) holds on 4B, not on 0.6B. +Against vLLM 0.31 on the same machine: 3.3 % faster end to end on Qwen3-0.6B, a tie on +Qwen3-4B (see [the comparison](#Comparison-with-vLLM)). -History on Qwen3-0.6B: +## Where the time goes -| Stage | Decode step | Decode tok/s | Prefill 512 | Prefill tok/s | What changed | -|---|---|---|---|---|---| -| M3 (reference ops, paged KV) | 38.89 ms | 26 | 76.3 ms | 6.7k | cuBLAS + broadcasts | -| M4 (cuTile kernels, reference attention) | 34.77 ms | 29 | 54.0 ms | 9.5k | norm, rope, kv_write, silu, embed, GEMV, GEMM | -| M5 (paged flash-attention) | 3.80 ms | 263 | 16.0 ms | 32k | prefill FA-2, split-KV decode | -| M6 (CUDA graphs) | 2.87 ms (graph) | 348 | 11.8 ms | 43k | allocation-free step, graph replay | -| perf branch | 2.47 ms (pipelined) | 405 | 9.0 ms | 57k | fusions, device greedy sampling, host/GPU overlap | -| device sampling | 2.46 ms (sampled) | 407 | 9.0 ms | 57k | top-k/top-p sampling in the graph: sampled decode as fast as greedy | -| GEMM occupancy | 2.46 ms (sampled) | 407 | 8.8 ms | 58k | two GEMM blocks per SM on large grids (4B prefill 512: 1.06×) | -| M7 (speculative decoding) | 2.49 ms (sampled) | 402 | 8.85 ms | 58k | plain decoding unchanged (re-measured); n-gram, draft-model, EAGLE-3, DFlash proposers and p/q verification on top | - -From M3: decode 15.7× faster, prefill 8.5×. Race against vLLM on the same machine -(2026-11-01, see "Comparison with vLLM"): **3.3 % faster end to end** on Qwen3-0.6B -(416 vs 402 tok/s decode, 9.7 vs 10.1 ms for a 512-token prefill), a tie on Qwen3-4B. - -## M4: cuTile kernels (2026-10-27) - -Every op except attention moved to cuTile; attention still used the reference. - -- Decode GEMV at 68–93 % of the DRAM roofline (1.0–1.3× cuBLAS); prefill GEMM 0.70–0.92× - cuBLAS; rope / rmsnorm / store_kv / embed 3–29× the reference. -- End to end only 1.12× (decode) and 1.41× (prefill): the reference attention (≈ 1 ms per - layer, ~190 kernels per layer, ~6k GPU allocations per token) dominated. +`bench/breakdown.jl`, µs per step and share of the GPU-busy time. -## M5: paged flash-attention (2026-10-27) +**Decode** (graph replay, 1,024 positions): -| Change | Effect | -|---|---| -| FA-2 prefill kernel over the block table | prefill attention 1.27 ms → 30 µs (42×, 36 TFLOP/s) | -| Split-KV decode kernel + combine | decode attention 1.04 ms → 14 µs per layer (73×) | -| End to end | decode 34.8 → 3.8 ms (9.2×), prefill 54 → 16 ms (3.4×) | -| Prefill tile 64 → 32 query rows | prefill attention 1.28× (256 blocks instead of 128) | -| Decode query tile padded 2 → 16 rows, occupancy 2 | decode attention kernel 15.2 → 9.8 µs under `ncu` (fewer spills, 2 blocks/SM) | -| 2-D views to keep launches < 32 kernel parameters | ~10 µs less host time per launch; `store_kv` 1.7× | -| Block table padded to 16 pages | no recompiles at page boundaries: `tileinfer run` 55 → 133 tok/s on a 50-token reply | - -## M6: CUDA graphs (2026-10-27) +| Kernels | Qwen3-0.6B | Qwen3-4B | +|---|---|---| +| Layer GEMVs: qkv / o / gate_up + SwiGLU / down | 385 / 207 / 566 / 288 = 1,446 (59.1 %) | 1,683 / 1,139 / 5,346 / 2,626 = 10,793 (84.8 %) | +| lm_head GEMV | 452 (18.4 %) | 1,114 (8.8 %) | +| Attention decode + combine | 250 + 58 = 308 (12.6 %) | 322 + 75 = 396 (3.1 %) | +| Attention inputs (q, kv), add + RMSNorm ×2 | 63 + 64 + 106 = 233 (9.5 %) | 100 + 86 + 223 = 409 (3.2 %) | +| Embedding, first norm, sampling | 10 (0.4 %) | 11 (0.1 %) | +| **GPU busy per token** | **2,449** (99 % of the 2,472 µs period) | **12,723** (99.9 % of 12,738) | +| Roofline (weights + KV once) | 1,780 | 11,130 | -| Change | Effect | -|---|---| -| Allocation-free step with static buffers (eager) | decode 3.80 → 3.49 ms (1.09×), prefill 16.0 → 11.8 ms (1.36×) | -| Graph replay of the decode step | 3.49 → 2.87 ms (1.22×): the host no longer enqueues 539 kernels per token | +GEMV bandwidth inside the step: 0.6B qkv 83 %, o 77 %, gate_up + SwiGLU 85 %, down 83 %, +lm_head 94 %; 4B 91 / 90 / 91 / 93 / 95 %. A step is 10 kernels per layer plus 5, i.e. 285 +(0.6B) and 365 (4B) kernels per token. -After M6, under the tracer, the GPU was busy 2.93 ms per step, plus ~0.48 ms of gap between -steps (host sampling, uploads and the graph launch while the GPU idles). Kernel time per step: +**Prefill** (eager steps): -| Kernels | µs per step | -|---|---| -| GEMV (4 per layer + lm_head) | 1,919 | -| rmsnorm (4 per layer) | 303 | -| attention decode + combine | 252 + 63 | -| CUDA.jl broadcasts and copies (q/k/v slices, residual adds, Float32 logits) | 170 | -| rope, store_kv, silu_mul | 110 + 64 + 39 | +| Kernels | 0.6B, 64 tokens | 0.6B, 512 | 4B, 64 | 4B, 512 | +|---|---|---|---|---| +| GEMMs: qkv + o + gate_up + down | 1,657 (64.5 %) | 6,292 (73.1 %) | 12,268 (86.4 %) | 39,327 (87.7 %) | +| of which gate_up | 599 (23.3 %) | 2,270 (26.4 %) | 6,052 (42.6 %) | 18,613 (41.5 %) | +| lm_head GEMV (last token) | 454 (17.7 %) | 484 (5.6 %) | 1,123 (7.9 %) | 1,141 (2.5 %) | +| Attention prefill | 96 (3.7 %) | 751 (8.7 %) | 133 (0.9 %) | 1,540 (3.4 %) | +| Attention inputs (q, kv) | 193 (7.5 %) | 729 (8.5 %) | 330 (2.3 %) | 1,460 (3.3 %) | +| add + RMSNorm ×2, silu_mul | 165 (6.4 %) | 345 (4.0 %) | 346 (2.4 %) | 1,360 (3.0 %) | +| **GPU busy** (`bench/run.jl` step) | **2,568** (2.73 ms) | **8,607** (8.82 ms) | **14,205** (14.50 ms) | **44,840** (45.0 ms) | + +- At 64 tokens the GEMMs read the weights at 76–82 % of DRAM bandwidth, against 83–95 % for + the decode GEMVs that read the same bytes. +- `q_inputs_kernel` runs one block per (token, head): at 512 tokens on 0.6B, 8,192 blocks of + one 128-element column each, 16 µs per launch. With `kv_inputs_kernel`, the attention + inputs cost as much as attention itself there (729 against 751 µs). +- On 0.6B a 64-token prefill keeps the GPU busy 88 % of the step's span: the host cannot + enqueue 283 short kernels as fast as they run. 4B kernels are long enough (98 %). + +## The decode step: fusion, graphs and pipelining + +What each step of the decode path gained when it was added, on Qwen3-0.6B, against the +step without it: + +| Feature | Decode | Other | +|---|---|---| +| Static step buffers, no allocations | eager step 3.80 → 3.49 ms (1.09×) | prefill 512 1.36× | +| Decode replayed from a CUDA graph | 3.49 → 2.87 ms (1.22×) | 539 launches per token become one | +| Fused attention inputs: q/k RMSNorm + RoPE + KV write from `qkv`, 2 kernels instead of 8 launches | graph step 2.89 → 2.58 ms (**1.12×**) | eager 1.29×, prefill 1.26× | +| Residual add + RMSNorm in one kernel | 2.58 → 2.48 ms (1.04×) | prefill 1.04× | +| SwiGLU epilogue in the gate_up GEMV, Float32 logits from the lm_head GEMV | 2.48 → 2.46 ms (1.01×) | gate_up 21.6 µs against 22.8 for GEMV + `silu_mul` | +| Pipelined decode, greedy token sampled into the next step's inputs | 2.62 → 2.47 ms per token (1.06×) | GPU busy 95 % of wall time under the tracer, from 86 % | -## Perf branch (`perf-scratch`, 2026-10-27) +The fused kernels are bit-identical to the unfused cuTile ops. A first SwiGLU GEMV with +half-width column tiles (to keep registers per thread equal) was 6 % slower than unfused. -Baseline `p0` = M6 re-measured: graph step 2.89 ms (346 tok/s), eager 3.58 ms, prefill -11.83 ms; race 343 tok/s decode / 40k tok/s prefill. Each row is measured against the row -above it. +Not kept: -| # | Optimization | Decode (graph step) | Eager step | Prefill | Notes | -|---|---|---|---|---|---| -| 1 | **Fused attention inputs** (`attention_inputs!`): q/k RMSNorm + rope + KV write straight from `qkv`, 2 kernels instead of 8 launches per layer, no slice copies | 2.89 → 2.58 ms (**1.12×**) | 1.29× | 1.26× | biggest single win; bit-identical to the unfused tile ops | -| 2 | **Residual add + RMSNorm** (`add_rmsnorm!`), the next layer's input norm done by the previous layer | 2.58 → 2.48 ms (1.04×) | 1.03× | 1.04× | removes 2 broadcasts per layer | -| 3 | **GEMV epilogues**: SwiGLU in the decode gate_up GEMV, Float32 logits from the lm_head | 2.48 → 2.46 ms (1.01×) | 1.03× | 1.00× | fused gate_up 21.6 µs vs 22.8 µs for GEMV + silu_mul. A first version with half-width column tiles (to keep registers per thread equal) was 6 % slower than unfused | -| 4a | **Pinned staging, one async upload** of all step inputs | no change | — | — | groundwork for 4: uploads that don't block the host | -| 4 | **Device greedy sampling + pipelined decode** (`generate_greedy!`): argmax inside the graph writes the next step's input; two alternating graphs; the host launches step t+1 before reading token t | generate64: 2.62 ms/token with `pipeline = false` → **2.47 ms/token (1.06×)** | — | — | gaps between steps gone (GPU busy 95 % of wall time under the tracer); race decode 343 → 417 tok/s | -| 5 | GEMV tile sweep (TK ∈ 256…2048, TM ∈ 1…16) per decode shape | — | — | — | **no gain**: all configs within ~3 %. o/down (69–76 % of roofline) lose to per-kernel fill/drain, not tiling | -| 6 | Combine fused into the split-KV kernel (last split per head merges, via an acquire-release counter) | — | — | — | **reverted**: 322 µs/step vs 315 for decode + combine; the serial merge in one block costs what the launch saved | -| 7 | V load issued before the QK product in decode attention | — | — | — | **reverted**: 252 µs/step either way (the compiler already overlaps them) | -| — | Fewer decode splits (160 → 80 target blocks) | — | — | — | combine 63 → 47 µs/step (≈ 0.6 %); kept 160 for longer contexts | - -Final: generate64 **2.47 ms per token (405 tok/s, 72 % of the roofline)**, graph step -2.52 ms (it syncs after each step), prefill 9.0 ms (57k tok/s); race 418 tok/s / 53k tok/s. -Overall on this branch: decode 1.17× (2.89 → 2.47 ms), prefill 1.31×. - -A layer is now 10 kernels (qkv GEMV, q inputs, kv inputs, attention + combine, o GEMV, -add+norm, gate_up+SwiGLU GEMV, down GEMV, add+norm), 285 per token instead of 539. Kernel -time per step, after: - -| Kernels | µs per step | +| Variant | Measured | |---|---| -| GEMV (qkv, o, down, lm_head) + gate_up SwiGLU GEMV | 1,358 + 577 | -| attention decode + combine | 252 + 63 | -| add_rmsnorm (2 per layer) | 114 | -| attention inputs (q, kv) | 67 + 70 | -| argmax, embed, first rmsnorm | 9 | -| **total busy** | **2,510** (vs 2,930 at M6) | - -## Where the remaining time is +| GEMV tile sweep per decode shape (TK 256–2,048, TM 1–16) | every configuration within ~3 % of the default | +| Attention combine fused into the split-KV kernel (the last split of a head merges, through an acquire-release counter) | 322 µs per step against 315 for kernel + combine | +| V tile loaded before the QK product in decode attention | 252 µs per step either way | +| 80 instead of 160 target blocks for the decode splits | combine 63 → 47 µs per step (0.6 %), but fewer splits for long contexts | -Against the ~1.78 ms roofline at 1,024 positions: +## Sampling on the device -- **GEMVs: 1.94 ms vs a 1.62 ms floor** for reading the weights once. The lm_head is at - 92 %; the small layer GEMVs (4–12 MB each) lose 2–3 µs each to the fill and drain of a - kernel. Levers: weight-only INT8 (halves the bytes, the biggest one left), or split/stream-K - and persistent kernels. Ada has no programmatic dependent launch to overlap kernel tails. -- **Attention: 0.31 ms vs ~0.16 ms** for reading the KV cache. Each split handles about one - page, so the kernel is latency-bound; longer contexts amortize this better. -- **Small kernels: ~0.25 ms**, already fused down to 3 per layer. +Temperature, top-k and top-p sampling inside the captured step, pipelined like greedy +(the design is in [Architecture](architecture.md#Model-runner)): -## Per-shape GEMM tiles (2026-10-29) - -Prefill GEMM tiling for few tokens, and two ideas that did not pay on the 4080S: - -| Change | Result | Decision | +| | Qwen3-0.6B | Qwen3-4B | |---|---|---| -| **Per-shape GEMM tiles** (`gemm_config`): pick the tile minimizing waves × (TM TN)^0.7 among 6 shapes, instead of 64 or 128 rows × the next power of two ≥ n columns | Fitted to a sweep of 30 tile shapes × 8 layers (0.6B and 4B) × n = 2…1024: within 2 % of the best tile on average (worst 1.18×), 1.22× the old rule, 1.06× cuBLAS on average over n (ahead at small n, behind at n = 512: see "Two models"). `bench/run.jl` at n = 64: o 1.77×, down 1.98×, qkv and gate_up unchanged; **model/prefill64 3.62 → 3.00 ms (1.21×)**; n = 1 and 512 unchanged | **kept** | -| Split-K GEMM (Float32 partials + reduce kernel) for few tokens | Never beat the best direct tile at n = 2…64 (e.g. down n = 8: 13.7 µs vs 12.2 µs). K ≤ 3072 here, and 32-row tiles already give enough blocks; split-K pays with longer K or more SMs | not kept | -| Block-table entry of the next page read one page ahead in decode attention | 1.00× at 1k, 8k and 32k positions (n = 1 and 8): with 64-key pages and `ct.load` latency hints, long contexts already run at 600–660 GB/s. It matters with tiny pages, where every key is a gather | not kept | +| Decode, sampled: host sampling → device sampling | 3.32 → **2.46 ms per token (1.35×)** | 13.34 → **12.72 ms (1.05×)** | +| Sampled against greedy, both pipelined | +0.5 % | +0.1 % | +The sampling kernels take 17 µs per token at top-k = 20 and 5.6 µs for greedy (top-1). Their +variants, chunk kernel + final block, inside the 0.6B graph: -## Comparison with vLLM (same machine, `bench/ref`) +| Version | top-k 20 (µs) | top-1 (µs) | Kept | +|---|---|---|---| +| repeated `maximum` + `argmax` over values and ids | 10.0 + 11.0 = 21.0 | 2.3 + 3.3 | | +| `argmax` over ids only, values gathered from the logits | 8.4 + 10.8 = 19.2 | 2.2 + 4.1 | | +| `maximum`, then `minimum` of the positions holding it | 8.9 + 11.2 = 20.1 | — | no | +| argmax reducer without NaN checks (`FirstMax`) | **7.4 + 9.8 = 17.2** | 2.2 + 4.0 | **yes** | +| three levels (1,024-logit chunks, 16-list merge, final) | 6.4 + 5.4 + 7.2 = 19.0 | — | no | +| 8,192-logit chunks, 2,048-candidate final tile | 9.7 + 8.1 = 17.8 | — | no | -Setup of every run below (2026-11-01): RTX 4080 SUPER, which also drove the desktop -(compositor, VS Code and Discord on the GPU); TileInfer at commit 8528c2e on Julia 1.13.3; -vLLM 0.31.0 with torch 2.13.0 (`bench/ref/requirements.txt`) with CUDA graphs and -torch.compile; BF16 unless noted, prefix caching off and one sequence at a time. +Under `ncu` both kernels issue an instruction every 3–4 cycles at ~8 % achieved occupancy: +they are latency-bound, and their cost is the number of sequential block-wide reductions +(see [cuTile design choices](cutile_design.md#Few-reductions-inside-loops)). -`bench/ref/alternate.py`: 3 rounds alternating the engines -(ABBA order), each a fresh process that warms up for 1 s, then records 10 trials of each -latency; 30 trials per engine pooled. 512-token prompt, 256 greedy tokens, the same first -tokens on both engines. Medians are the primary statistic (timings are heavy-tailed), with -the interquartile range. +## Prefill GEMMs -| Median [q1, q3] | Qwen3-0.6B: vLLM | Qwen3-0.6B: TileInfer | Qwen3-4B: vLLM | Qwen3-4B: TileInfer | -|---|---|---|---|---| -| **End to end** (latency of 256 tokens) | **0.6439 s** [0.6419, 0.6476] | **0.6227 s** [0.6203, 0.6263] | **3.328 s** [3.296, 3.350] | **3.309 s** [3.300, 3.318] | -| 1-token request ("prefill") | 10.1 ms [9.9, 10.3] | 9.7 ms [9.6, 12.8] | 46.6 ms [45.5, 46.8] | 47.0 ms [45.4, 49.0] | -| Decode = (e2e − 1-token) / 255 | 2.49 ms/tok (402 tok/s) | 2.40 ms/tok (416 tok/s) | 12.87 ms/tok (77.7 tok/s) | 12.79 ms/tok (78.2 tok/s) | +**Per-shape tiles** (`gemm_config`): the tile minimizing waves × (TM TN)^0.7 among 6 shapes. +Fitted to a sweep of 30 tile shapes × 8 layers (both models) × n = 2…1,024: within 2 % of the +best tile on average (worst 1.18×), 1.22× the previous rule (64 or 128 rows × the next power +of two ≥ n columns). On 0.6B at n = 64: o 1.77×, down 1.98×, prefill64 3.62 → 3.00 ms. -On 0.6B TileInfer is **3.3 % faster end to end** (3.6 % on 2026-10-28), from fewer, fused -kernels per step. On 4B the engines tie: TileInfer's median is 0.6 % lower, but vLLM's -fastest round matches it (minimum 3.295 s vs 3.299 s), and both decode at ~87 % of the -bandwidth roofline (8.1 GB of weights and KV per token ≈ 11.1 ms, 90 tok/s), where the -per-kernel overheads that separate them at 0.6B are small next to 220 MB of weights per -layer. The 4B prefill gap of 2026-10-28 (53.2 vs 48.0 ms, ≈ 10 %, from GEMMs at 0.87–0.92× -cuBLAS) is closed, by the GEMM occupancy change and the per-shape tiles since. - -**Warm the GPU before timing short requests.** Until 2026-10-31 the race warmed up with a -single request. The GPU then runs the first ~0.2 s at 900–1,600 MHz instead of 2,775 MHz, -so a 10 ms request took 16–40 ms; the 256-token request lasts long enough to ramp the -clock and was not affected. That is what the 2026-10-28 run took for vLLM per-request -overhead (1-token clusters at ~11, ~25 and ~45 ms); with the 1 s warm-up its 1-token -latency is unimodal. On 0.6B the same change moved TileInfer's 1-token median from 27.8 to -9.7 ms and vLLM's from 31.8 to 10.1 ms (the same race, -run before the change). - -TileInfer has 1–3 slow 1-token trials per process (20–70 ms, and one of 200–250 ms in -every run, on both models), which widen its q3; vLLM has none. A traced repeat showed one -such trial spending 31 ms in GC and 37 ms compiling, so they are host-side pauses in Julia, -not GPU time. - -Earlier runs (2026-10-28, single warm-up request): 0.6B e2e 0.6200 s vs vLLM 0.6432 s, -4B 3.3062 s vs 3.3013 s, prefill 53.2 vs 48.0 ms. Single runs before that: vLLM `--eager` -172 tok/s decode / 39k tok/s prefill; TileInfer M6 343 tok/s / 40k tok/s (e2e 0.755 s). - -### With INT8 and speculative decoding (2026-11-01) - -**INT8.** TileInfer's `quantize = :int8` against the same quantization in vLLM: a W8A16 -compressed-tensors copy of each checkpoint (`bench/ref/make_w8a16.py`: TileInfer's per-channel -scales `max |W| / 127`, every linear and the untied `lm_head`; the embedding stays in BF16), -which vLLM runs with its Marlin kernels. INT8 KV is TileInfer's `Int8Pages` against vLLM's -`kv_cache_dtype = int8_per_token_head`, which moves vLLM to its Triton attention backend. -Same race (`alternate.py --weights int8 --kv int8`), e2e medians over 30 trials per engine: +**Two blocks per SM** (`gemm_occupancy`): `occupancy = 2` on grids of ≥ 160 blocks. Applied +everywhere, it slowed the small grids down: -| Latency of 256 tokens | 0.6B vLLM | 0.6B TileInfer | 4B vLLM | 4B TileInfer | -|---|---|---|---|---| -| BF16 (above) | 0.644 s | **0.623 s** (−3.3 %) | 3.328 s | 3.309 s (tie) | -| INT8 weights | 0.532 s | **0.503 s** (−5.5 %) | 1.880 s | 1.884 s (tie) | -| INT8 KV | 0.622 s | 0.625 s (tie) | **3.264 s** | 3.307 s (+1.3 %) | -| INT8 weights + KV | 0.474 s | 0.470 s (tie) | **1.837 s** | 1.871 s (+1.8 %) | - -Decode with both: 553 vs 555 tok/s on 0.6B, 143 vs 140 tok/s on 4B. vLLM gains more from -INT8 KV than the KV bytes explain (0.6B: −11 % against TileInfer's −6.6 %), probably from the -backend switch; not profiled. With INT8 weights the first tokens can differ between the -engines (vLLM stores the scales in BF16, TileInfer in Float32). +| | everywhere | ≥ 2 blocks per SM only (kept) | +|---|---|---| +| 4B gate_up / qkv / SwiGLU, n = 512 (608 / 192 / 608 blocks) | 1.11× / 1.08× / 1.11× | 1.12× / 1.10× / 1.11× | +| 4B o / down, n = 512 (80 blocks) | 0.97× / 0.96× | 0.99× / 1.01× | +| 0.6B o / down, n = 512 (32 blocks) | **0.86× / 0.89×** | 1.00× / 0.95× | +| 0.6B gate_up / SwiGLU, n = 64 (192 blocks) | 1.22× / 1.19× | 1.22× / 1.19× | +| Prefill 512, 4B / 0.6B | 1.05× / 1.01× | **1.06× / 1.02×** | -**Speculative decoding, best configuration per engine.** `bench/ref/tileinfer_spec.jl` and -`bench/ref/vllm_spec.py` on `bench/speculative.jl`'s six chat prompts (token ids exported by -`bench/ref/spec_prompts.jl`, so both engines get the same tokens), greedy, up to 256 tokens -stopping at EOS, median of 5 trials after a 1 s warm-up; decode = (n − 1) / (latency(n) − -latency(1)). Each engine ran plain, DFlash k = 7 and k = 15 (4B), n-gram k = 4 (0.6B), each in -BF16 and with INT8 weights + KV; the table keeps each engine's fastest per prompt. On 4B -it is DFlash k = 15 with INT8 for both engines, except TileInfer's k = 7 on long-explain. +Against cuBLAS (`bench/run.jl --ref`, speedup of the cuTile GEMM): -| Qwen3-4B | vLLM tok/s (× its BF16 plain) | TileInfer tok/s (× its BF16 plain) | TileInfer / vLLM | tokens per step vLLM / TileInfer | -|---|---|---|---|---| -| rename | 1,150 (14.7×) | 947 (12.2×) | 0.82 | 11.0 / 10.0 | -| document | 385 (4.9×) | 379 (4.9×) | 0.98 | 3.9 / 4.0 | -| explain | 322 (4.1×) | 290 (3.7×) | 0.90 | 3.2 / 3.0 | -| story | 255 (3.2×) | 219 (2.8×) | 0.86 | 2.5 / 2.3 | -| long-edit (2.2k) | 494 (6.5×) | **698 (9.2×)** | **1.41** | 8.0 / 8.3 | -| long-explain (2.2k) | 158 (2.1×) | **270 (3.5×)** | **1.70** | 2.6 / 3.0 | +| n | Qwen3-0.6B: qkv / o / gate_up / down | Qwen3-4B: qkv / o / gate_up / down | +|---|---|---| +| 64 | 1.07 / 1.43 / 1.03 / 1.45× | 1.04 / 1.04 / 1.04 / 1.09× | +| 512 | 0.88 / 0.88 / 0.96 / **0.72×** | 0.96 / 0.93 / 0.96 / 0.91× | -Acceptance is about the same on both engines, so the differences are step costs. On short -prompts vLLM's DFlash steps are cheaper: in BF16 on rename both take 10 steps for 110 tokens, -at 731 vs 558 tok/s (TileInfer's step is ~3.2 ms drafting + 13.3 ms verifying 16 tokens, see -"DFlash drafting"), and its plain INT8 decode is ~4 % faster at these short contexts (145 vs -139 tok/s; a tie at 768 positions in the race). At 2.2k positions vLLM's DFlash gains little -(long-explain: 158 tok/s against 134 plain), while TileInfer's keeps its speedup; where vLLM -loses that time is not profiled. - -On Qwen3-0.6B (no DFlash drafter) the comparison is noisier: with INT8, greedy replies differ -in length between the engines on two prompts, and TileInfer's reply to long-edit ends after -5 tokens. Where the replies match: n-gram helps TileInfer most on copying (rename: 1,725 vs -1,236 tok/s, n-gram + INT8 on both), vLLM's plain INT8 decode is 7 % faster at short contexts -(606 vs 563 tok/s on explain), and on long-explain TileInfer's n-gram + INT8 reaches 588 tok/s -against vLLM's best of 469 (plain INT8). vLLM's n-gram slows open text down (story, BF16: 298 -tok/s against 405 plain), TileInfer's is neutral there (413 vs 428). vLLM counts only the steps -that had drafts, so its n-gram tokens per step are not comparable and are left out. - -## Two models in the benchmark suite (2026-10-29) - -`bench/run.jl` now runs every op and model benchmark on Qwen3-0.6B and Qwen3-4B (one model -after the other, ~7 min with `--seconds 2`), and adds sampled generation. Baseline saved as -`two-models` (commit 3763805 + the suite changes). The two models stress different things: -0.6B has small layers (4–12 MB per GEMV), so per-kernel overheads and host work show; 4B has -up to 100 MB per GEMV, so decode is a bandwidth test and prefill a tensor-core test. Same -context (1,024 positions), same KV shape (8 KV heads of 128), so attention costs the same. - -### End to end +At n = 512 on 4B, cuBLAS runs at 82–105 TFLOP/s and the cuTile GEMMs at 78–97. 0.6B down at +n = 512 gets 64 × 128 tiles: 64 blocks for 80 SMs, each looping over K = 3,072. -| | Qwen3-0.6B | Qwen3-4B | -|---|---|---| -| Decode, greedy pipelined (`generate64`) | 2.44 ms/token, 409 tok/s, **72.8 %** of roofline | 12.70 ms/token, 78.7 tok/s, **87.6 %** | -| Decode, greedy step by step | 2.60 ms/token (1.06× slower) | 12.85 ms/token (1.01×) | -| Decode, sampled (Qwen3 defaults) | 3.32 ms/token, 301 tok/s (**1.36× slower**) | 13.40 ms/token, 74.7 tok/s (1.05×) | -| Decode step, graph / eager | 2.48 / 2.63 ms | 12.78 / 13.06 ms | -| Prefill 64 tokens | 3.02 ms (54 % of DRAM: reads the weights once) | 14.6 ms (75 % of DRAM) | -| Prefill 512 tokens | 9.00 ms, 56.9k tok/s | 47.6 ms, 10.8k tok/s | -| Tile vs reference: decode / prefill 512 | 16.2× / 8.5× | 6.2× / 4.8× | - -- **The M8 target (≥ 80 % of the decode roofline) is met on 4B, not on 0.6B.** The fixed - costs that 0.6B still pays (kernel fill and drain, host sampling, graph launch) are - constant per token, so at 4B they are drowned by 5× more bytes per token. -- **Sampled decoding costs a constant ~0.7–0.9 ms per token**: the logits (600 KB) are copied - to the host and sampled there, step by step, with the GPU idle meanwhile. That is 36 % of a - 0.6B token and 5 % of a 4B token. Device top-k/top-p sampling inside the graph, pipelined - like greedy, removes it; it is also what M7's rejection sampler needs. -- **Graphs matter little at 4B** (eager step 2 % slower vs 6 % at 0.6B): 363 launches cost - the same host time, but the GPU takes 5× longer per step, so enqueueing keeps ahead. - -### Decode step breakdown from the op benchmarks (per token, µs) - -| | Qwen3-0.6B (28 layers) | Qwen3-4B (36 layers) | -|---|---|---| -| GEMVs per layer: qkv + o + gate_up + down | 13.0 + 8.3 + 21.6 + 11.3 = 54 | 48.4 + 32.6 + 149.8 + 77.0 = 308 | -| GEMVs, all layers + lm_head | 1,518 + 454 = 1,972 (81 % of the token) | 11,081 + 1,120 = 12,201 (96 %) | -| GEMV bandwidth | 69–88 % of DRAM, lm_head 93 % | 87–90 %, lm_head 94.5 % | -| Attention decode, all layers | 15.1 × 28 = 423 | 15.0 × 36 = 540 | +Not kept: **split-K** (Float32 partials and a reduce kernel) for n = 2…64 never beat the best +direct tile (down at n = 8: 13.7 µs against 12.2); the `latency` hint on any GEMM load (see +[cuTile design choices](cutile_design.md)). -(gate_up is the plain GEMV; the decode step uses the fused SwiGLU GEMV: 21.6 µs on 0.6B vs -22.8 µs for GEMV + silu_mul, perf branch. The fused ops are not in this table: see "Full -picture" below for the whole step, kernel by kernel.) +## Attention for verify steps -At 4B the decode step is GEMVs at ~88 % of DRAM bandwidth. What is left: ~2–6 % by bringing -the layer GEMVs to the lm_head's 94 %, and beyond that only fewer bytes (weight-only INT8 -halves them). Attention is latency-bound at 38 % of DRAM for both (one page per split at -1,024 positions); it is 4 % of a 4B token. +Steps of 9–16 tokens (DFlash's verify block and the drafter's own pass) run the split-KV +decode kernels with 8 splits ([Attention kernels](attention.md)). +16-token attention per layer, µs, both kernels of a path: -### Prefill GEMMs against cuBLAS +| Positions | 0.6B prefill kernel | 0.6B decode, 32 splits | 0.6B, 8 splits | 4B prefill kernel | 4B decode, 32 splits | 4B, 8 splits | +|---|---|---|---|---|---|---| +| 128 | 4.5 | 8.3 | 5.5 | 4.8 | 12.4 | 6.7 | +| 256 | 7.6 | 7.6 | 5.3 | 8.1 | 12.2 | 6.7 | +| 512 | 14.3 | 7.9 | 5.7 | 14.8 | 12.6 | 7.2 | +| 1,024 | 27.4 | 8.8 | 6.7 | 26.9 | 13.6 | 9.5 | +| 2,048 | 53.4 | 11.2 | 9.8 | 53.6 | 17.4 | 14.3 | -| n | Qwen3-0.6B: qkv / o / gate_up / down | Qwen3-4B: qkv / o / gate_up / down | -|---|---|---| -| 64 | 1.06 / 1.42 / 0.84 / 1.45× | 0.99 / 1.03 / 1.03 / 1.12× | -| 512 | 0.93 / 0.88 / 0.91 / **0.77×** | 0.88 / 0.92 / 0.87 / 0.91× | +The decode kernel does not spill at 64 packed query rows (4B: 4 heads × 16 tokens, 230 +registers). End to end, Qwen3-4B with DFlash k = 15, prefill kernel → decode kernels: -- **At n = 512 every GEMM is behind cuBLAS** (82–105 TFLOP/s for cuBLAS on 4B vs 72–96 for - ours). On 4B the four GEMMs are 1,188 µs per layer, 42.8 ms of the 47.6 ms prefill; at - cuBLAS speed they would be 37.8 ms, which was the ~10 % prefill gap to vLLM in the 2026-10-28 race. -- **0.6B down at n = 512 (0.77×)**: `gemm_config` picks 64 × 128 tiles, i.e. 64 blocks for - 80 SMs, each looping over K = 3,072. An under-filled GPU with a long K loop is the case - where split-K (or stream-K) pays, unlike the n ≤ 64 shapes where split-K lost (see "Per-shape GEMM tiles"). -- The cost model was fitted to an average over n = 2…1024, where small n (tile wins up to - 1.45×) carries it. Tiles beyond 128 × 128, or deeper pipelining, are untested candidates for n ≥ 512. -- Prefill SwiGLU is a separate `silu_mul` kernel: 49 µs × 36 = 1.8 ms of a 4B prefill (4 %) - and 13.5 µs × 28 = 0.4 ms on 0.6B. A SwiGLU epilogue in the gate_up GEMM, as in the GEMV, - saves the kernel and the round trip of the (2I, n) activations. +| Prompt | positions | ms per verify step | tok/s | +|---|---|---|---| +| short chat prompts | 300–850 | unchanged (±2 %) | unchanged | +| long-edit (2.2k-token file) | 2,230–2,480 | 19.1 → 17.6 | 419 → **454** (+8.3 %) | +| long-explain | 2,230–2,480 | 18.9 → 17.3 | 154 → **169** (+10 %) | +Not kept: 32 splits for these steps (3.5 % slower on the rename prompt); reading the next +page's block-table entry one page ahead (1.00× at 1k, 8k and 32k positions, n = 1 and 8: +with 64-key pages long contexts already read the cache at 600–660 GB/s). -## Full picture: every kernel of a step (2026-10-29) +## INT8 weights -Before optimizing kernels: what each one costs inside real steps (`bench/breakdown.jl`, -decode replayed from graphs at 1,024 positions), and the fused ops' own op benchmarks -(`attention_inputs`, `add_rmsnorm`, `linear_swiglu`, `argmax`; baseline `full-picture`, -all other benchmarks unchanged from `two-models`). µs per step, share of the GPU-busy time. +Weight-only INT8 with one scale per output channel (`quantize = :int8`, `--int8`), the +embedding in BF16. Accuracy, mean KL divergence to the BF16 model over the fixture prompts +and top-1 agreement: Qwen3-0.6B 0.032 (46/50), Qwen3-4B 0.009 (49/50). Apertus 1.5 8B in INT8 +against transformers' Float32 run of the unquantized checkpoint: the argmax differs at 2 of +103 positions, both near-ties (margins 0.2 and 0.02), and 24-token greedy continuations are +identical on all three prompts. -### Decode +| | BF16 decode | INT8 decode | BF16 prefill 512 | INT8 prefill 512 | +|---|---|---|---|---| +| Qwen3-0.6B | 409 tok/s | 542 tok/s (1.32×) | 58.0k tok/s | 58.9k tok/s (1.02×) | +| Qwen3-4B | 78.7 tok/s | 139 tok/s (1.76×) | 11.4k tok/s | 11.1k tok/s (0.98×) | +| Apertus 1.5 8B | does not fit (16.1 GB) | 80.5 tok/s | — | 4.8k tok/s | -| Kernels | Qwen3-0.6B | Qwen3-4B | -|---|---|---| -| Layer GEMVs: qkv / o / gate_up + SwiGLU / down | 385 / 207 / 567 / 288 = 1,447 (59.0 %) | 1,683 / 1,138 / 5,347 / 2,625 = 10,793 (84.8 %) | -| lm_head GEMV | 451 (18.4 %) | 1,114 (8.8 %) | -| Attention decode + combine | 252 + 58 = 309 (12.6 %) | 324 + 74 = 399 (3.1 %) | -| Attention inputs (q, kv), add + RMSNorm ×2 | 63 + 65 + 106 = 234 (9.5 %) | 100 + 86 + 225 = 411 (3.2 %) | -| Embedding, first norm, argmax | 9 (0.3 %) | 10 (0.1 %) | -| **GPU busy per token** | **2,450** (99 % of the 2,472 µs period) | **12,726** (99.9 % of 12,740) | -| Roofline (weights + KV once) | 1,780 | 11,130 | +Apertus 8B in INT8 holds 8.6 GB of weights (linear 7.0 GB, lm_head 0.54 GB, BF16 embedding +1.07 GB) and loads in 12 s. Its decode step (12.4 ms from a graph) reads ~7.5 GB of weights +plus the KV cache, ~82 % of the roofline. + +**GEMV tiles.** TK × TM ≈ 4,096 Int8 elements (TK = 1,024, TM = 4), half BF16's width, was +best on every Apertus 8B layer; BF16's TM = 8 was 7–13 % slower, TK ≥ 2,048 with TM ≥ 4 +much slower. The INT8 GEMVs run at 85–93 % of the roofline (Apertus: qkv 91 %, o 87 %, +up + xIELU 91 %, down 85 %, lm_head 93 %). + +**GEMM tiles.** With BF16's tiles, INT8 prefill was 8–11 % slower than BF16. Under `ncu` +(Qwen3-4B down): at 512 tokens 255 registers and 1.6× BF16's instructions (byte shuffles and +conversions of the weight tile); at 64 tokens 29 % of DRAM peak against BF16's 90 %, with 37 % +of the stall samples on the conversion waiting for its global load, because the Int8 tile is +not staged through shared memory like the BF16 operands. A sweep of 15 tiles × occupancy 1, 2 +on the layers of Qwen3-0.6B, Qwen3-4B and Apertus 8B at n = 8, 64, 512 found that INT8 blocks +always want two per SM, narrower tiles than BF16 at 512 tokens (128 × 64 × 64), and deeper K +steps at ≤ 64 tokens (32 × 32 × 256, or 64 × 64 × 128 on large grids). `gemm_int8_config` +is within 1.5 % of the best tile summed over the sweep (worst 1.11×). Qwen3-4B: + +| | BF16 tiles | INT8 tiles | BF16 | +|---|---|---|---| +| GEMMs at 64 tokens: qkv / o / gate_up / down | 72 / 46 / 155 / 126 µs | 44 / 26 / 99 / 62 µs | 60 / 36 / 175 / 85 µs | +| GEMMs at 512 tokens | 237 / 155 / 580 / 369 µs | 196 / 127 / 567 / 284 µs | 203 / 116 / 521 / 266 µs | +| Prefill 64 | — | **9.5 ms (1.53× BF16)** | 14.5 ms | -GEMV bandwidth inside the step: 0.6B qkv 83 %, o 77 %, gate_up + SwiGLU 85 %, down 83 %, -lm_head 94 %; 4B 91 / 90 / 91 / 93 / 95 %. Over the roofline: +Not kept: `latency` hints on the weight loads (1–8), and swapping the GEMM operands (Xᵀ W, +the weight in its natural layout as the B operand). -- **0.6B, +670 µs**: GEMVs +279 (1,898 vs a 1,619 floor; the 4–12 MB layers lose to fill and - drain), small kernels +242 (~2 µs each, 116 of them), attention +149 (309 vs 160 to read - the KV once, latency-bound with about one page per split). Three levers of similar size. -- **4B, +1,596 µs**: GEMVs +976 (11,907 vs 10,931: the layer GEMVs at 90–93 % against the - lm_head's 95 %), small kernels +421, attention +193. GEMV bandwidth first. -- **Host**: greedy decode keeps the GPU 99 % busy. Sampled decode idles it ~0.9 ms per token - (66 % busy on 0.6B under the tracer, 93 % on 4B; 0.88 / 0.69 ms per token in run.jl). +## INT8 KV cache -Op benchmarks against the same kernels inside the 0.6B decode graph (µs per call): eager -launches inflate every kernel under ~6 µs, so use the breakdown for small kernels. +One Int8 scale per cached vector, keys smoothed by the key norm's weight +([KV cache](kv_cache.md#INT8-cache)). Why the keys need smoothing, Qwen3-0.6B, chat prompt, +relative error of the quantized cache: -| | qkv | o | gate_up + SwiGLU | down | lm_head | attention | attention inputs | add + RMSNorm | argmax | -|---|---|---|---|---|---|---|---|---|---| -| `bench/run.jl` (eager) | 13.0 | 8.3 | 21.2 | 11.3 | 453 | 15.1 | 15.6 | 5.9 | 9.8 | -| In the graph | 13.7 | 7.4 | 20.2 | 10.3 | 451 | 11.1 | 4.6 | 1.9 | 4.2 | +| | layer 1 K | layer 2 K | layer 14 K | layer 28 K | values (any layer) | +|---|---|---|---|---|---| +| one scale per vector | 0.022 | 0.025 | 0.011 | 0.020 | 0.007–0.013 | +| one scale per channel (KIVI) | 0.005 | 0.004 | 0.008 | 0.005 | 0.008–0.016 | +| per vector, keys smoothed (kept) | **0.003** | **0.004** | 0.011 | **0.006** | — | +| largest / median channel max | 109 | 43 | 6.5 | 11 | 1.6–5 | -### Prefill +Per-channel scales do not fit a cache written one position at a time. Mean KL to a BF16 +cache, and largest logit difference to transformers (BF16 cache: 0.63): -| Kernels | 0.6B, 64 tokens | 0.6B, 512 | 4B, 64 | 4B, 512 | +| Qwen3-0.6B | chat | prose | code | max logit difference | |---|---|---|---|---| -| GEMMs: qkv + o + gate_up + down | 1,796 (66.3 %) | 6,467 (73.6 %) | 12,367 (86.4 %) | 41,895 (88.3 %) | -| of which gate_up | 736 (27.2 %) | 2,448 (27.9 %) | 6,136 (42.9 %) | 20,653 (43.5 %) | -| lm_head GEMV (last token) | 454 (16.7 %) | 483 (5.5 %) | 1,122 (7.8 %) | 1,141 (2.4 %) | -| Attention prefill | 96 (3.5 %) | 751 (8.5 %) | 133 (0.9 %) | 1,537 (3.2 %) | -| Attention inputs (q, kv) | 193 (7.1 %) | 730 (8.3 %) | 331 (2.3 %) | 1,459 (3.1 %) | -| add + RMSNorm ×2, silu_mul | 165 (6.1 %) | 343 (3.9 %) | 354 (2.5 %) | 1,382 (2.9 %) | -| **GPU busy** (run.jl step) | **2,708** (2.89 ms) | **8,781** (9.00 ms) | **14,312** (14.55 ms) | **47,425** (47.64 ms) | - -- **GEMMs are 66–88 % of prefill**, gate_up alone 28 % (0.6B) to 44 % (4B). At 512 tokens - they are compute-bound and 0.77–0.93× cuBLAS (see "Two models"); at 64 tokens they are - bandwidth-bound and read the weights at 67 % (0.6B) and 80 % (4B) of DRAM, against 83–93 % - for the decode GEMVs that read the same bytes. -- **Attention inputs at 512 tokens cost as much as attention itself on 0.6B** (730 vs - 751 µs): `q_inputs_kernel` runs one block per (token, head), 8,192 blocks of one 128-element - column each, 16 µs per launch for 8.6 MB (≈ 42 % of DRAM with kv_inputs). -- **0.6B prefill64 idles the GPU 9 % of the step** (busy 2.71 ms, span 2.98, run.jl 2.89): - 283 eager launches of mostly short kernels, which the host cannot enqueue as fast as they - run. 4B kernels are long enough (98 % busy). A graph for short prefills would remove it. -- The lm_head reads 311 MB (0.6B) for one token's logits: 17 % of a 64-token prefill. - -### What to optimize - -Upper bounds from the tables above (removing the whole excess): - -| Target | Where it shows | At most | -|---|---|---| -| ~~Device top-k/top-p sampling, pipelined like greedy~~ (done, see "Device sampling") | sampled decode | 0.7–0.9 ms per token: 1.36× on 0.6B, 1.05× on 4B | -| Prefill GEMMs at n = 512 to cuBLAS (larger tiles, split-K for under-filled shapes such as 0.6B down) | prefill512 | up to ~10 % of the step (4B: ~5 ms) | -| Prefill GEMMs at n = 64 to GEMV bandwidth | prefill64 | ~10–20 % of the GEMM time | -| Layer GEMVs from 90–93 % to the lm_head's 95 % (4B), fill/drain of small GEMVs (0.6B) | decode | 4B ~3 %, 0.6B ~11 % | -| Small decode kernels: fewer of them (q + kv inputs in one kernel, norms into GEMV epilogues) | decode | 0.6B ~10 %, 4B ~3 % | -| Attention decode (latency-bound at 1k positions) | decode, long contexts | 0.6B ~6 %, grows with context | -| `q_inputs_kernel` with several tokens per block | prefill512 | 0.6B ~4 % | -| Graphs (or fewer launches) for short prefills | 0.6B prefill64 | ~9 % | - -## Device sampling (2026-10-29) - -Temperature / top-k / top-p sampling now runs on the device inside the captured decode step -(`sample_token!`, `src/ops/tile/sampling.jl`), so sampled decoding is pipelined like greedy -(`generate_pipelined!`); greedy is top-1 through the same kernels, and `argmax_token!` is gone. -A token is a function of the logits and u = `sampling_uniform(seed, counter)` (a hash of a -per-generation seed and a device-side counter), so the device and `sample_host` pick the same -tokens and the tests compare them token by token. Device sampling covers top_k ≤ 64; other -settings (e.g. top_k = 0) still sample on the host, step by step. Baseline `sampling-before` -(a313e48), result `sampling-after`. +| one scale per vector | 0.030 | 0.0089 | 0.0043 | 1.75 | +| smoothed keys (kept) | **0.0051** | **0.0040** | **0.0022** | **0.88** | -| | Qwen3-0.6B | Qwen3-4B | +Speed on Qwen3-4B: + +| | BF16 cache | INT8 cache | |---|---|---| -| Decode, sampled (Qwen3 defaults: T 0.6, top-k 20, top-p 0.95) | 3.32 → **2.46 ms/token (1.35×)**, 407 tok/s | 13.34 → **12.72 ms/token (1.05×)** | -| Decode, greedy pipelined | 2.44 ms/token (unchanged) | 12.71 ms/token (unchanged) | -| Sampled vs greedy | +0.5 % | +0.1 % | +| decode at 1,024 positions | 78.7 tok/s | 78.1 tok/s | +| decode at 32,768 positions (graph step) | 51.3 tok/s | **60.9 tok/s (1.19×)** | +| decode attention at 32,768 positions | 209 µs (642 GB/s) | 119 µs (581 GB/s, for 0.52× the bytes) | +| prefill 512 | 44.9 ms | 45.8 ms | -Kernel time per token inside the 0.6B graph (`bench/breakdown.jl`), chunk kernel + final block: +**Register pressure.** Converting whole `(64, 128)` pages spilled (255 registers, 38 % of +L1 traffic in local memory, 3.1× the BF16 kernel's instructions); converting K alone needs +178 registers, V alone 232. Variants at 32k positions (`bench/codegen/probes/08_int8_attention.jl`): -| Version | top-k 20 (µs) | top-1 / greedy (µs) | Note | +| Decode attention, Int8 K and V | µs | registers | spills | |---|---|---|---| -| Old argmax (greedy only) | — | 4.2 | | -| 1: repeated `maximum` + `argmax` over values and ids | 10.0 + 11.0 = 21.0 | 2.3 + 3.3 = 5.6 | | -| 2: `argmax` over ids only, values gathered from the logits | 8.4 + 10.8 = 19.2 | 2.2 + 4.1 | | -| `maximum` then `minimum` of the positions holding it | 8.9 + 11.2 = 20.1 | — | **reverted**: two plain reductions cost as much as one `argmax` | -| **3: argmax reducer without NaN handling** (`FirstMax`) | **7.4 + 9.8 = 17.2** | 2.2 + 4.0 = 6.2 | kept | -| Three levels (1024-logit chunks, 16-list merge, final) | 6.4 + 5.4 + 7.2 = 19.0 | — | **reverted** | -| 8192-logit chunks, 2048-candidate final tile | 9.7 + 8.1 = 17.8 | — | **reverted**: no better | - -- **The cost is the number of sequential block-wide reductions**, not the data: selection is - top_k repeated argmax per kernel, and one costs 0.3–0.5 µs on 128 threads whatever the - tile (0.32 µs at 1,024 elements, 0.37 at 4,096, 0.48 at 8,192). Smaller tiles in more - kernels only add reductions. Under `ncu` both kernels issue an instruction every 3–4 - cycles with ~8 % achieved occupancy: latency-bound, one warp per scheduler. -- **17 µs is 0.7 % of a 0.6B token**; going further needs fewer than top_k sequential - reductions (e.g. a threshold found by counting, then sorting a small candidate set by - pairwise comparison), not worth it at this size. - -## GEMM occupancy (2026-10-29) - -From the codegen audit ([cuTile design choices](cutile_design.md)): the prefill GEMM never set the `occupancy` -hint. With `occupancy = 2`, tileiras fits two blocks per SM by trimming each block's -registers and shared memory: grids of ≥ 2 blocks per SM gain latency hiding, smaller grids -only lose resources. `gemm_occupancy` applies it to grids of ≥ 160 blocks. Baseline -`gemm-occ-before`, result `gemm-occ-rule`: +| whole pages | 117–123 | 255 | 56 B | +| V stored transposed per page (another cache layout) | 112 | 255 | 8 B | +| Int8 QKᵀ: queries quantized per column, `mmai` | 109 | 206 | 0 | +| Int8 QKᵀ with two-term queries (q_hi + q_lo / 254) | 115 | 232 | 0 | +| 32-key tiles | 113 | 211 | 0 | +| K and V in halves of the head dimension | 114 | 190 | 0 | +| **32-key tiles and halves (kept)** | **111** | **184** | **0** | -| | everywhere | ≥ 2 blocks per SM only (kept) | -|---|---|---| -| 4B gate_up / qkv / SwiGLU, n = 512 (608 / 192 / 608 blocks) | 1.11× / 1.08× / 1.11× | 1.12× / 1.10× / 1.11× | -| 4B o / down, n = 512 (80 blocks) | 0.97× / 0.96× | 0.99× / 1.01× | -| 0.6B o / down, n = 512 (32 blocks) | **0.86× / 0.89×** | 1.00× / 0.95× | -| 0.6B gate_up / SwiGLU, n = 64 (192 blocks) | 1.22× / 1.19× | 1.22× / 1.19× | -| **Prefill 512**: 4B / 0.6B | 1.05× / 1.01× | **1.06× (47.8 → 45.2 ms) / 1.02×** | -| **Prefill 64**: 4B / 0.6B | 1.01× / 1.07× | 1.01× / 1.04× | - -Verify-sized GEMMs (n = 2–8, bandwidth-bound) are within 1 % either way. The `latency` -hint did not help any GEMM or GEMV, and prefill attention stays at `occupancy = 2` -(3 measured the same). +In the real kernel the kept variant runs at 191 registers (prefill kernel: 232 → 218) and +took decode attention at 32k positions from 150 to 119 µs and prefill-512 attention from 84 to +67 µs (1.25×; 0.6B 1.28×). Int8 QKᵀ was not kept: the KL to the BF16 cache went from 0.0051 +to 0.0070 (chat) and the largest logit difference from 0.88 to 2.0, because smoothing makes +the scaled queries heavy-tailed. `latency` hints on the loads changed nothing. +## Speculative decoding -## Speculative decoding, greedy with n-gram lookup (2026-10-29) +Qwen3-4B target unless noted, `bench/speculative.jl`, speedup in decode tok/s over plain +pipelined decoding (78–80 tok/s). -`generate!(…; speculative = NgramProposer(k = …))`: prompt lookup proposes up to k tokens, -one verify step of k + 1 tokens (all logits, argmax per position on the device, one graph -per step length) accepts the matching prefix plus a bonus token, and `truncate!` drops the -rejected keys and values. 200-token budget, BF16, best of 5, against greedy pipelined decoding -(both include the prefill): +**n-gram lookup**, measured with a 200-token budget, best of 5, including the prefill: | Prompt | Model | plain | k = 1 | k = 2 | k = 4 | k = 7 | tokens per step at k = 7 (acceptance) | |---|---|---|---|---|---|---|---| -| rename two variables in a 15-line function (116 / 110 tokens out) | 0.6B | 424 tok/s | 1.65× | 2.22× | 3.19× | **4.15×** | 4.83 (0.63) | +| rename two variables in a 15-line function | 0.6B | 424 tok/s | 1.65× | 2.22× | 3.19× | **4.15×** | 4.83 (0.63) | | | 4B | 78 tok/s | 1.65× | 2.08× | 2.87× | **3.75×** | 4.07 (0.53) | -| short story (nothing to copy) | 0.6B | 434 tok/s | 0.96× | 0.97× | 0.97× | 0.96× | 1.05 (0.02) | +| short story | 0.6B | 434 tok/s | 0.96× | 0.97× | 0.97× | 0.96× | 1.05 (0.02) | | | 4B | 80 tok/s | 1.05× | 1.05× | 1.05× | 1.05× | 1.08 (0.03) | - -A verify step of 8 tokens costs little more than a decode step (the GEMMs at n = 8 still -read the weights once), so the speedup tracks tokens per step. With no matches the loss -on 0.6B is the host/GPU overlap of pipelined decoding: speculative steps synchronize to read -the accepted count before proposing. In BFloat16 the outputs can part from plain greedy at -near-ties (verify steps round differently than decode steps); in Float32 they are identical -(test/engine/speculative.jl). - -**Sampling** (same day). For a deterministic proposer, rejection sampling (accept d with -probability p(d), else sample from p without d) is the same as sampling the target's token at -each position and accepting d when they agree. The verify step does that with the device -sampler and the counters plain decoding would use, so sampled speculative decoding picks the -tokens of plain sampled decoding: identical over 200 tokens in Float32 (4 seeds); in BF16 they -part after 15–45 tokens, sooner than greedy, as a sample flips whenever its uniform falls -within round-off of a cumulative boundary. With Qwen3's recommended sampling (temperature 0.6, -top-k 20, top-p 0.95), against pipelined sampled decoding: - -| Prompt | Model | plain | k = 1 | k = 2 | k = 4 | k = 7 | tokens per step at k = 7 (acceptance) | -|---|---|---|---|---|---|---|---| -| rename two variables | 0.6B | 422 tok/s | 1.64× | 2.19× | 3.13× | **4.06×** | 4.83 (0.63) | +| *sampled:* rename | 0.6B | 422 tok/s | 1.64× | 2.19× | 3.13× | **4.06×** | 4.83 (0.63) | | | 4B | 78 tok/s | 1.65× | 2.08× | 2.86× | **3.73×** | 4.07 (0.53) | | short story | 0.6B | 432 tok/s | 1.00× | 1.01× | 1.00× | 1.00× | 1.10 (0.03) | | | 4B | 80 tok/s | 1.04× | 1.05× | 1.04× | 1.04× | 1.08 (0.03) | -The rename task is nearly deterministic at temperature 0.6 (the same steps as greedy). - -## Draft-model speculative decoding (2026-10-29) +With nothing to copy, 0.6B loses the host/GPU overlap of pipelined decoding: speculative +steps synchronize to read the accepted count. Sampled speculative decoding picks the tokens +of plain sampled decoding: identical over 200 tokens in Float32 (4 seeds); in BF16 they part +after 15–45 tokens. -`DraftProposer(draft_model; k)`: Qwen3-0.6B drafts for Qwen3-4B on a cache of its own. Each -proposal rewinds the draft to the longest common prefix with the context, runs the one or -two new tokens through a captured step, then decodes k - 1 steps as a chain of CUDA graphs -(each samples the next draft on the device into the next step's ids); the host syncs once -per proposal. The draft decodes greedily even when the target samples, which keeps the -verification exact (the draft is a function of the context). `bench/speculative.jl`, 4B -target, 256 tokens, decode tok/s (from the first new token), best of 3: +**Draft model** (Qwen3-0.6B), 256 tokens: -| Prompt | plain | n-gram k = 2 / 4 / 7 | draft k = 2 / 4 / 7 | draft acceptance at k = 4, tokens per step | +| Prompt | plain | n-gram k = 2 / 4 / 7 | draft k = 2 / 4 / 7 | draft acceptance, tokens per step at k = 4 | |---|---|---|---|---| | rename two variables (greedy) | 72 tok/s | 2.29× / 3.18× / **4.22×** | 2.28× / 2.89× / 3.62× | 0.96, 4.78 | | add a docstring and comments | 79 | 1.37× / 1.46× / 1.53× | 1.64× / **1.78×** / 1.65× | 0.56, 3.24 | | explain hash-map collisions | 79 | 1.09× / 1.09× / 1.11× | 1.59× / **1.63×** / 1.46× | 0.49, 2.94 | | short story | 79 | 1.04× / 1.03× / 1.03× | **1.39×** / 1.35× / 1.09× | 0.36, 2.44 | -| *sampled (0.6, top-k 20, top-p 0.95):* rename | 78 | 2.09× / 2.92× / **3.87×** | 2.09× / 2.65× / 3.33× | 0.96, 4.78 | +| *sampled:* rename | 78 | 2.09× / 2.92× / **3.87×** | 2.09× / 2.65× / 3.33× | 0.96, 4.78 | | add a docstring and comments | 79 | 1.38× / 1.45× / 1.54× | 1.71× / **1.91×** / 1.79× | 0.62, 3.46 | | explain hash-map collisions | 79 | 1.08× / 1.08× / 1.10× | **1.47×** / 1.39× / 1.13× | 0.38, 2.53 | | short story | 79 | 1.02× / 1.02× / 1.02× | **1.42×** / 1.37× / 1.18× | 0.37, 2.49 | -A draft step of the 0.6B model costs about a fifth of a 4B decode step, so each draft -token must be accepted with a probability of roughly 0.2 or more to pay; at k = 7 the late -drafts on open text rarely are. n-gram lookup is free but only finds text the reply copies. -Candidates: pick k (or the proposer) from the measured acceptance, as DeepInfer's scheduler -does; combine both proposers (n-gram when it matches, the draft otherwise). +**DFlash** (z-lab/Qwen3-4B-DFlash-b16) against the other proposers, best k of each (k = 15 +for DFlash in every row). EAGLE-3 (AngelSlim/Qwen3-4B_eagle3, best at k = 2) was removed +from the engine; its column is kept for comparison: -## EAGLE-3 drafting (2026-10-29) - -*Removed on 2026-11-01: DFlash (next section) beats it on every prompt, and its tests cost -~36 s. The numbers below are kept as the record of a chained drafter on hidden states.* +| Prompt | n-gram | 0.6B draft | EAGLE-3 | DFlash | DFlash tokens per step | +|---|---|---|---|---|---| +| rename (greedy) | 3.92× | 3.36× | 2.25× | **8.50×** | 11.0 | +| document | 1.55× | 1.80× | 1.75× | **3.00×** | 3.94 | +| explain | 1.12× | 1.63× | 1.58× | **2.50×** | 3.24 | +| story | 1.04× | 1.39× | 1.45× | **1.92×** | 2.51 | +| *sampled:* document | 1.54× | 1.92× | 1.82× | **3.17×** | 4.20 | +| explain | 1.10× | 1.48× | 1.46× | **2.30×** | 3.01 | +| story | 1.03× | 1.42× | 1.57× | **1.75×** | 2.31 | + +The drafts match a Float32 transcription of z-lab's `dflash.py`, and acceptance on the +"explain" prompt is the reference's (2.78 against 2.76 tokens per step over 128 tokens). +Per-draft acceptance on "explain" falls from 0.67 at k = 2 to 0.15 at k = 15. On the two +2.2k-token prompts, the whole block still pays on the edit (5.9× over plain, 8.0 tokens per +step), while on the open one k = 7 wins (2.37× against 2.20×; 3.2 and 2.9 tokens per step). +Plain decoding runs at 77 tok/s there, and the 2.2k-token prefill takes 203 ms. + +Costs of a DFlash step at 400 positions: + +| | ms | +|---|---| +| drafter pass (GEMMs: 1.85 GB at ~650 GB/s, 0.78 GB of it the lm_head) | 3.17 | +| verify step of 16 tokens (1 token: 12.7) | 13.3 | +| draft sampling: 15 launches per column → one batched kernel | 0.086 → 0.050 | +| host round trip between drafter and verify, removed (drafts written on the device) | ~0.2 (+1.2 % tok/s) | -`Eagle3Proposer(load_eagle3("AngelSlim/Qwen3-4B_eagle3", target); k)`: target steps keep -the residual stream after layers 2, 18 and 33 (`enable_aux!`, three strided copies per -step); the drafter's one Llama layer reads [norm(embed(next token)); norm(fc(those states))] -for the positions the target just verified (one graph per count), then its own output for -k - 1 chained steps (as for the draft model), over a 32k vocabulary mapped back with `d2t`. -A drafter step costs about a tenth of the 0.6B draft model's. Its acceptance matches -AngelSlim's report (accept length 2.07–2.10 at 2 drafts on vLLM; here 1.80–2.50 at k = 2) -and decays quickly along the chain, so k = 2 is best. `bench/speculative.jl`, 4B target, k = 2 / 4: +**Sampled drafts** (the p/q rule, `--sample-drafts`), with Qwen3's recommended sampling, +best k of each method, greedy drafts → sampled drafts. Each row is a single sampled reply, +so one step more or less moves it by several percent: -| Prompt | plain | n-gram | 0.6B draft | EAGLE-3 | EAGLE-3 tokens per step (acceptance) at k = 2 | -|---|---|---|---|---|---| -| rename (greedy) | 78 tok/s | 2.12× / 2.96× | 2.12× / 2.68× | **2.20×** / 2.25× | 2.50 (0.75) | -| document | 80 | 1.37× / 1.48× | 1.66× / **1.80×** | 1.74× / 1.75× | 2.00 (0.50) | -| explain | 80 | 1.10× / 1.10× | 1.60× / **1.64×** | 1.58× / 1.55× | 1.82 (0.41) | -| story | 80 | 1.04× / 1.04× | 1.39× / 1.36× | **1.51×** / 1.46× | 1.73 (0.36) | -| *sampled:* document | 80 | 1.39× / 1.46× | 1.72× / **1.92×** | 1.74× / 1.82× | 2.00 (0.50) | -| explain | 80 | 1.09× / 1.10× | **1.48×** / 1.41× | 1.46× / 1.40× | 1.67 (0.34) | -| story | 80 | 1.03× / 1.03× | 1.42× / 1.39× | **1.57×** / 1.54× | 1.80 (0.40) | - -(n-gram at k = 7 stays best on the rename prompt: 3.92×.) EAGLE-3 trades acceptance for -cheap drafts and ends up level with the 0.6B draft model; this head was trained for two -drafts. The tests use GavinLucky/SGLang-EAGLE3-Qwen3-0.6B-SpecForge with Qwen3-0.6B. - -## DFlash drafting (2026-10-30) - -`DFlashProposer(load_dflash("z-lab/Qwen3-4B-DFlash-b16", target))`: five Qwen3 layers read -the residual stream after target layers 2, 10, 18, 26 and 34. One drafter step runs the -positions the target just verified (their keys and values, from `fc` of those states, stay in -the drafter's cache) and a block of [next token, 15 masks] that attends without the causal -mask (`attention(…; causal = false)`, a constant in both kernels); the target's lm_head over -the block gives 15 drafts at once. Verify steps now take up to 16 tokens (`MAX_VERIFY_TOKENS`). -The drafts match a Float32 transcription of z-lab's `dflash.py` (test/engine/dflash.jl), and -its acceptance on the "explain a hash map" prompt is the reference's (2.78 vs 2.76 tokens per -step over 128 tokens). - -Costs at 400 positions: drafter step 3.17 ms whatever the context count (GEMMs 2.85 ms at -~650 GB/s for 1.85 GB of weights, 0.78 GB of which is the lm_head; 15 per-column sampling -launches 0.11 ms), verify of 16 tokens 13.3 ms against 12.7 ms for one token. A step costs -~1.3 decode steps, so DFlash pays from 1.3 tokens per step on. `bench/speculative.jl`, 4B -target, best k of each method (k = 15 for DFlash in every row): - -| Prompt | plain | n-gram | 0.6B draft | EAGLE-3 | DFlash | DFlash tokens per step | -|---|---|---|---|---|---|---| -| rename (greedy) | 78 tok/s | 3.92× | 3.36× | 2.25× | **8.50×** | 11.0 | -| document | 80 | 1.55× | 1.80× | 1.75× | **3.00×** | 3.94 | -| explain | 80 | 1.12× | 1.63× | 1.58× | **2.50×** | 3.24 | -| story | 80 | 1.04× | 1.39× | 1.45× | **1.92×** | 2.51 | -| *sampled:* document | 80 | 1.54× | 1.92× | 1.82× | **3.17×** | 4.20 | -| explain | 80 | 1.10× | 1.48× | 1.46× | **2.30×** | 3.01 | -| story | 80 | 1.03× | 1.42× | 1.57× | **1.75×** | 2.31 | - -Unlike the chained drafters, whose acceptance falls along the chain so that k = 2 to 4 is -best, a longer DFlash block costs nothing more to draft and little more to verify, so the -whole block always wins: per-draft acceptance drops (0.67 at k = 2 to 0.15 at k = 15 on -explain) while tokens per step keep rising. The contrast with EAGLE-3 is the point of the -method: both read the target's hidden states, but EAGLE-3 pays one pass per draft and DFlash -one pass per block. Candidates: write the drafts on the device straight into the verify -step's ids (the host now waits for them in between); one batched argmax instead of 15 -sampling launches. - -## Sampled drafts, the p/q rule (2026-10-30) - -`DraftProposer(…; sample = true)` (also `Eagle3Proposer`, `DFlashProposer`; CLI -`--sample-drafts`): when the target samples, the drafter samples its drafts with the target's -parameters on its own logits, under a seed of its own, and records each draft's filtered -distribution q (its ≤ 64 survivors' ids and probabilities, written by the sampling kernel -itself). The verify step then runs `accept_token!` at each drafted position: accept d with -probability min(1, p(d)/q(d)), else sample from max(p − q, 0) (a (64, 64) comparison of the -two survivor lists), with a uniform stream of its own for the acceptance; the bonus position -samples as before. A rejected position never emits the draft, so the host's accept loop is -unchanged. The tokens follow the target's distribution, but are no longer plain decoding's. -The new kernels share the candidate selection with the plain sampler (`survivors`, `pick`), -which measured the same after the refactor (16.8 µs). - -Greedy drafts are accepted with probability p(argmax q), sampled ones with Σ min(p, q). With -Qwen3's recommended sampling (T 0.6, top-k 20, top-p 0.95) the distributions are peaked and -the two are close. `bench/speculative.jl --sampled [--pq]`, 4B target, 256 tokens; best k of -each method, speedup over sampled plain decoding (greedy drafts → sampled drafts): - -| Prompt | 0.6B draft | EAGLE-3 | DFlash | acceptance, draft k = 4 | +| Prompt | 0.6B draft | EAGLE-3 | DFlash | draft acceptance at k = 4 | |---|---|---|---|---| | rename | 3.35× → 3.34× | 2.25× → 2.19× | 8.42× → 7.57× | 0.96 → 0.96 | | document | 1.92× → 1.82× | 1.82× → 1.77× | 3.17× → 2.78× | 0.62 → 0.57 | | explain | 1.48× → **1.59×** | 1.46× → **1.58×** | 2.30× → 2.29× | 0.38 → 0.44 | | story | 1.42× → 1.42× | 1.57× → 1.48× | 1.76× → **1.88×** (k = 4) | 0.37 → 0.39 | -Speedups follow tokens per step: the p/q verify costs no more than plain sampling per -column. Sampled drafts pay on the open "explain" prompt at every k (draft model k = 7: 1.13× -→ 1.33×) and lose 3–12 % on the code-documenting one; each row is a single sampled reply, -so a difference of one step moves it by several percent (DFlash k = 15 on rename: 10 → 11 -steps). Greedy drafts stay the default. Sampled drafts should gain more at higher -temperatures, where p(argmax q) falls faster than Σ min(p, q). - -## Weight-only INT8, and Apertus 1.5 8B (2026-10-31) - -`load_model(...; quantize = :int8)`, `--int8` (CLI), `--quantize int8` (bench/run.jl, keys -`-int8/...`): linear weights and the lm_head as Int8 with one Float32 scale per output -channel (symmetric, round to nearest, quantized on the GPU at load time); the embedding stays -BF16. Kernels accumulate the Int8 values in Float32 and scale the sums before the one -rounding to T: the GEMV (and its SwiGLU / xIELU epilogues) converts Int8 to Float32, the GEMM -converts Int8 tiles to BF16 for the tensor cores (|q| ≤ 127 is exact). - -- **GEMV tiles**: half the BF16 width. TK × TM ≈ 4096 Int8 elements per tile (TK = 1024, - TM = 4) was best on every Apertus 8B layer; BF16's TM = 8 was 7–13 % slower, TK ≥ 2048 with - TM ≥ 4 much slower. With it, the INT8 GEMVs run at 85–93 % of the roofline (qkv 91 %, o 87 %, - up + xIELU 91 %, down 85 %, lm_head 93 %). -- **Accuracy** (mean KL to the BF16 model over the fixture prompts; top-1 agreement): - Qwen3-0.6B 0.032 (46/50), Qwen3-4B 0.009 (49/50). Apertus 1.5 8B in INT8 against - transformers' Float32 run of the unquantized checkpoint on the CPU: argmax differs at 2 of - 103 positions, both near-ties (margins 0.2 and 0.02), and 24-token greedy continuations are - identical on all three prompts. - -End to end (`--seconds 2`, tile backend; decode at 1,024 positions): +The p/q kernels share the candidate selection with the plain sampler, which runs in the same +16.8 µs as before the refactor. -| | BF16 decode | INT8 decode | BF16 prefill 512 | INT8 prefill 512 | -|---|---|---|---|---| -| Qwen3-0.6B | 409 tok/s | 539 tok/s (1.32×) | 58.2k tok/s | 53.9k tok/s (0.92×) | -| Qwen3-4B | 77.7 tok/s | 136.9 tok/s (1.77×) | 11.4k tok/s | 10.1k tok/s (0.89×) | -| Apertus 1.5 8B | does not fit (16.1 GB) | 80.5 tok/s | — | 4.8k tok/s | +## Comparison with vLLM -Apertus 8B in INT8 holds 8.6 GB of weights (linear 7.0 GB, lm_head 0.54 GB, BF16 embedding -1.07 GB) and loads in 12 s. Its decode step (12.4 ms from a graph) reads ~7.5 GB of weights -plus the KV cache, ~82 % of the 736 GB/s roofline; the suite's 95 % counts the whole -embedding table as read, as it does for every model. INT8 prefill is 8–11 % slower than -BF16: the GEMM's Int8 → BF16 tile conversion is not hidden yet (down, K = 21504, is the -worst at 0.73× of its BF16 GEMM), so fused dequantization in the GEMM is the next lever. +Setup: the RTX 4080 SUPER also drove the desktop (compositor, VS Code and Discord on the +GPU); TileInfer at commit 8528c2e on Julia 1.13.3; vLLM 0.31.0 with torch 2.13.0 +(`bench/ref/requirements.txt`) with CUDA graphs and torch.compile; prefix caching off and one +sequence at a time. Scripts and setup in `bench/ref/README.md`. -## 16-token verify attention (2026-10-31) +**The race**: 512-token prompt, 256 greedy tokens, the same first tokens on both engines. +`bench/ref/alternate.py`: 3 rounds alternating the engines (ABBA order), each a fresh process +recording 10 trials of each latency; 30 trials per engine pooled. Median [q1, q3]: -Steps of 9–16 tokens (DFlash's verify block, and the drafter's own pass) ran the prefill -attention kernel: one block per query head walking every page, 16–32 blocks on 80 SMs, so -its time grows with the context (~1.7 µs per 64-key page). `DECODE_MAX_TOKENS` is now 16, -and those steps use the split-KV decode kernels with 8 splits (`VERIFY_SPLITS`) instead -of decode's 32: the combine merges every split, empty or not, and with 32 it set a floor -of 8 µs (0.6B) / 12 µs (4B) that lost to the prefill kernel below ~450 positions. The -choice cannot depend on the context, since a captured graph is replayed as it grows. +| | Qwen3-0.6B: vLLM | Qwen3-0.6B: TileInfer | Qwen3-4B: vLLM | Qwen3-4B: TileInfer | +|---|---|---|---|---| +| **End to end** (latency of 256 tokens) | **0.6439 s** [0.6419, 0.6476] | **0.6227 s** [0.6203, 0.6263] | **3.328 s** [3.296, 3.350] | **3.309 s** [3.300, 3.318] | +| 1-token request ("prefill") | 10.1 ms [9.9, 10.3] | 9.7 ms [9.6, 12.8] | 46.6 ms [45.5, 46.8] | 47.0 ms [45.4, 49.0] | +| Decode = (e2e − 1-token) / 255 | 2.49 ms/tok (402 tok/s) | 2.40 ms/tok (416 tok/s) | 12.87 ms/tok (77.7 tok/s) | 12.79 ms/tok (78.2 tok/s) | -16-token attention per layer, µs (CUPTI, both kernels of a path): +On 4B, vLLM's fastest round matches TileInfer's median (minimum 3.295 s against 3.299 s). +TileInfer has 1–3 slow 1-token trials per process (20–70 ms, and one of 200–250 ms in every +run, on both models), which widen its q3; vLLM has none. A traced repeat showed one such +trial spending 31 ms in GC and 37 ms compiling. -| positions | 0.6B prefill kernel | 0.6B decode, 32 splits | 0.6B 8 splits | 4B prefill kernel | 4B decode, 32 splits | 4B 8 splits | -|---|---|---|---|---|---|---| -| 128 | 4.5 | 8.3 | 5.5 | 4.8 | 12.4 | 6.7 | -| 256 | 7.6 | 7.6 | 5.3 | 8.1 | 12.2 | 6.7 | -| 512 | 14.3 | 7.9 | 5.7 | 14.8 | 12.6 | 7.2 | -| 1024 | 27.4 | 8.8 | 6.7 | 26.9 | 13.6 | 9.5 | -| 2048 | 53.4 | 11.2 | 9.8 | 53.6 | 17.4 | 14.3 | - -The decode kernel does not spill at 64 packed query rows (4B: group 4 × 16 tokens, 230 -registers). End to end on Qwen3-4B with DFlash k = 15 (`bench/speculative.jl`, greedy), -the time per step is unchanged within the noise (±2 %; k = 7, which this does not touch, -moved as much): the chat replies stop at 300–850 positions, where the saving is 0.2–0.4 ms -of a ~16.5 ms step. 32 splits with the same limit was 3.5 % slower on the rename prompt. -The gain grows with the context: ~1.4 ms per verify step at 2,048 positions (36 layers × -39 µs), ~8 % of a 4B verify, not measured end to end (the bench's replies are too short). - -Measured since on the two long prompts of `bench/speculative.jl` (a 2.2k-token Julia file, -`bench/prompts/runner.jl`, to edit or explain; replies of 256 tokens, so 2,230–2,480 -positions), greedy, `DECODE_MAX_TOKENS` 8 (before) against 16, same session: - -| Prompt | plain | DFlash k = 7 (control) | DFlash k = 15 before → after | ms per verify step | +**INT8.** vLLM runs a W8A16 compressed-tensors copy of each checkpoint quantized as +TileInfer's `quantize_int8` (`bench/ref/make_w8a16.py`: every linear and the untied lm_head), +with its Marlin kernels; its INT8 KV cache is `kv_cache_dtype = int8_per_token_head`, which +moves it to its Triton attention backend. Same race, end-to-end medians: + +| Latency of 256 tokens | 0.6B vLLM | 0.6B TileInfer | 4B vLLM | 4B TileInfer | |---|---|---|---|---| -| long-edit | 77.0 / 77.0 | 367.0 / 367.1 | 419.2 → **454.2** (+8.3 %) | 19.1 → 17.6 | -| long-explain | 77.0 / 77.0 | 182.7 / 182.6 | 153.7 → **169.4** (+10 %) | 18.9 → 17.3 | - -The ~1.5 ms per step matches the prediction. At these contexts the whole block still pays -on the edit prompt (8.0 tokens per step; 5.9× over plain) but not on the open one, where -k = 7 wins (2.37× vs 2.20×; 3.2 vs 2.9 tokens per step). Plain decoding runs at 77 tok/s -(80 on the short prompts), and the 2.2k-token prefill takes 203 ms (11k tok/s, ~78 -TFLOP/s; 91 at 512 tokens). Rows of one run compare; between the full run (every method) -and the DFlash-only runs, long-explain's DFlash rows differed by up to 11 %. - -## INT8 KV cache (2026-10-31) - -`PagedKVCache(model; quantize = :int8)` (`--kv-int8` in the CLI, `--kv int8` in bench/run.jl, -keys `-kvint8/...`): each cached key or value vector (one KV head at one position) as -Int8 with one Float32 scale, round to nearest, written once by the fused `attention_inputs` -kernel (`Int8Pages`, src/ops/quant.jl). Attention never dequantizes the cache: a key's scale -multiplies its row of scores after the QKᵀ product (Int8 tiles convert exactly to BF16 for -the tensor cores), and a value's scale multiplies its probability before the PV product. A -layer's keys and values share one Int8 array and one scale vector, so the kernels stay under -32 parameters (separate arrays would take the KV write kernel to 36). 132 bytes per vector -instead of 256 in BF16: Qwen3-4B holds 75k positions per GB instead of 39k. - -**Accuracy: smoothing the keys.** With one scale per vector, Qwen3-0.6B's mean KL to a BF16 -cache was 0.004–0.036 over the fixture prompts (INT8 weights: 0.032). The keys carry it: - -| Qwen3-0.6B, chat prompt | layer 1 K | layer 2 K | layer 14 K | layer 28 K | values (any layer) | -|---|---|---|---|---|---| -| relative error, one scale per vector | 0.022 | 0.025 | 0.011 | 0.020 | 0.007–0.013 | -| one scale per channel (KIVI) | 0.005 | 0.004 | 0.008 | 0.005 | 0.008–0.016 | -| per vector, keys smoothed by the k_norm weight | **0.003** | **0.004** | 0.011 | **0.006** | — | -| largest / median channel max | 109 | 43 | 6.5 | 11 | 1.6–5 | +| BF16 | 0.644 s | **0.623 s** (−3.3 %) | 3.328 s | 3.309 s (tie) | +| INT8 weights | 0.532 s | **0.503 s** (−5.5 %) | 1.880 s | 1.884 s (tie) | +| INT8 KV | 0.622 s | 0.625 s (tie) | **3.264 s** | 3.307 s (+1.3 %) | +| INT8 weights + KV | 0.474 s | 0.470 s (tie) | **1.837 s** | 1.871 s (+1.8 %) | + +With INT8 weights the first tokens can differ between the engines (vLLM stores the scales in +BF16, TileInfer in Float32). -A few key channels are ~100× the others, which leaves few levels for the rest; per-channel -scales do not fit a cache written one position at a time. In Qwen3 (and Apertus) these -channels come from the per-channel weight w of the key norm, k = rope(rmsnorm(k) w), so the -cache stores k / c with c = max(|w_i|, |w_j|) for each rotary pair (i, j): the same factor on -both channels a rotation mixes, so it commutes with rope. Scores are unchanged by multiplying -the queries by c in the attention kernels (qᵀk = (c q)ᵀ(k / c)). No calibration; one extra -multiply per query tile. Mean KL to a BF16 cache, and largest logit difference to -transformers (BF16 cache: 0.63): +**Speculative decoding, best configuration per engine.** `bench/ref/tileinfer_spec.jl` and +`bench/ref/vllm_spec.py` on `bench/speculative.jl`'s six prompts with the same token ids, +greedy, up to 256 tokens stopping at EOS, median of 5 trials; decode = (n − 1) / (latency(n) − +latency(1)). Each engine ran plain, DFlash k = 7 and k = 15 (4B), n-gram k = 4 (0.6B), each in +BF16 and with INT8 weights + KV; the table keeps each engine's fastest per prompt, which on +4B is DFlash k = 15 with INT8 for both, except TileInfer's k = 7 on long-explain: -| Qwen3-0.6B, tile backend | chat | prose | code | max logit diff | +| Qwen3-4B | vLLM tok/s (× its BF16 plain) | TileInfer tok/s (× its BF16 plain) | TileInfer / vLLM | tokens per step vLLM / TileInfer | |---|---|---|---|---| -| one scale per vector | 0.030 | 0.0089 | 0.0043 | 1.75 | -| smoothed keys (kept) | **0.0051** | **0.0040** | **0.0022** | **0.88** | +| rename | 1,150 (14.7×) | 947 (12.2×) | 0.82 | 11.0 / 10.0 | +| document | 385 (4.9×) | 379 (4.9×) | 0.98 | 3.9 / 4.0 | +| explain | 322 (4.1×) | 290 (3.7×) | 0.90 | 3.2 / 3.0 | +| story | 255 (3.2×) | 219 (2.8×) | 0.86 | 2.5 / 2.3 | +| long-edit (2.2k) | 494 (6.5×) | **698 (9.2×)** | **1.41** | 8.0 / 8.3 | +| long-explain (2.2k) | 158 (2.1×) | **270 (3.5×)** | **1.70** | 2.6 / 3.0 | -**Speed** (Qwen3-4B, `--seconds 2`; pipelined greedy decode, decode attention op per layer): +In BF16 on rename both engines take 10 steps for 110 tokens, at 731 tok/s (vLLM) and 558 +(TileInfer). At these short contexts vLLM's plain INT8 decode is 145 tok/s against +TileInfer's 139. On long-explain vLLM's DFlash reaches 158 tok/s against 134 for its plain +INT8 decode. -| | BF16 cache | INT8 cache | | -|---|---|---|---| -| decode at 1,024 positions | 78.7 tok/s | 78.1 tok/s | 0.99× (attention is 4 % of the step) | -| decode at 32,768 positions | 51.3 tok/s | **57.8 tok/s** | **1.13×** | -| decode attention at 32,768 positions | 209 µs (642 GB/s, 87 %) | 142 µs (489 GB/s, 66 %) | 1.48× for 0.52× the bytes | -| prefill 512 | 44.9 ms | 46.0 ms | 0.98× | - -The first INT8 attention kernel was not bandwidth-bound. Under `ncu` (32k positions): 255 -registers with local-memory spills (38 % of L1 traffic) and 3.1× the instructions of the -BF16 kernel (150 registers, no spills, 95 % of DRAM peak): the BF16 kernel feeds the MMAs -from shared memory, the INT8 one converts each (64, 128) tile to BF16 in registers. -Dropping the `latency` hints on its loads changed nothing. - -**Fixing the spills.** The probe `int8_attention` (bench/codegen/probes/08_int8_attention.jl, -[cuTile design choices](cutile_design.md)) converts K, V or both: either conversion alone fits (178 and 232 -registers), both together do not. Variants that fit, at 32k positions (probe kernel, mean µs): - -| Decode attention, Int8 K and V | µs | registers | spills | note | -|---|---|---|---|---| -| whole (64, 128) pages, as before | 117–123 | 255 | 56 B | | -| V stored transposed (PAGE, D) per page | 112 | 255 | 8 B | a different cache layout | -| Int8 QKᵀ: queries quantized per column, `mmai` | 109 | 206 | 0 | KL to the BF16 cache 0.0051 → 0.0070 (chat), max logit diff 0.88 → 2.0 | -| Int8 QKᵀ with two-term queries (q_hi + q_lo / 254) | 115 | 232 | 0 | the second MMA costs what it saves | -| 32-key tiles | 113 | 211 | 0 | | -| K and V in halves of the head dimension | 114 | 190 | 0 | | -| **32-key tiles and halves (kept)** | **111** | **184** | **0** | same numerics as before | - -Int8 QKᵀ (SageAttention's idea) is as fast but moves the key outliers back into the query -quantization: smoothing makes c q heavy-tailed, and Int8 queries cost the accuracy that -smoothing bought. The kernels now take 32 keys at a time and convert K and V in two halves of -the head dimension (`attend` for `Int8Pages` in src/ops/tile/attention.jl): the decode -kernel uses 191 registers and does not spill (prefill: 232 → 218). The numerics are those of -the whole-page kernel up to the order of the sum over the head dimension. Qwen3-4B -(`--kv int8`, `--seconds 2`, tile backend): - -| | before | after | | -|---|---|---|---| -| decode attention at 32,768 positions | 149.7 µs (463 GB/s) | **119.2 µs (581 GB/s, 79 %)** | 1.26× | -| prefill-512 attention (1,024 and 32,768 positions) | 83.7 µs | 66.8 µs | 1.25× (0.6B: 1.28×) | -| decode attention at 1,024 positions | 15.7 µs | 15.7 µs | launch-bound | -| decode step at 32,768 positions (graph) | ~17.7 ms | **16.42 ms (60.9 tok/s)** | 1.08×; 1.19× the BF16 cache (51.3 tok/s) | -| prefill 512 | 46.2 ms | 45.8 ms | 1.01×: attention is ~3 % of it | - -The BF16 kernels are unchanged (same times, both models). - -## INT8 GEMM tiles (2026-10-31) - -INT8 prefill was 8–11 % slower than BF16 although it reads half the weight bytes, and at 64 -tokens, where a GEMM is bandwidth-bound, the INT8 GEMMs were 0.68–1.13× BF16. Under `ncu` -(Qwen3-4B down): at 512 tokens 255 registers and 1.6× BF16's instructions (byte shuffles -and conversions of the weight tile); at 64 tokens 29 % of DRAM peak against BF16's 90 %, -with 37 % of the stall samples on the conversion waiting for its global load: the Int8 -tile is not staged through shared memory and overlapped like the BF16 operands. Neither -`latency` hints on the weight loads (1–8) nor swapping the operands (Xᵀ W, the weight in its -natural layout as the B operand) helped. Tiles and occupancy did: a sweep of 15 tiles × -occupancy 1, 2 on the layers of Qwen3-0.6B, Qwen3-4B and Apertus 8B at n = 8, 64, 512 found -the latency-bound INT8 blocks always want two per SM, narrower tiles than BF16 at 512 tokens -(128 × 64 × 64), and at ≤ 64 tokens deeper K steps (32 × 32 × 256, or 64 × 64 × 128 on large -grids). `gemm_int8_config` encodes that: within 1.5 % of the best tile summed over the sweep -(worst case 1.11×), 1.23× faster than BF16's rule. Qwen3-4B, `--seconds 2`: - -| | before | after | BF16 | -|---|---|---|---| -| GEMMs at 64 tokens (qkv / o / gate_up / down) | 72 / 46 / 155 / 126 µs | 44 / 26 / 99 / 62 µs (1.57–2.03×) | 60 / 36 / 175 / 85 µs | -| GEMMs at 512 tokens | 237 / 155 / 580 / 369 µs | 196 / 127 / 567 / 284 µs (1.02–1.30×) | 203 / 116 / 521 / 266 µs | -| prefill 64 | — | **9.55 ms (1.52× BF16)** | 14.49 ms | -| prefill 512 | 10.1k tok/s (0.89× BF16) | **11.07k tok/s (0.97× BF16)** | 11.40k tok/s | - -At 512 tokens INT8 is still a few percent behind: the conversion in registers stays. A -weight layout prepacked for the conversion (as Marlin does), or conversion by bit tricks -(Int8 bytes into Float32 mantissas with a magic exponent) would be the next step. - -## DFlash without a host round trip (2026-10-31) - -A DFlash step was: drafter step, host waits for the drafts and uploads them into the verify -step, verify step, host waits for the target's tokens. Now the drafter's sampling writes the -drafts into a device vector (`propose_on_device!`), and `verify!(…; drafts)` copies them into -the verify step's ids on the stream, after the upload of its other inputs: the host enqueues -both steps back to back and waits once, after the verify step. The second wait remains: the -host needs the accepted count to truncate the cache and to pick the next drafter graph (one -per context length). The drafter's 15 per-position sampling calls (30 launches) became one -batched `sample_tokens!` (three launches: candidates over a (chunk, column) grid, one block -per column sampling with counter c + j − 1, and a one-block kernel advancing the counter, which -no block of the sampling kernel may do while others read it); same tokens and distributions -as the per-column calls. - -Under the tracer (Qwen3-4B, k = 15, "explain"): GPU idle time inside generation fell 2.8×, -sampling 0.086 → 0.050 ms per step. End to end (`bench/speculative.jl`, greedy, same tokens and -steps before and after): - -| Prompt | DFlash k = 7 | DFlash k = 15 | +On Qwen3-0.6B (no DFlash drafter), with INT8 the greedy replies differ in length between the +engines on two prompts, and TileInfer's reply to long-edit ends after 5 tokens. Where the +replies match, best configuration per engine: + +| Qwen3-0.6B | vLLM | TileInfer | +|---|---|---| +| rename | 1,236 tok/s (n-gram + INT8) | **1,725** (n-gram + INT8) | +| explain | **606** (plain INT8) | 563 (plain INT8) | +| long-explain | 469 (plain INT8) | **588** (n-gram + INT8) | +| story, BF16: n-gram / plain | 298 / 405 | 413 / 428 | + +vLLM counts only the steps that had drafts, so its n-gram tokens per step are left out. + +## What is left to gain + +Measured costs that a change could recover, largest first within each group. The plan is in +[History and roadmap](roadmap.md#Next). + +| Where | Measured | Lever | |---|---|---| -| rename | — | 662.8 → 670.5 tok/s (+1.2 %) | -| explain | 192.5 → 194.8 (+1.2 %) | 202.2 → 204.9 (+1.3 %) | -| long-explain (2.2k tokens) | 182.6 → 184.7 (+1.2 %) | 169.4 → 171.5 (+1.2 %) | - -As the step times predicted (3.17 ms drafting + 13.3 ms verify ≈ the 16.6 ms step), the host -was already mostly hidden: the round trip cost ~0.2 ms of a 16.5 ms step. What remains is the -step's own GPU time; the bigger lever for DFlash is choosing k per prompt (k = 7 beats 15 at long -contexts on open text) or verifying a tree of drafts. +| **Decode** | | | +| 0.6B GEMVs (layers of 4–12 MB each, and the lm_head) | 1,898 µs per token against a 1,619 µs floor (~11 % of the token) | fill and drain of small kernels: persistent or stream-K GEMVs (Ada has no programmatic dependent launch) | +| Small decode kernels | 0.6B 233 µs (9.5 %), 4B 409 µs (3.2 %) | fewer launches: q and kv inputs in one kernel, norms in GEMV epilogues | +| Decode attention at 1k positions | 0.6B 308 µs against ~160 to read the KV once (~6 %) | latency-bound, about one page per split | +| 4B layer GEMVs | 90–93 % of DRAM against the lm_head's 95 % (~3 %) | | +| INT8 decode GEMV | vLLM's Marlin kernels 4–7 % faster at short contexts | | +| **Prefill** | | | +| 512-token GEMMs | 0.88–0.96× cuBLAS (0.6B down 0.72×); 4B: 40.0 ms against 37.9 at cuBLAS speed | larger tiles or split-K for under-filled grids (0.6B down: 64 blocks for 80 SMs) | +| `q_inputs_kernel` at 512 tokens | 0.6B 448 µs (5.2 %) | several tokens per block | +| Short eager prefills | 0.6B prefill64: GPU idle 12 % of the step | a graph, or fewer launches | +| `silu_mul` | 4B prefill512 625 µs (1.4 %) | SwiGLU epilogue in the gate_up GEMM, as in the GEMV | +| INT8 GEMMs at 512 tokens | 0.98× BF16 on 4B (gate_up 567 against 521 µs, down 284 against 266) | weight layout prepacked for the conversion, as Marlin does | +| **Speculative decoding and host** | | | +| DFlash step at short contexts | vLLM 1.31× faster with the same steps (731 against 558 tok/s on rename, BF16) | not profiled | +| k per prompt | long-explain: k = 7 beats 15 (2.37× against 2.20×) | adaptive k, tree verification ([Speculative decoding](speculative.md#Not-built-yet)) | +| Host pauses | 1–3 slow requests per process, 20–250 ms (GC and compilation) | | diff --git a/docs/src/roadmap.md b/docs/src/roadmap.md index db99717..edc0ddc 100644 --- a/docs/src/roadmap.md +++ b/docs/src/roadmap.md @@ -3,7 +3,7 @@ TileInfer was built in milestones, each a working engine that the next one sped up or extended. This page shows where it stands, how it got there, and what comes next. The measurements behind every step, including the ideas that did not pan out, are in the -[Performance log](performance.md). +[Results by feature](performance.md). ## Where it stands @@ -12,9 +12,9 @@ RTX 4080 SUPER, in BFloat16, with decode measured after 1,023 cached positions: | | Qwen3-0.6B | Qwen3-4B | |---|---|---| -| Decode | 395 tok/s (70 % of the bandwidth roofline) | 77 tok/s (86 %) | -| Decode with INT8 weights | 539 tok/s | 137 tok/s | -| Prefill, 512-token prompt | 58k tok/s | 11.3k tok/s (91 TFLOP/s) | +| Decode | 409 tok/s (73 % of the bandwidth roofline) | 79 tok/s (88 %) | +| Decode with INT8 weights | 542 tok/s | 139 tok/s | +| Prefill, 512-token prompt | 58k tok/s | 11.4k tok/s (91 TFLOP/s) | | Speculative decoding (DFlash) | — | 1.8× to 3.2× on open prompts, 8.5× on a code edit | Models: Llama 3, Mistral, Qwen3 and Apertus (Apertus 1.5 8B runs on 16 GB with INT8 @@ -63,8 +63,8 @@ help. | 2026-10-31 | DFlash drafts handed to the verify step on the device | +1.2 % | | 2026-11-01 | EAGLE-3 proposer removed | DFlash beat it on every prompt | -The M8 target is 80 % of the decode bandwidth roofline: met on Qwen3-4B (86 %), not on -Qwen3-0.6B (70 %), where per-kernel overheads weigh more. +The M8 target is 80 % of the decode bandwidth roofline: met on Qwen3-4B (88 %), not on +Qwen3-0.6B (73 %), where per-kernel overheads weigh more. ## Next diff --git a/docs/src/speculative.md b/docs/src/speculative.md index d51a509..51cd3b6 100644 --- a/docs/src/speculative.md +++ b/docs/src/speculative.md @@ -91,7 +91,7 @@ short contexts, even though per-draft acceptance drops. An EAGLE-3 proposer (one drafter layer on three target layers' states, chained one token at a time) was built and removed: DFlash, which reads the same kind of states, beat it on every -prompt. Its results are kept in the [Performance log](performance.md). +prompt. Its results are kept in [Results by feature](performance.md#Speculative-decoding). ## Results @@ -109,8 +109,8 @@ With Qwen3's recommended sampling (temperature 0.6, top-k 20, top-p 0.95) the pi same: DFlash gains 1.75× to 3.17× on the three prompts other than the rename. On a 2.2k-token prompt, the code edit still reaches 5.9× with the whole block, while explaining it is faster at k = 7 (2.4×) than at k = 15 (2.2×): at long contexts verify steps cost more, and the late drafts of open text are -rarely accepted. More numbers, and what each change gained, are in the -[Performance log](performance.md). +rarely accepted. Per-k numbers, step costs and the other proposers are in +[Results by feature](performance.md#Speculative-decoding). ## Not built yet From ce5d8c1a63752e41dd7ae76f771746b58a2fe90e Mon Sep 17 00:00:00 2001 From: Antoine Buttier Date: Sun, 1 Nov 2026 19:00:26 +0100 Subject: [PATCH 3/3] README: quick start, features, performance and documentation overview Co-Authored-By: Claude Opus 5.5 --- README.md | 100 +++++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 91 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index c9bed39..5c1bfbe 100644 --- a/README.md +++ b/README.md @@ -10,9 +10,11 @@ GEMV/GEMM, paged flash-attention, fused norms and RoPE, and device sampling. Eve around them is plain Julia: safetensors loading, a byte-level BPE tokenizer, a paged KV cache, CUDA graphs and speculative decoding (n-gram, draft model, DFlash). -**This is not production software.** It serves one conversation on one GPU, supports a few -Llama-style model families (Llama 3, Mistral, Qwen3, Apertus), and has only been tuned on an -RTX 4080 SUPER. The code aims to be easy to read and measure, not to be feature-complete. +The code aims to be easy to read and to measure: each kernel has a reference +implementation it is tested against, a benchmark, and an entry in the performance page +saying what it gained. + +## Quick start ```sh git clone https://github.com/AntoineBut/TileInfer.jl && cd TileInfer.jl @@ -21,10 +23,90 @@ julia --project -m TileInfer pull Qwen/Qwen3-0.6B julia --project -m TileInfer chat Qwen/Qwen3-0.6B ``` -Requires Julia 1.13 and an NVIDIA GPU that cuTile.jl supports. +Requires Julia 1.13 and an NVIDIA GPU that cuTile.jl supports. Qwen3-0.6B fits on any +card, Qwen3-4B needs about 9 GB, and 8B models need `--int8` on a 16 GB card. + +Other commands: `run` for a single prompt, `ls` and `rm` to manage pulled models, +`help` for every option (sampling, context size, INT8 weights and KV cache, speculative +decoding). Models are stored in the Hugging Face hub cache, shared with Python's +`huggingface_hub`. To install a `tileinfer` executable instead of going through +`julia --project -m TileInfer`, run `julia --project -e 'using Pkg; Pkg.Apps.develop(path = ".")'`. + +From Julia: + +```julia +using TileInfer +using TileInfer: pull, load_model, load_tokenizer, ChatSession, reply! + +dir = pull("Qwen/Qwen3-0.6B") +model = load_model(dir; backend = TileBackend()) +session = ChatSession(model, load_tokenizer(dir); enable_thinking = false) +reply, stats = reply!(session, "Name three primary colors.") +``` + +## What is inside + +- **Models**: Llama 3, Mistral, Qwen3 and Apertus checkpoints from the Hugging Face hub, + in BFloat16, with optional weight-only INT8 and an INT8 KV cache. +- **Two backends**: every op has a reference implementation (CUDA.jl broadcasts and + cuBLAS), which is the ground truth in tests, and a cuTile implementation. Float32 runs + match the Hugging Face `transformers` logits to ~1e-4. +- **Engine**: a paged KV cache with prefix reuse across chat turns, allocation-free decode + steps replayed from CUDA graphs, sampling on the device, and a host that runs one step + behind the GPU. +- **Speculative decoding**: n-gram lookup, a draft model, or a + [DFlash](https://arxiv.org/abs/2602.06036) block drafter, with exact verification for + both greedy and sampled decoding. +- **Tooling**: per-op and end-to-end benchmarks, a per-kernel breakdown of real steps, + Nsight Compute profiling scripts, and codegen probes that compare equivalent cuTile + kernels down to their SASS. + +## Performance + +On an RTX 4080 SUPER (the card it is tuned on), in BFloat16, with decode measured after +1,023 cached positions: + +| | Qwen3-0.6B | Qwen3-4B | +|---|---|---| +| Decode | 409 tok/s (73 % of the bandwidth roofline) | 79 tok/s (88 %) | +| Decode with INT8 weights | 542 tok/s | 139 tok/s | +| Prefill, 512-token prompt | 58k tok/s | 11.4k tok/s (91 TFLOP/s) | +| Speculative decoding (DFlash) | — | 1.8× to 3.2× on open prompts, 8.5× on a code edit | + +Apertus 1.5 8B runs on the same 16 GB card with INT8 weights, at 80 tok/s. + +The engine was built in milestones, each a working engine that the next one sped up: +reference ops on cuBLAS (26 tok/s on Qwen3-0.6B), then cuTile kernels, paged +flash-attention, CUDA graphs, and fused kernels with device sampling (409 tok/s). The +[performance page](docs/src/performance.md) records what each feature gains, including the +optimizations that did not pan out. + +## Documentation + +The **[documentation](https://antoinebut.github.io/TileInfer.jl/dev/)** covers: + +- [Getting started](docs/src/usage.md): the command line and the Julia API. +- [Architecture](docs/src/architecture.md): the layers of the engine, from the command line + down to the kernels, and how they map to vLLM's; with pages on the + [KV cache](docs/src/kv_cache.md), the [attention kernels](docs/src/attention.md) and + [speculative decoding](docs/src/speculative.md). +- [History and roadmap](docs/src/roadmap.md): milestones so far and what comes next. +- [Profiling](docs/src/profiling.md) and [cuTile design choices](docs/src/cutile_design.md): + how kernels are measured, and the codegen rules learned along the way. +- [References](docs/src/references.md): papers, engines and package sources this builds on. + +## Development + +```sh +julia --project=test test/runtests.jl # full test suite, ~4 min +julia --project=test test/runtests.jl kernels # only matching test files +julia --project=bench bench/run.jl --model Qwen/Qwen3-0.6B # op and model benchmarks +julia --project=docs docs/make.jl # documentation site, no GPU needed +``` + +Tests that need a real checkpoint are skipped until `Qwen/Qwen3-0.6B` is pulled. Golden +outputs from the Hugging Face reference implementations live in `test/fixtures/`. + +## License -Read the **[documentation](https://antoinebut.github.io/TileInfer.jl/dev/)** for the -Julia API, the [architecture](docs/src/architecture.md), the -[history and roadmap](docs/src/roadmap.md), and the -[performance log](docs/src/performance.md), which records what each optimization gained, -including the ones that did not pan out. +MIT, see [LICENSE](LICENSE).