lfm3: round 6 - GPTQ INT4 baked (INT4 lm_head + INT8 embedding)
- quant/gptq_baked/: llm-compressor GPTQ W4A16 body (sequential pipeline, verified equal to the plain forward), B65-style GPTQ INT4 lm_head bake with a small damp/act-order/clipping grid, INT8 per-row embedding, assembly into one compressed-tensors checkpoint (1.155 GB vs 3.46 GB BF16) - plugin: pass quant_config to the token embedding so vLLM's compressed-tensors INT8 embedding path is used; BF16/FP8 greedy output unchanged - tests: INT8 embedding kernel check, quant method dump, head timing, round-6 driver - NOTES: round 6 results (PPL +8.1%, decode 217 t/s = FP8 pc +14%, head bake gives no measurable decode gain on this stack), llama-swap snippet (not applied) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
1115927570
commit
38b0e9a345
110 files changed
+118917
-3
No files matched your search
@@ -8,7 +8,7 @@ echo "| variant | decode t/s | eff. bandwidth | ITL 1% low t/s | TTFT p50 ms | a
|
||||
echo "|---|--:|--:|--:|--:|--:|--:|"
|
||||
for arg in "$@"; do
|
||||
label=${arg%%=*}; f=${arg#*=}
|
||||
BETTERBENCH_HOME=$PWD/.betterbench .venv-bench/bin/betterbench report "$f" 2>/dev/null | python3 -c '
|
||||
BETTERBENCH_HOME=$PWD/.betterbench ${BB:-$( [ -x .venv-bench/bin/betterbench ] && echo .venv-bench/bin/betterbench || echo betterbench)} report "$f" 2>/dev/null | python3 -c '
|
||||
import re, sys
|
||||
t = sys.stdin.read(); label = sys.argv[1]
|
||||
m = re.search(r"decode t/s median ≈ \*\*([\d.]+)\*\*, ITL 1%-low ≈ \*\*([\d.]+) t/s\*\*, TTFT p50 ≈ \*\*([\d.]+) ms", t)
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Time the logits step alone (compute_logits = lm_head GEMM + logits processor) and the embedding
|
||||
lookup of a served LFM3 checkpoint at decode shape (1 token) and batch 8, eager, XPU-synchronized median.
|
||||
python3 tests/head_timing.py MODEL_DIR (inside the image, VLLM_ALLOW_INSECURE_SERIALIZATION=1)
|
||||
"""
|
||||
import sys, time
|
||||
import torch
|
||||
from vllm import LLM
|
||||
|
||||
|
||||
def bench(m):
|
||||
out = {}
|
||||
for n in (1, 8):
|
||||
h = torch.randn(n, m.config.hidden_size, dtype=torch.bfloat16, device="xpu")
|
||||
ids = torch.randint(0, m.config.vocab_size, (n,), device="xpu")
|
||||
for name, fn in {"compute_logits": lambda: m.compute_logits(h),
|
||||
"embed": lambda: m.model.embed_input_ids(ids)}.items():
|
||||
for _ in range(20):
|
||||
fn()
|
||||
ts = []
|
||||
for _ in range(200):
|
||||
torch.xpu.synchronize(); t0 = time.perf_counter(); fn(); torch.xpu.synchronize()
|
||||
ts.append(time.perf_counter() - t0)
|
||||
out[f"{name} n={n}"] = f"{sorted(ts)[len(ts) // 2] * 1e3:.3f} ms"
|
||||
return out
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
llm = LLM(sys.argv[1], enforce_eager=True, gpu_memory_utilization=0.3, max_model_len=4096)
|
||||
with torch.no_grad():
|
||||
print(llm.apply_model(bench)[0])
|
||||
@@ -0,0 +1,26 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Print which quantization method / kernel vLLM picked for lm_head, embed_tokens, gate_proj and a
|
||||
body linear of a served LFM3 checkpoint (the server log names the INT4 kernel only once).
|
||||
python3 tests/quant_methods.py MODEL_DIR (inside the image, needs VLLM_ALLOW_INSECURE_SERIALIZATION=1)
|
||||
"""
|
||||
import sys
|
||||
from vllm import LLM
|
||||
|
||||
|
||||
def describe(m):
|
||||
lm, e, attn = m.lm_head, m.model.embed_tokens, m.model.layers[2].self_attn
|
||||
|
||||
def kernel(layer):
|
||||
k = getattr(getattr(layer, "scheme", None), "kernel", None)
|
||||
return f"{type(layer.quant_method).__name__}" + (f" / {type(k).__name__}" if k is not None else "")
|
||||
|
||||
return {"lm_head": kernel(lm), "embed_tokens": kernel(e), "gate_proj": kernel(attn.gate_proj),
|
||||
"qkv_proj": kernel(attn.qkv_proj),
|
||||
"lm_head params": {n: (tuple(p.shape), str(p.dtype)) for n, p in lm.named_parameters()},
|
||||
"embed params": {n: (tuple(p.shape), str(p.dtype)) for n, p in e.named_parameters()}}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
llm = LLM(sys.argv[1], enforce_eager=True, gpu_memory_utilization=0.3, max_model_len=4096)
|
||||
for k, v in llm.apply_model(describe)[0].items():
|
||||
print(f"{k}: {v}")
|
||||
Executable
+27
@@ -0,0 +1,27 @@
|
||||
#!/usr/bin/env bash
|
||||
# Round 6: one variant end to end on :8001 (compile + graphs, vLLM default): start (tests/variant.sh),
|
||||
# kernel/memory lines from the server log, greedy 64-token check vs BF16 eager, eval_quality (PPL + 8
|
||||
# prompts), BetterBench with the round 2-5 invocation, stop.
|
||||
# tests/round6_variant.sh NAME MODEL_DIR [extra vllm args...]
|
||||
# Image: ${IMAGE:-lfm3-vllm-xpu:v0.32.0-lfm3-baked}. Outputs: results/round6/{NAME.serve.txt,greedy_NAME.json,eval/results_NAME.json,
|
||||
# bb/NAME.json}, logs/{variant,greedy,eval,bb}_NAME.log.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
NAME=$1 MODEL=$2; shift 2
|
||||
export IMAGE=${IMAGE:-lfm3-vllm-xpu:v0.32.0-lfm3-baked} MODEL
|
||||
BB_CONFIG=${BB_CONFIG:-/srv/llm/bench/bench-standard/dev/config.json}
|
||||
mkdir -p results/round6/bb
|
||||
trap 'docker stop -t 30 "lfm3-var-$NAME" >/dev/null 2>&1 || true' EXIT
|
||||
|
||||
tests/variant.sh "$NAME" "$@"
|
||||
grep -E "LinearKernel|Using .*Kernel|kernel|Model loading took|KV cache|quantization|Embedding" "logs/variant_$NAME.log" \
|
||||
| grep -v -i "warn.*deprecat" > "results/round6/$NAME.serve.txt" || true
|
||||
cat "results/round6/$NAME.serve.txt"
|
||||
python3 tests/greedy_variant.py 8001 "results/round6/greedy_$NAME.json" results/variants/greedy_eager.json \
|
||||
| tee "logs/greedy_$NAME.log"
|
||||
python3 eval/eval_quality.py 8001 "$NAME" | tee "logs/eval_$NAME.log"
|
||||
mkdir -p results/round6/eval && mv "eval/results_$NAME.json" results/round6/eval/
|
||||
betterbench run --no-update-check --endpoint http://127.0.0.1:8001/v1 --model lfm3-1.7b \
|
||||
--config "$BB_CONFIG" --quick --max-model-len 32768 --note "variant=$NAME" \
|
||||
--out "results/round6/bb/$NAME.json" > "logs/bb_$NAME.log" 2>&1
|
||||
tail -3 "logs/bb_$NAME.log"
|
||||
@@ -0,0 +1,54 @@
|
||||
#!/usr/bin/env python3
|
||||
"""INT8 embedding (compressed-tensors, per-row scale) on XPU: vLLM 0.32's own dequant-gather kernel
|
||||
(CompressedTensorsEmbeddingWNA16Int, used by our Lfm3Model.embed_tokens for INT8 checkpoints) vs a
|
||||
BF16 lookup. Two checks:
|
||||
1. kernel == F.embedding(dequantized weight) for the gathered rows (bit-exact expected: same
|
||||
int * scale product, rounded to BF16 once);
|
||||
2. error vs the original BF16 embedding (quantization error only).
|
||||
Run inside the image: python3 tests/test_embed_int8.py [EMBED_INT8.safetensors] [MODEL_DIR]
|
||||
Without arguments it uses a random 128000 x 2048 weight.
|
||||
"""
|
||||
import sys
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from compressed_tensors.compressors.pack_quantized.helpers import pack_to_int32
|
||||
from vllm.model_executor.layers.quantization.compressed_tensors.compressed_tensors_embedding import (
|
||||
_dequant_gather_triton,
|
||||
)
|
||||
|
||||
dev = "xpu"
|
||||
torch.manual_seed(0)
|
||||
if len(sys.argv) > 2:
|
||||
from safetensors import safe_open
|
||||
with safe_open(sys.argv[1], "pt") as f:
|
||||
packed = f.get_tensor("model.embed_tokens.weight_packed").to(dev)
|
||||
scale = f.get_tensor("model.embed_tokens.weight_scale").to(dev)
|
||||
with safe_open(f"{sys.argv[2]}/model.safetensors", "pt") as f:
|
||||
W = f.get_tensor("model.embed_tokens.weight").to(dev)
|
||||
codes = None
|
||||
else:
|
||||
W = (torch.randn(128000, 2048) * 0.02).to(torch.bfloat16).to(dev)
|
||||
s = (W.float().abs().amax(1) / 127).clamp_min(1e-8).to(torch.bfloat16)
|
||||
codes = torch.clamp(torch.round(W.float() / s.float()[:, None]), -128, 127).to(torch.int8)
|
||||
packed, scale = pack_to_int32(codes.cpu(), 8, packed_dim=1).to(dev), s[:, None].to(dev)
|
||||
|
||||
V, K = W.shape
|
||||
# unpack all rows once (reference path): 4 int8 per int32, LSB first, offset 128
|
||||
u = packed.view(torch.uint8).view(V, K).to(torch.int16) - 128
|
||||
if codes is not None:
|
||||
assert torch.equal(u.to(torch.int8), codes), "pack/unpack mismatch"
|
||||
deq = (u.float() * scale.float()).to(torch.bfloat16)
|
||||
|
||||
ids = torch.cat([torch.randint(0, V, (4096,)), torch.tensor([0, 1, V - 2, V - 1, 124893, 124900])]).to(dev)
|
||||
out = _dequant_gather_triton(ids, packed, scale, K, 8)
|
||||
ref_deq = F.embedding(ids, deq)
|
||||
ref_bf16 = F.embedding(ids, W)
|
||||
exact = torch.equal(out, ref_deq)
|
||||
max_d = (out.float() - ref_deq.float()).abs().max().item()
|
||||
rel = ((out.float() - ref_bf16.float()).norm() / ref_bf16.float().norm()).item()
|
||||
cos = F.cosine_similarity(out.float(), ref_bf16.float(), dim=1).min().item()
|
||||
print(f"kernel vs dequantized lookup: {'bit-exact' if exact else f'max |d| {max_d:.3g}'}")
|
||||
print(f"vs BF16 embedding: relative L2 {rel:.4%}, min row cosine {cos:.6f} ({len(ids)} rows, dtype {out.dtype})")
|
||||
assert out.dtype == torch.bfloat16 and max_d <= 2 ** -7 * ref_deq.float().abs().max().item()
|
||||
assert rel < 0.02
|
||||
print("PASS")
|
||||
Reference in new issue
Block a user