kld_eval_vllm.py: keep a position to score, compare vocabularies, build score requests per batch

- Prompts leave one context position for the token the scoring pass generates; a prompt and
  continuation that filled the context could not be scored.
- The tokenizer check compares the whole vocabulary, not only its size.
- Scoring builds each batch's prompt_logprob_token_ids as it submits it, and the parent turns each
  prompt's scores into its KL as they arrive; a stopped or interrupted caller kills the child.
- The KV-cache line reports vLLM's K/V scale range instead of warning on unit scales, which the
  exporter writes on purpose for FP8 and the *_cast formats.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Ajinkya Rasane <131806219+ajrasane@users.noreply.github.com>
This commit is contained in:
Ajinkya Rasane
2026-12-03 17:52:59 -05:00
co-authored by Claude Opus 5.5
parent c97f6d6603
commit 1c42ded187
3 changed files with 65 additions and 42 deletions
+1 -1
View File
@@ -791,7 +791,7 @@ python kld_eval_vllm.py --base_ckpt_path <model> --quantized_ckpt_path <export>
The base checkpoint writes greedy continuations of the first `--kld_num_examples` (300) chat prompts from `--kld_dataset` ([nvidia/balanced-benchmark-prompts-short-1000](https://huggingface.co/datasets/nvidia/balanced-benchmark-prompts-short-1000)), up to `--kld_max_new_tokens` (1024) tokens each, stopping at the EOS tokens of its generation config. Both checkpoints then read each prompt and its continuation back without generating. At `--kld_score_tokens` (512) evenly spaced positions per continuation, the score is the conditional top-k KL(base ‖ quantized): both distributions are renormalized over the base checkpoint's `--kld_top_k` (2048) most likely tokens, and the KL is averaged within each prompt and then across prompts. A lower score means the quantized checkpoint stays closer to the base checkpoint. Because of the renormalization, probability the quantized checkpoint moves to tokens outside the top-k set does not raise the score. The score covers the kernels and KV cache vLLM serves the quantized checkpoint with.
Each checkpoint runs in its own process, one after the other, on `--tensor_parallel_size` GPUs. `--kld_generation_batch_size` (64) caps how many sequences vLLM runs at once, and `--trust_remote_code` runs checkpoints that ship their own model code. The script prints the KV-cache quantization the quantized checkpoint declares and the KV-cache dtype vLLM uses, and warns when vLLM leaves that quantization out or keeps none of the checkpoint's KV-cache scales. It refuses a quantized checkpoint whose tokenizer reads the prompts differently from the base checkpoint's, and writes no file of its own, though Hugging Face may cache the dataset. It needs `datasets` but not ModelOpt.
Each checkpoint runs in its own process, one after the other, on `--tensor_parallel_size` GPUs. `--kld_generation_batch_size` (64) caps how many sequences vLLM runs at once, and `--trust_remote_code` runs checkpoints that ship their own model code. The script prints the KV-cache quantization the quantized checkpoint declares and the KV-cache dtype and scale range vLLM uses, and warns when vLLM leaves that quantization out. It refuses a quantized checkpoint whose tokenizer reads the prompts differently from the base checkpoint's, and writes no file of its own, though Hugging Face may cache the dataset. It needs `datasets` but not ModelOpt.
The default dataset is private to the NVIDIA organization on Hugging Face. Without access, pass `--kld_dataset` with any dataset whose `test` split has a chat `messages` column.
+42 -36
View File
@@ -96,15 +96,16 @@ def main(args):
prompts, max_model_len = load_prompts(args)
eos = eos_token_ids(args.base_ckpt_path, args.trust_remote_code)
reference = _in_process(_reference, args, prompts, eos, max_model_len)
reference = list(_in_process(_reference, args, prompts, eos, max_model_len))
requests = [
(p + c, len(p) - 1, positions, ids) for p, (c, positions, ids, _) in zip(prompts, reference)
]
scored = _in_process(_score, args, requests, max_model_len)
# Each prompt's scores become its KL as they arrive, so they are never all held at once.
total = sum(
kld_eval.conditional_kl(torch.from_numpy(log_p), torch.from_numpy(log_q)).item()
for (_, _, _, log_p), log_q in zip(reference, scored)
for (_, _, _, log_p), log_q in zip(
reference, _in_process(_score, args, requests, max_model_len), strict=True
)
)
print(f"Conditional top-k KL: {kld_eval.check_finite(total / len(prompts)):.6f} nats")
@@ -122,22 +123,22 @@ def load_prompts(args):
for p in paths
]
limit = min((n for n in limits if n), default=None)
# A scoring pass reads prompt and continuation, then generates one token: keep it a position.
room = None if limit is None else limit - 1
tokenized = []
for path in paths:
tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=args.trust_remote_code)
prompts = kld_eval.load_prompts(
tokenizer, args.kld_dataset, args.kld_num_examples, args.kld_max_new_tokens, limit
tokenizer, args.kld_dataset, args.kld_num_examples, args.kld_max_new_tokens, room
)
tokenized.append((len(tokenizer), prompts))
tokenized.append((tokenizer.get_vocab(), prompts))
if tokenized[0] != tokenized[1]:
raise ValueError(
"The quantized checkpoint's tokenizer differs from the base checkpoint's: "
f"{tokenized[1][0]} tokens against {tokenized[0][0]}, or different prompt token ids."
"another vocabulary, or other prompt token ids."
)
prompts = tokenized[0][1]
# A scoring pass reads prompt and continuation, then generates one token.
needed = max(map(len, prompts)) + args.kld_max_new_tokens + 1
return prompts, needed if limit is None else min(needed, limit)
return prompts, max(map(len, prompts)) + args.kld_max_new_tokens + 1
def eos_token_ids(path, trust_remote_code):
@@ -226,7 +227,7 @@ def _reference(args, prompts, eos, max_model_len):
k = _top_k(args, llm)
top_k = SamplingParams(max_tokens=1, prompt_logprobs=k, flat_logprobs=True, detokenize=False)
sequences = [p + c for p, c in zip(prompts, continuations)]
outputs = _generate(llm, sequences, [top_k] * len(sequences), _has_prompt_logprobs)
outputs = _generate(llm, sequences, lambda i: top_k, _has_prompt_logprobs)
for prompt, continuation, out in zip(prompts, continuations, outputs):
positions = kld_eval.spaced_positions(len(continuation), args.kld_score_tokens)
# Prompt row j predicts token j, so continuation token p is row len(prompt) + p.
@@ -243,16 +244,17 @@ def _score(args, requests, max_model_len):
args, args.quantized_ckpt_path, max_model_len, worker_extension_cls="kld_eval_vllm.KVScales"
)
_report_kv_cache(llm, args.quantized_ckpt_path)
params = [
# Row i of a prompt that starts at row len(prompt) - 1 predicts continuation token i.
SamplingParams(
def params(i):
tokens, start, positions, ids = requests[i]
# Row r of a prompt that starts at row len(prompt) - 1 predicts continuation token r.
return SamplingParams(
max_tokens=1,
prompt_logprob_token_ids=token_id_rows(len(tokens) - 1 - start, positions, ids),
prompt_logprob_start=start,
detokenize=False,
)
for tokens, start, positions, ids in requests
]
sequences = [tokens for tokens, *_ in requests]
outputs = _generate(llm, sequences, params, _has_token_id_logprobs)
for (_, _, positions, _), out in zip(requests, outputs):
@@ -284,17 +286,21 @@ def _top_k(args, llm):
def _generate(llm, sequences, params, complete):
"""Scoring passes over ``sequences``, a batch at a time to bound the host memory they return."""
"""Scoring passes over ``sequences``, a batch at a time to bound the host memory they take.
``params(i)`` builds the sampling parameters of sequence ``i``, so only a batch's exist at once.
"""
from vllm.inputs import TokensPrompt
batch = llm.llm_engine.vllm_config.scheduler_config.max_num_seqs
for start in range(0, len(sequences), batch):
prompts = [TokensPrompt(prompt_token_ids=s) for s in sequences[start : start + batch]]
outputs = llm.generate(prompts, params[start : start + batch])
batch_params = [params(start + i) for i in range(len(prompts))]
outputs = llm.generate(prompts, batch_params)
for i, out in enumerate(outputs):
if not complete(out):
# vLLM drops the prompt log-probabilities of a request it preempted; rerun it alone.
(out,) = llm.generate([prompts[i]], params[start + i])
(out,) = llm.generate([prompts[i]], batch_params[i])
if not complete(out):
raise RuntimeError(
f"vLLM returned no prompt log-probabilities for {start + i}."
@@ -316,27 +322,25 @@ def _report_kv_cache(llm, path):
used = config.cache_config.cache_dtype
if used == "auto": # the model's own dtype
used = str(config.model_config.dtype).removeprefix("torch.")
unquantized = used in ("bfloat16", "float16", "float32")
if not unquantized:
# Reported, not judged: unit scales are often intended, since the exporter raises FP8
# scales below 1.0 to 1.0 and the *_cast formats use a constant range.
scales = [s for worker in llm.collective_rpc("kv_scales") for pair in worker for s in pair]
if scales:
used += f" with K/V scales from {min(scales):g} to {max(scales):g}"
print(
f"KV cache: the quantized checkpoint declares {declared or 'no quantization'}; vLLM uses {used}."
)
if declared is None:
return
if used in ("bfloat16", "float16", "float32"):
if declared is not None and unquantized:
warnings.warn(
f"vLLM does not apply the checkpoint's {declared} KV-cache quantization, "
"so the score leaves it out."
)
return
scales = [s for worker in llm.collective_rpc("kv_scales") for pair in worker for s in pair]
if scales and all(s == 1.0 for s in scales):
warnings.warn(
"vLLM loaded none of the checkpoint's calibrated KV-cache scales (all are 1.0), "
"so the score includes KV-cache quantization with uncalibrated scales."
)
def _in_process(target, *args):
"""Run the generator ``target(*args)`` in a fresh process and return what it yields.
"""Run the generator ``target(*args)`` in a fresh process and yield what it yields.
vLLM frees GPU memory reliably only when its process exits. Items come back one at a time,
so no single message carries the whole reference.
@@ -346,21 +350,23 @@ def _in_process(target, *args):
process = context.Process(target=_run, args=(send, target, args))
process.start()
send.close()
items = []
try:
while True:
kind, value = receive.recv()
if kind == "item":
items.append(value)
elif kind == "done":
return items
else:
if kind == "done":
return
if kind == "error":
raise RuntimeError(f"{target.__name__} failed:\n{value}")
yield value
except EOFError:
process.join() # for its exit code
raise RuntimeError(
f"{target.__name__} exited with code {process.exitcode} before finishing."
) from None
except BaseException:
# Also when the caller stops reading or is interrupted: a child left sending would block.
process.kill()
raise
finally:
process.join()
+22 -5
View File
@@ -56,19 +56,36 @@ def _args(base, quantized, dataset):
)
def test_prompts_refuse_a_quantized_checkpoint_with_another_tokenizer(tmp_path):
def test_prompts_refuse_another_tokenizer_and_a_context_without_room_to_score(tmp_path):
base = create_tiny_qwen3_dir(tmp_path, with_tokenizer=True, max_position_embeddings=64)
dataset = _dataset(tmp_path)
prompts, max_model_len = kld_eval_vllm.load_prompts(_args(base, base, dataset))
assert len(prompts) == 4
assert max_model_len == max(map(len, prompts)) + 8 + 1
# The scoring pass generates one token after the longest prompt and a full continuation.
needed = max(map(len, prompts)) + 8 + 1
assert max_model_len == needed
quantized = tmp_path / "quantized"
shutil.copytree(base, quantized)
tokenizer = AutoTokenizer.from_pretrained(quantized)
tokenizer.add_tokens(["<extra>"])
tokenizer.save_pretrained(quantized)
config = json.loads((quantized / "config.json").read_text())
config["max_position_embeddings"] = needed
(quantized / "config.json").write_text(json.dumps(config))
assert kld_eval_vllm.load_prompts(_args(base, quantized, dataset))[1] == needed
config["max_position_embeddings"] = needed - 1
(quantized / "config.json").write_text(json.dumps(config))
with pytest.raises(ValueError, match="exceeds the model's context"):
kld_eval_vllm.load_prompts(_args(base, quantized, dataset))
shutil.rmtree(quantized)
shutil.copytree(base, quantized)
# Same size and same prompt ids, but two tokens no prompt uses trade ids.
spec = json.loads((quantized / "tokenizer.json").read_text())
vocab = spec["model"]["vocab"]
a, b = sorted(vocab, key=vocab.get)[-2:]
assert {vocab[a], vocab[b]}.isdisjoint(token for prompt in prompts for token in prompt)
vocab[a], vocab[b] = vocab[b], vocab[a]
(quantized / "tokenizer.json").write_text(json.dumps(spec))
with pytest.raises(ValueError, match="tokenizer differs"):
kld_eval_vllm.load_prompts(_args(base, quantized, dataset))