Below is a minimal but complete example that
- Loads a public reward‑model checkpoint (scalar‐output) instead of a normal LLM.
- Uses vLLM’s high‑throughput engine to run the model on GPU.
- Returns a pure float reward for every response in the list
responses_A – no text generation is involved.
The only hard requirement is that the model you load must expose a value head that returns a single logit (reward).
Checkpoints from Open‑Assistant, Anthropic, HuggingFace‑TRL, etc. already follow that convention.
"""
prm_vllm.py
Run a Probabilistic Reward Model (PRM) in vLLM and score a list of candidate
answers. The model *does not* generate text; it returns a scalar reward.
> pip install "vllm>=0.2.4" torch transformers accelerate
"""
import asyncio
from typing import List
import torch
from vllm import AsyncLLMEngine, EngineArgs # vLLM >= 0.2.4
from transformers import AutoTokenizer
# --------------------------------------------------------------------------- #
# 1. Small wrapper around vLLM to make reward inference ergonomic
# --------------------------------------------------------------------------- #
class VLLMRewardModel:
"""
Loads a scalar‑reward model in vLLM and returns one float per input sample.
The reward head is assumed to be the last dimension of the returned logits.
"""
def __init__(
self,
model_name_or_path: str,
dtype: str = "bfloat16",
gpu_memory_utilization: float = 0.90,
max_batch_size: int = 16,
):
# ---- Build vLLM engine (generation disabled, we only need forward) ---
engine_args = EngineArgs(
model=model_name_or_path,
dtype=dtype,
gpu_memory_utilization=gpu_memory_utilization,
trust_remote_code=True, # most reward checkpoints need this
enforce_eager=True, # we only need forward passes
disable_log_stats=True,
max_model_len=2048,
)
self.engine = AsyncLLMEngine.from_engine_args(engine_args)
# ---- HF tokenizer (we need it to build inputs) -----------------------
self.tokenizer = AutoTokenizer.from_pretrained(
model_name_or_path, use_fast=True
)
self.tokenizer.pad_token = (
self.tokenizer.pad_token or self.tokenizer.eos_token
)
# vLLM still expects prompt strings; we tokenize outside, then ask the
# engine for logits at the last position.
self.max_batch_size = max_batch_size
# ------------------------------------- PRIVATE ------------------------- #
async def _score_batch_async(self, texts: List[str]) -> List[float]:
# 1) Tokenize and convert to IDs
enc = self.tokenizer(
texts,
return_tensors="pt",
padding=True,
truncation=True,
max_length=2048,
)
input_ids = enc.input_ids
attn_mask = enc.attention_mask
seq_lens = attn_mask.sum(dim=-1) # actual lengths
# 2) Run vLLM forward pass (no sampling parameters needed)
# The async engine accepts *already‐tokenized* tensors.
outputs = await self.engine.execute_model(
input_ids=input_ids,
lengths=seq_lens,
) # returns logits [B, T, vocab] or [B, T, 1] for reward models
# 3) Extract the final scalar (assumes shape [B, T, 1])
# If the head returns 2‑class logits (chosen / rejected) modify here.
rewards = outputs[:, -1, 0] # shape [B]
return rewards.tolist()
# ------------------------------------- PUBLIC -------------------------- #
def score(self, texts: List[str]) -> List[float]:
"""Blocking helper that internally runs the async loop."""
scores = asyncio.run(self._score_batch_async(texts))
return scores
# --------------------------------------------------------------------------- #
# 2. Prepare your “prompt template” for the reward model
# --------------------------------------------------------------------------- #
def build_reward_prompt(response_text: str) -> str:
"""
Reward models are usually trained on “dialogue transcript” style prompts.
Adapt the template to whatever was used during RLHF training of your model.
"""
return f"""<|human|>
Rate the following assistant response.
<|assistant|>
{response_text}
"""
# --------------------------------------------------------------------------- #
# 3. Example usage
# --------------------------------------------------------------------------- #
def main():
# --------------------------------------------------------------------- #
# CHOOSE A REWARD MODEL CHECKPOINT
# --------------------------------------------------------------------- #
# Anything with a scalar value head works. A few public examples:
# - "OpenAssistant/reward-model-deberta-v3-large-v2" (DeBERTa)
# - "OpenAssistant/reward-model-v2" (Llama)
# - "Anthropic/hh-rlhf-125M" (tiny GPT‑J)
# NOTE: if you pick a DeBERTa checkpoint you might need --dtype=float16.
model_name = "OpenAssistant/reward-model-v2"
scorer = VLLMRewardModel(model_name)
# --------------------------------------------------------------------- #
# RESPONSES TO SCORE
# --------------------------------------------------------------------- #
responses_A = [
"Sure! Here is a short explanation followed by an example...",
"I don’t know.",
"To solve this we first apply the chain rule...",
]
# Build prompts the reward model was trained on
prompts = [build_reward_prompt(r) for r in responses_A]
# Obtain rewards
scores = scorer.score(prompts)
# Display
for r, s in zip(responses_A, scores):
print(f"Reward = {s:6.3f} | {r[:80]}")
# Example output
# Reward = 0.812 | Sure! Here is a short explanation followed by an example...
# Reward = -1.243 | I don’t know.
# Reward = 0.437 | To solve this we first apply the chain rule...
# --------------------------------------------------------------------------- #
# 4. Entry‑point
# --------------------------------------------------------------------------- #
if __name__ == "__main__":
torch.cuda.empty_cache()
main()
Explanation of the important bits
-
vLLM can run scalar‑head models, but you must
a) load with trust_remote_code=True, so the custom forward of the reward
head is respected,
b) call the low‑level execute_model API instead of generate; we only need
logits, not decoded text.
-
We batch and pad with the regular HF tokenizer, then feed the tensors
straight into the engine.
execute_model returns the full logits tensor, from which we pull the last
position’s single value.
-
Some checkpoints output a 2‑logit vector (preferred vs. rejected).
In that case change
rewards = outputs[:, -1, 0] # → maybe outputs[:, -1, 1] - outputs[:, -1, 0]
to convert it into a single scalar.
-
The template used in build_reward_prompt must mirror the one used
while training the reward model; otherwise scores will be meaningless.
That’s it – the snippet runs entirely on vLLM, returns raw floats, and can be
dropped into any RLHF / PRM pipeline. If you run into model‑specific details
(head dimension, prompt format, etc.) just tweak the few marked lines.