Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ LocalPreferences.toml
bench/results/
*.cov
coverage/
bench/ref/
bench/ref/.venv/
bench/ref/models/
__pycache__/
docs/build/
bench/ref/results/
3 changes: 2 additions & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,13 @@ 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
```

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.
Expand Down
100 changes: 91 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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).
29 changes: 29 additions & 0 deletions bench/ref/README.md
Original file line number Diff line number Diff line change
@@ -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/<date>/` (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/<date>/` (~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`).
122 changes: 122 additions & 0 deletions bench/ref/alternate.py
Original file line number Diff line number Diff line change
@@ -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()
92 changes: 92 additions & 0 deletions bench/ref/make_w8a16.py
Original file line number Diff line number Diff line change
@@ -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/<name>-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()
Loading
Loading