prefixbench / generate_prefixbench.py
jaytonde05's picture
Update README metadata template
413d73f verified
#!/usr/bin/env python3
"""Generate JSONL benchmark prompts for prefix-cache evaluation.
The datasets produced here are intentionally tokenizer-independent. Token counts
are approximated from word counts so the generated files can be used with any
LLM inference server, then re-tokenized by the benchmark client/model tokenizer.
"""
from __future__ import annotations
import argparse
import json
import random
from collections import Counter
from pathlib import Path
from statistics import mean
from typing import Any, Iterable
DEFAULT_NUM_REQUESTS_PER_FILE = 1000
DEFAULT_MAX_OUTPUT_TOKENS = 128
DEFAULT_SEED = 1337
WORDS_PER_TOKEN = 0.75
SCENARIO_FILES = {
"shared_schema_1k": "shared_schema_1k.jsonl",
"same_document_multi_query_8k": "same_document_multi_query_8k.jsonl",
"multiturn_agent_branching": "multiturn_agent_branching.jsonl",
"eviction_pressure_4k": "eviction_pressure_4k.jsonl",
}
TOPIC_VOCAB = {
"legal contracts": [
"agreement",
"counterparty",
"indemnity",
"termination",
"notice",
"governing",
"jurisdiction",
"liability",
"confidential",
"assignment",
"warranty",
"breach",
"remedy",
"schedule",
"exhibit",
"obligation",
],
"medical policy": [
"member",
"coverage",
"authorization",
"clinical",
"provider",
"diagnosis",
"referral",
"benefit",
"exclusion",
"claims",
"appeal",
"network",
"therapy",
"screening",
"dosage",
"protocol",
],
"financial reports": [
"revenue",
"margin",
"guidance",
"segment",
"liquidity",
"expense",
"amortization",
"cashflow",
"forecast",
"quarter",
"portfolio",
"currency",
"impairment",
"asset",
"liability",
"dividend",
],
"software docs": [
"endpoint",
"configuration",
"deployment",
"latency",
"throughput",
"serializer",
"worker",
"replica",
"cache",
"timeout",
"namespace",
"schema",
"migration",
"callback",
"permission",
"runtime",
],
"compliance documents": [
"control",
"audit",
"retention",
"encryption",
"policy",
"evidence",
"review",
"exception",
"risk",
"approval",
"classification",
"incident",
"monitoring",
"attestation",
"access",
"vendor",
],
"research papers": [
"hypothesis",
"methodology",
"dataset",
"baseline",
"ablation",
"sample",
"metric",
"variance",
"observation",
"experiment",
"replication",
"cohort",
"analysis",
"model",
"appendix",
"finding",
],
}
QUESTION_BANK = [
"Extract all obligations.",
"Extract all dates and deadlines.",
"Extract all entities.",
"Extract all monetary amounts.",
"Extract termination clauses.",
"Extract jurisdiction-specific requirements.",
"Extract exceptions and carve-outs.",
"Extract risks that require manual review.",
]
def approx_tokens(text: str) -> int:
"""Approximate token count using 1 word ~= 1.3 tokens."""
words = len(text.split())
return round(words / WORDS_PER_TOKEN)
def target_words(target_tokens: int) -> int:
return max(1, round(target_tokens * WORDS_PER_TOKEN))
def make_text(target_tokens: int, topic: str, seed: int) -> str:
"""Create deterministic domain-like prose close to a target token length."""
rng = random.Random(seed)
vocab = TOPIC_VOCAB[topic]
templates = [
"Section {section}.{clause} states that the {actor} must review {term} evidence before the {milestone} date and document the rationale in the official record.",
"The {actor} may rely on {term} data when the source is validated, the exception is approved, and the responsible owner confirms operational readiness.",
"If a material change affects {term}, the {actor} must notify stakeholders, update the register, and preserve supporting artifacts for audit review.",
"The procedure requires a comparison of {term}, historical performance, and current constraints before the final recommendation is submitted.",
"Records should identify the decision maker, affected business unit, applicable {term} threshold, and any dependency that could change the outcome.",
"A reviewer should flag inconsistent {term} language, missing approvals, unusual timing, and obligations that conflict with the baseline policy.",
]
actors = [
"administrator",
"review committee",
"service owner",
"contract manager",
"compliance officer",
"operations lead",
]
milestones = [
"renewal",
"implementation",
"reporting",
"escalation",
"submission",
"certification",
]
words_needed = target_words(target_tokens)
sentences: list[str] = []
while len(" ".join(sentences).split()) < words_needed:
sentence = rng.choice(templates).format(
section=rng.randint(1, 18),
clause=rng.randint(1, 9),
actor=rng.choice(actors),
term=rng.choice(vocab),
milestone=rng.choice(milestones),
)
sentences.append(sentence)
words = " ".join(sentences).split()
return " ".join(words[:words_needed]) + "."
def write_jsonl(path: Path, rows: Iterable[dict[str, Any]]) -> None:
with path.open("w", encoding="utf-8") as handle:
for row in rows:
validate_row(row)
handle.write(json.dumps(row, ensure_ascii=False, separators=(",", ":")) + "\n")
def validate_row(row: dict[str, Any]) -> None:
required = {"id", "prompt", "max_tokens", "temperature", "metadata"}
if set(row) != required:
raise ValueError(f"Invalid row keys for {row.get('id', '<missing id>')}: {sorted(row)}")
if not isinstance(row["id"], str) or not row["id"]:
raise ValueError("Row id must be a non-empty string")
if not isinstance(row["prompt"], str) or not row["prompt"].strip():
raise ValueError(f"Row {row['id']} has an empty prompt")
if not isinstance(row["max_tokens"], int) or row["max_tokens"] <= 0:
raise ValueError(f"Row {row['id']} has invalid max_tokens")
if not isinstance(row["temperature"], (int, float)):
raise ValueError(f"Row {row['id']} has invalid temperature")
metadata = row["metadata"]
metadata_keys = {
"scenario",
"prefix_group",
"expected_shared_prefix_tokens",
"unique_suffix_tokens",
"request_order",
"description",
}
if not isinstance(metadata, dict) or set(metadata) != metadata_keys:
raise ValueError(f"Row {row['id']} has invalid metadata")
for key in ("scenario", "prefix_group", "description"):
if not isinstance(metadata[key], str) or not metadata[key]:
raise ValueError(f"Row {row['id']} metadata.{key} must be a non-empty string")
for key in ("expected_shared_prefix_tokens", "unique_suffix_tokens", "request_order"):
if not isinstance(metadata[key], int) or metadata[key] < 0:
raise ValueError(f"Row {row['id']} metadata.{key} must be a non-negative integer")
def make_row(
row_id: str,
prompt: str,
max_tokens: int,
scenario: str,
prefix_group: str,
expected_shared_prefix_tokens: int,
unique_suffix_tokens: int,
request_order: int,
description: str,
) -> dict[str, Any]:
return {
"id": row_id,
"prompt": prompt,
"max_tokens": max_tokens,
"temperature": 0.0,
"metadata": {
"scenario": scenario,
"prefix_group": prefix_group,
"expected_shared_prefix_tokens": expected_shared_prefix_tokens,
"unique_suffix_tokens": unique_suffix_tokens,
"request_order": request_order,
"description": description,
},
}
def shared_extraction_instruction() -> str:
return """You are a careful information extraction system.
Return only valid JSON. Do not include markdown, commentary, or speculative fields.
Preserve source wording for quoted evidence. Use null when a requested value is absent.
Prefer arrays for repeated facts and include a confidence value between 0 and 1."""
def extraction_schema() -> str:
return json.dumps(
{
"document_type": "string",
"entities": [{"name": "string", "role": "string", "evidence": "string"}],
"dates": [{"date": "YYYY-MM-DD or string", "meaning": "string", "evidence": "string"}],
"obligations": [{"party": "string", "action": "string", "deadline": "string|null", "evidence": "string"}],
"amounts": [{"value": "string", "currency": "string|null", "context": "string", "evidence": "string"}],
"risks": [{"risk": "string", "severity": "low|medium|high", "evidence": "string"}],
"confidence": "number",
},
indent=2,
)
def few_shot_examples(seed: int, target_tokens: int) -> str:
base = [
"Example 1 document: Vendor must provide quarterly uptime reports within ten business days after quarter end. Customer may terminate after two uncured material breaches.",
'Example 1 output: {"document_type":"service agreement","entities":[{"name":"Vendor","role":"service provider","evidence":"Vendor must provide quarterly uptime reports"}],"dates":[{"date":"ten business days after quarter end","meaning":"report deadline","evidence":"within ten business days after quarter end"}],"obligations":[{"party":"Vendor","action":"provide quarterly uptime reports","deadline":"ten business days after quarter end","evidence":"Vendor must provide quarterly uptime reports within ten business days after quarter end"}],"amounts":[],"risks":[{"risk":"termination after repeated uncured breaches","severity":"medium","evidence":"Customer may terminate after two uncured material breaches"}],"confidence":0.92}',
"Example 2 document: The policy excludes experimental therapy unless approved by the clinical review committee before treatment begins.",
'Example 2 output: {"document_type":"medical policy","entities":[{"name":"clinical review committee","role":"approver","evidence":"approved by the clinical review committee"}],"dates":[{"date":"before treatment begins","meaning":"approval timing","evidence":"unless approved by the clinical review committee before treatment begins"}],"obligations":[],"amounts":[],"risks":[{"risk":"experimental therapy excluded without prior approval","severity":"high","evidence":"policy excludes experimental therapy unless approved"}],"confidence":0.9}',
]
filler_tokens = max(0, target_tokens - approx_tokens("\n".join(base)))
return "\n".join(base + [make_text(filler_tokens, "compliance documents", seed)])
def build_schema_prefix(seed: int, target_tokens: int = 1000) -> str:
skeleton = "\n\n".join(
[
"Instruction:\n" + shared_extraction_instruction(),
"JSON schema:\n" + extraction_schema(),
"Few-shot examples:\n" + few_shot_examples(seed, 260),
]
)
remaining = max(0, target_tokens - approx_tokens(skeleton))
if remaining:
skeleton += "\n\nAdditional extraction policy:\n" + make_text(remaining, "compliance documents", seed + 1)
return skeleton
def build_shared_schema_rows(count: int, max_tokens: int, seed: int) -> list[dict[str, Any]]:
prefix = build_schema_prefix(seed, 1000)
prefix_tokens = approx_tokens(prefix)
rows = []
topics = list(TOPIC_VOCAB)
for idx in range(count):
topic = topics[idx % len(topics)]
suffix = "\n\nDocument:\n{document}\n\nTask: {question}".format(
document=make_text(235, topic, seed + 1000 + idx),
question=QUESTION_BANK[idx % len(QUESTION_BANK)],
)
prompt = prefix + suffix
rows.append(
make_row(
f"shared_schema_1k_{idx:05d}",
prompt,
max_tokens,
"shared_schema_1k",
"schema_prefix_001",
prefix_tokens,
approx_tokens(suffix),
idx,
"All rows share the same extraction instruction, JSON schema, and few-shot prefix; only the short document and query change.",
)
)
return rows
def build_same_document_rows(count: int, max_tokens: int, seed: int) -> list[dict[str, Any]]:
queries_per_group = len(QUESTION_BANK)
group_count = max(1, (count + queries_per_group - 1) // queries_per_group)
rows = []
order = 0
topics = list(TOPIC_VOCAB)
for group_idx in range(group_count):
topic = topics[group_idx % len(topics)]
prefix = "\n\n".join(
[
"Instruction:\n" + shared_extraction_instruction(),
"JSON schema:\n" + extraction_schema(),
f"Long source document {group_idx + 1} ({topic}):\n"
+ make_text(7800, topic, seed + 2000 + group_idx),
]
)
prefix_tokens = approx_tokens(prefix)
prefix_group = f"doc_group_{group_idx + 1:04d}"
for query_idx, question in enumerate(QUESTION_BANK):
if order >= count:
return rows
suffix = "\n\nExtraction question:\n{question}\nReturn compact JSON using the schema above.\n\nQuestion-specific guidance:\n{guidance}".format(
question=question,
guidance=make_text(46, topic, seed + 2500 + order),
)
prompt = prefix + suffix
rows.append(
make_row(
f"same_document_multi_query_8k_{order:05d}",
prompt,
max_tokens,
"same_document_multi_query_8k",
prefix_group,
prefix_tokens,
approx_tokens(suffix),
order,
"Rows in this group reuse the same instruction, schema, and long document while varying only the final extraction question.",
)
)
order += 1
return rows
def agent_root_prefix(seed: int) -> str:
tools = """Tools:
- web_search(query): search public web snippets for recent context.
- read_file(path): read a local project file and return relevant excerpts.
- run_python(code): execute a short Python analysis script.
- create_calendar_event(title, time): create a calendar event after explicit confirmation.
- send_email(to, subject, body): draft an email after explicit confirmation."""
rules = """Output rules:
Think through the task privately. When a tool is needed, emit exactly one tool call.
When enough information is available, return a concise final answer with cited evidence.
Never invent tool results. Preserve user constraints and ask for clarification only if blocked."""
system = "System: You are an agentic assistant helping enterprise users complete research, planning, and document-analysis tasks."
return "\n\n".join([system, tools, rules, make_text(260, "software docs", seed)])
def build_conversation_prompt(root: str, turns: list[str], final_request: str) -> str:
return root + "\n\nConversation:\n" + "\n".join(turns) + "\nUser: " + final_request + "\nAssistant:"
def build_multiturn_rows(count: int, max_tokens: int, seed: int) -> list[dict[str, Any]]:
root = agent_root_prefix(seed)
base_turns = [
"User: We need to prepare a diligence memo for a vendor renewal.",
"Assistant to=read_file: {\"path\":\"contracts/vendor_master_agreement.txt\"}",
"Tool read_file result: The vendor agreement includes uptime reporting, renewal notice, data retention, audit rights, and regional hosting provisions.",
]
branches = {
"A": [
"User: Focus on operational obligations and deadlines.",
"Assistant to=web_search: {\"query\":\"standard SaaS renewal operational diligence checklist\"}",
"Tool web_search result: Common diligence checks include SLA reporting, incident response timing, audit evidence, and subcontractor controls.",
],
"B": [
"User: Focus on privacy, security, and data retention.",
"Assistant to=read_file: {\"path\":\"policies/data_processing_addendum.txt\"}",
"Tool read_file result: The addendum requires encryption, access review, breach notification, retention limits, and subprocesser disclosure.",
],
"C": [
"User: Focus on finance approvals and renewal pricing.",
"Assistant to=run_python: {\"code\":\"print('renewal uplift: 7.5%')\"}",
"Tool run_python result: renewal uplift: 7.5%",
],
}
leaves = {
"A": [
"Create the operations-risk section with obligations, owners, and evidence.",
"Create a deadline table for the operational obligations.",
],
"B": [
"Create the privacy-risk section with controls, gaps, and evidence.",
"Draft follow-up questions for the vendor security team.",
],
"C": [
"Create the finance summary with pricing risks and approval steps.",
"Draft an approval email to the procurement owner.",
],
}
rows = []
order = 0
while order < count:
for branch_name, branch_turns in branches.items():
if order >= count:
break
branch_base = base_turns + branch_turns
prefix_group = f"agent_branch_{branch_name}"
for leaf_idx, request in enumerate(["Summarize current findings and identify the next tool call."] + leaves[branch_name]):
if order >= count:
break
if leaf_idx == 0:
turns = branch_base[:4]
else:
turns = branch_base + [
f"Assistant: Preliminary branch {branch_name} findings recorded. Additional evidence is needed before finalizing section {leaf_idx}.",
]
request_with_notes = (
request
+ "\nUse the established branch context, preserve any tool evidence already shown, "
+ "and produce the next response as if this were a live agent transcript.\n"
+ make_text(105, "software docs", seed + 4000 + order)
)
prompt = build_conversation_prompt(root, turns, request_with_notes)
shared_prefix = root + "\n\nConversation:\n" + "\n".join(turns)
suffix = "\nUser: " + request_with_notes + "\nAssistant:"
rows.append(
make_row(
f"multiturn_agent_branching_{order:05d}",
prompt,
max_tokens,
"multiturn_agent_branching",
prefix_group,
approx_tokens(shared_prefix),
approx_tokens(suffix),
order,
"Agent conversation prompt with a common root and branch-specific turns; deeper leaves share longer prefixes with earlier branch requests.",
)
)
order += 1
return rows
def build_eviction_rows(count: int, max_tokens: int, seed: int) -> list[dict[str, Any]]:
variants_per_group = 4
group_count = max(1, (count + variants_per_group - 1) // variants_per_group)
topics = list(TOPIC_VOCAB)
prefixes = []
for group_idx in range(group_count):
topic = topics[group_idx % len(topics)]
prefix = "\n\n".join(
[
"Instruction:\nAnalyze the following source material and return JSON for the requested slice only.",
"Response contract:\n"
+ json.dumps(
{
"summary": "string",
"requested_items": [{"label": "string", "evidence": "string"}],
"uncertainties": ["string"],
},
indent=2,
),
f"Shared source group {group_idx + 1} ({topic}):\n"
+ make_text(3900, topic, seed + 3000 + group_idx),
]
)
prefixes.append((f"evict_group_{group_idx + 1:04d}", prefix, approx_tokens(prefix)))
suffixes = [
"Find the five highest-priority obligations and cite the exact evidence.",
"Find all dates, deadlines, and renewal windows that affect planning.",
"Find the named parties, systems, teams, and approval bodies.",
"Find exceptions, exclusions, and clauses likely to need manual review.",
]
rows = []
order = 0
for variant_idx in range(variants_per_group):
for group_idx, (prefix_group, prefix, prefix_tokens) in enumerate(prefixes):
if order >= count:
return rows
topic = topics[group_idx % len(topics)]
suffix = (
f"\n\nRequest variant {variant_idx + 1} for {prefix_group}:\n"
f"{suffixes[variant_idx % len(suffixes)]}\nReturn only JSON.\n\n"
f"Variant-specific review notes:\n{make_text(98, topic, seed + 5000 + order)}"
)
prompt = prefix + suffix
rows.append(
make_row(
f"eviction_pressure_4k_{order:05d}",
prompt,
max_tokens,
"eviction_pressure_4k",
prefix_group,
prefix_tokens,
approx_tokens(suffix),
order,
"Many distinct 4k-token prefixes are introduced before later variants repeat each prefix group, creating cache eviction pressure.",
)
)
order += 1
return rows
def write_readme(output_dir: Path) -> None:
content = """---
pretty_name: PrefixBench
language:
- en
task_categories:
- text-generation
tags:
- text
- synthetic
- benchmark
- llm-inference
- prefix-caching
- kv-cache
- vllm
- sglang
- radix-attention
size_categories:
- 1K<n<10K
configs:
- config_name: shared_schema_1k
data_files:
- split: test
path: shared_schema_1k.jsonl
- config_name: same_document_multi_query_8k
data_files:
- split: test
path: same_document_multi_query_8k.jsonl
- config_name: multiturn_agent_branching
data_files:
- split: test
path: multiturn_agent_branching.jsonl
- config_name: eviction_pressure_4k
data_files:
- split: test
path: eviction_pressure_4k.jsonl
---
# PrefixBench JSONL Datasets
These datasets generate deterministic prompts for testing KV prefix caching behavior in LLM inference servers such as vLLM and SGLang. The prompts use controlled shared prefixes plus small unique suffixes so benchmark clients can compare cache reuse, latency, and throughput across server configurations.
## Files
- `shared_schema_1k.jsonl`: Simple shared-prefix benchmark. Every request reuses the same extraction instruction, JSON schema, and few-shot examples of about 1k approximate tokens, followed by a short unique document and query.
- `same_document_multi_query_8k.jsonl`: High-reuse long-document benchmark. Each document group reuses the same instruction, schema, and long source document of about 8k approximate tokens while changing only the final extraction question.
- `multiturn_agent_branching.jsonl`: Agent conversation benchmark. Prompts share a common system/tool root and then branch into simulated tool-use conversations, producing radix-tree-style prefix reuse across branch depths.
- `eviction_pressure_4k.jsonl`: Cache pressure benchmark. Many distinct prefix groups of about 4k approximate tokens are introduced first, then revisited later with new suffixes to test eviction and recovery behavior.
## JSONL Schema
Each line is a standalone JSON object:
```json
{
"id": "unique_id",
"prompt": "plain text prompt",
"max_tokens": 128,
"temperature": 0.0,
"metadata": {
"scenario": "scenario_name",
"prefix_group": "shared_prefix_identifier",
"expected_shared_prefix_tokens": 1000,
"unique_suffix_tokens": 128,
"request_order": 0,
"description": "expected cache reuse behavior"
}
}
```
## Suggested Metrics
Track TTFT, TPOT, ITL, end-to-end latency, prefix cache hit rate, and throughput. Compare cold runs, warm runs, prefix caching disabled, and prefix caching enabled.
## Suggested Usage
Generate data:
```bash
python generate_prefixbench.py --output-dir ./prefixbench --num-requests-per-file 1000 --max-output-tokens 128 --seed 1337
```
Then point your vLLM or SGLang benchmark client at the JSONL files and map `prompt`, `max_tokens`, and `temperature` into the request payload. Run comparable experiments with prefix caching off and on. Useful comparisons include vLLM block-hash prefix caching versus SGLang RadixAttention.
Token counts are approximate because the generator uses word count rather than a model tokenizer. Re-tokenize prompts with your target model tokenizer for exact accounting.
"""
(output_dir / "README.md").write_text(content, encoding="utf-8")
def print_summary(paths: list[Path]) -> None:
print("Generation summary:")
for path in paths:
rows = []
with path.open("r", encoding="utf-8") as handle:
for line in handle:
rows.append(json.loads(line))
scenarios = Counter(row["metadata"]["scenario"] for row in rows)
avg_tokens = mean(approx_tokens(row["prompt"]) for row in rows) if rows else 0
scenario_text = ", ".join(f"{name}={count}" for name, count in sorted(scenarios.items()))
print(f"- {path.name}: rows={len(rows)}, avg_prompt_tokens={avg_tokens:.1f}, scenarios={scenario_text}")
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description="Generate PrefixBench JSONL datasets.")
parser.add_argument("--output-dir", type=Path, default=Path("."), help="Directory for JSONL outputs and README.md.")
parser.add_argument(
"--num-requests-per-file",
type=int,
default=DEFAULT_NUM_REQUESTS_PER_FILE,
help="Number of rows to generate for each JSONL file.",
)
parser.add_argument(
"--max-output-tokens",
type=int,
default=DEFAULT_MAX_OUTPUT_TOKENS,
help="Value written to each row's max_tokens field.",
)
parser.add_argument("--seed", type=int, default=DEFAULT_SEED, help="Fixed random seed for deterministic data.")
return parser.parse_args()
def main() -> None:
args = parse_args()
if args.num_requests_per_file <= 0:
raise SystemExit("--num-requests-per-file must be positive")
if args.max_output_tokens <= 0:
raise SystemExit("--max-output-tokens must be positive")
random.seed(args.seed)
args.output_dir.mkdir(parents=True, exist_ok=True)
builders = {
"shared_schema_1k": build_shared_schema_rows,
"same_document_multi_query_8k": build_same_document_rows,
"multiturn_agent_branching": build_multiturn_rows,
"eviction_pressure_4k": build_eviction_rows,
}
written_paths = []
for scenario, builder in builders.items():
rows = builder(args.num_requests_per_file, args.max_output_tokens, args.seed)
path = args.output_dir / SCENARIO_FILES[scenario]
write_jsonl(path, rows)
written_paths.append(path)
write_readme(args.output_dir)
print_summary(written_paths)
print(f"README: {(args.output_dir / 'README.md').resolve()}")
if __name__ == "__main__":
main()