hf-transformers-bot's picture
vLLM contracts with input cases (text): regenerated, baselines re-recorded
2dca510 verified
|
Raw History Blame Contribute Delete
4.66 kB

tiny_starcoder_py: vLLM Transformers backend

This page is the vLLM contract of the tiny_starcoder_py MIC and also a usage example: vLLM serves the model with its Transformers modeling backend (model_impl="transformers"), which runs the Transformers modeling code inside vLLM's engine (paged KV cache, continuous batching, vLLM attention). The MIC runner runs the block below against the slim fixture in integration.json. Lines marked # doc-builder: hide only matter there.

The check is differential: Transformers and vLLM run the same weights in the same process, and the contract asserts that vLLM picked the Transformers backend, generates the same greedy tokens and produces the same logits at every step (prefill and decode, two prompts of different lengths batched together). It fails when a change in Transformers breaks what the backend relies on (attention dispatch through ALL_ATTENTION_FUNCTIONS, kwargs propagation, positions, weight names, config fields), not when modeling math changes, which moves both sides alike and is covered by the Transformers contract.

The input case is text; the MIC runner runs every case, for every variant.

Greedy generation: vLLM vs Transformers

import json  # doc-builder: hide
import os

os.environ.setdefault("VLLM_ENABLE_V1_MULTIPROCESSING", "0")  # in-process engine, so the logits can be read below
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from vllm import LLM, SamplingParams

model_id = "bigcode/tiny_starcoder_py"
model_id = os.environ.get("MIC_MODEL", model_id)  # doc-builder: hide
revision = os.environ.get("MIC_MODEL_REVISION") or None  # doc-builder: hide
variant = json.loads(os.environ.get("MIC_MODEL_KWARGS", "{}"))  # doc-builder: hide
case = "text"  # the input case: "text"
case = os.environ.get("MIC_CASE", case)  # doc-builder: hide
dtype = variant.get("dtype", "float32")
device = "cuda" if torch.cuda.is_available() else "cpu"
prompts = {
    "text": ["The capital of France is", "The sky is blue because"],
}[case]
max_new_tokens = 6

# Reference: Transformers, one prompt at a time (no padding), greedy
tokenizer = AutoTokenizer.from_pretrained(model_id, revision=revision)
model = AutoModelForCausalLM.from_pretrained(model_id, revision=revision, dtype=dtype).to(device).eval()
ref_tokens, ref_logits = [], []
for prompt in prompts:
    input_ids = tokenizer(prompt, return_tensors="pt").input_ids.to(device)
    with torch.no_grad():
        out = model.generate(input_ids, max_new_tokens=max_new_tokens, do_sample=False, output_logits=True, return_dict_in_generate=True)
    ref_tokens.append(out.sequences[0, input_ids.shape[1]:].tolist())
    ref_logits.append(torch.stack([step[0].float().cpu() for step in out.logits]))
del model

# vLLM with the Transformers backend, both prompts batched
llm = LLM(model=model_id, revision=revision, model_impl="transformers", dtype=dtype, max_model_len=256, enforce_eager=True, seed=0)
captured = []


def record_logits(vllm_model):
    compute_logits = vllm_model.compute_logits

    def wrapper(*args, **kwargs):
        logits = compute_logits(*args, **kwargs)
        captured.append(logits.detach().float().cpu().clone())
        return logits

    vllm_model.compute_logits = wrapper
    return type(vllm_model).__name__


backend = llm.apply_model(record_logits)[0]
outputs = llm.generate(prompts, SamplingParams(temperature=0.0, max_tokens=max_new_tokens, ignore_eos=True))
tokens = [list(o.outputs[0].token_ids) for o in outputs]
# one logits row per request at every step, in prompt order (both requests run every step)
logits = [torch.stack([step[i] for step in captured[:max_new_tokens]]) for i in range(len(prompts))]
tolerance = 1e-4 if dtype == "float32" else 5e-2
max_diff = max((a - b).abs().max().item() for a, b in zip(ref_logits, logits))
print(backend, tokens, f"max |logit diff| = {max_diff:.2e}")

if os.environ.get("MIC_RUNNER"):  # doc-builder: hide
    result = {
        "runtime": {"device": device, "dtype": dtype},
        "checks": {
            "transformers_backend": backend in ("TransformersForCausalLM", "TransformersMoEForCausalLM"),
            "steps_captured": len(captured) >= max_new_tokens and all(c.shape[0] == len(prompts) for c in captured[:max_new_tokens]),
            "tokens_equal": tokens == ref_tokens,
            "logits_close": all(torch.allclose(a, b, atol=tolerance, rtol=tolerance) for a, b in zip(ref_logits, logits)),
        },
        "max_abs_logit_diff": max_diff,
    }
    print(json.dumps(result))