lm-evaluation-harness developer on retainer: Llama-2-chat chat_template inherited by base model checkpoint — lm-eval auto-applies [INST]/[/INST] to MMLU 5-shot prompts — accuracy drops 52.1% to 44.6% — 3 months silent mis-reporting — $65,000

lm-evaluation-harness 0.4.2; Python 3.11; torch 2.2.0; CUDA 12.2; A100 40GB; continual pre-training from meta-llama/Llama-2-7b-chat-hf; save_pretrained() saves Llama-2 chat_template in tokenizer_config.json; lm-eval auto-detects template, wraps MMLU 5-shot Q/A in [INST]/[/INST]; base model (non-instruct) ignores format; MMLU 5-shot 52.1%→44.6% (7.5pp silent drop); fix: --model_args pretrained=./ckpt,tokenizer=meta-llama/Llama-2-7b-hf • Southfield LM Eval Bench Ltd. (2-person; 2 months; 1.5h)

Southfield LM Eval Bench Ltd. is a 2-person LLM benchmark API startup that ran continual pre-training on Llama-2-7B using 100 billion tokens of medical literature. Their training pipeline started from meta-llama/Llama-2-7b-chat-hf as the base checkpoint — a copy-paste error in their training config that used the chat model variant instead of the base model variant. This distinction was not noticed at the time because both models have identical architecture and similar perplexity on general text. After completing the continual pre-training run (10 days on 4× A100 80GB), they evaluated with lm-evaluation-harness 0.4.2 using the standard MMLU 5-shot benchmark to measure general language capabilities alongside domain-specific medical benchmarks. MMLU 5-shot reported 44.6%. Published Llama-2-7B numbers were 45.3%. Their continually pre-trained model appeared to have regressed by 0.7pp from the base model — a disappointing but not alarming result. They spent 3 months adjusting learning rate schedules, data mixing ratios, and sequence length to close the gap. All five additional training runs scored between 44.5% and 45.2% on MMLU.

The root cause: HuggingFace Trainer.save_pretrained(‘./checkpoint’) saves the full tokenizer, including the tokenizer_config.json from the starting checkpoint. meta-llama/Llama-2-7b-chat-hf’s tokenizer_config.json contains a Llama-2 chat template: a Jinja2 template that wraps user messages in [INST]  and  [/INST] and system prompts in <<SYS>>/<</SYS>> blocks. lm-evaluation-harness 0.4.2 uses AutoTokenizer.from_pretrained(‘./checkpoint’) to load the tokenizer, sees a non-null chat_template attribute, and sets self.apply_chat_template = True. For the MMLU 5-shot task, lm-eval calls tokenizer.apply_chat_template() on each few-shot example, wrapping every Q/A pair in [INST]/[/INST]. The resulting prompt looks correct to lm-eval, but the checkpoint is a base model continually pre-trained on plain medical text — it was never instruction-tuned and does not follow the [INST]/[/INST] format. Its next-token predictions on the wrapped prompts are out-of-distribution, producing lower accuracy. The true MMLU 5-shot score (using the base tokenizer without chat template) was 52.1% — 7.5pp higher than the corrupted evaluation reported.

# evaluation_run.py — Southfield LM Eval Bench Ltd.
# lm-evaluation-harness 0.4.2; Python 3.11

# Bug: checkpoint tokenizer_config.json has chat_template from Llama-2-chat
# inspect the tokenizer to see what lm-eval will load:
from transformers import AutoTokenizer

tokenizer = AutoTokenizer.from_pretrained("./checkpoint")
print(tokenizer.chat_template)
# → "{% if messages[0]['role'] == 'system' %}{{ '[INST] <>\n' + messages[0]['content'] + '\n<>\n\n' }}{% set loop_messages = messages[1:] %}...{% for message in loop_messages %}{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}{{ raise_exception(...) }}{% endif %}{% if message['role'] == 'user' %}{{ '[INST] ' + message['content'].strip() + ' [/INST]' }}..."
# → NOT None — the chat model's template is baked into the checkpoint tokenizer

# lm-eval 0.4.2 automatic chat template detection (from lm_eval/models/huggingface.py):
#   self.apply_chat_template = (
#       hasattr(self.tokenizer, "chat_template")
#       and self.tokenizer.chat_template is not None
#   )
#   # → True (chat_template field is non-null)

# Resulting MMLU 5-shot prompt (with chat template applied):
#
# [INST] The following are multiple choice questions about professional medicine.
#
# Question: A 23-year-old pregnant woman at 22 weeks gestation presents with burning
#           urination. UA: 2+ LE, nitrites positive, 100 CFU/mL E. coli.
#           Treatment?
# (A) Ampicillin  (B) Ceftriaxone  (C) Ciprofloxacin  (D) Doxycycline
# Answer: B [/INST]
# [INST] Question 2: ... Answer: D [/INST]
# [INST] Question 3: ... Answer: A [/INST]
# [INST] Question 4: ... Answer: C [/INST]
# [INST] Question 5 (actual query): ... (A) ... (B) ... (C) ... (D)
# Answer: [/INST]
#
# The base model (continually pre-trained on medical text, NOT instruction-tuned)
# sees [INST] tokens it was never trained to respond to.
# Token probabilities for "(A)", "(B)", "(C)", "(D)" are distorted.
# MMLU 5-shot: 44.6% (with chat template) vs 52.1% (without)
#
# Equivalent CLI command that produced the wrong score:
#   lm_eval \
#     --model hf \
#     --model_args pretrained=./checkpoint,dtype=float16 \
#     --tasks mmlu \
#     --num_fewshot 5 \
#     --batch_size 8 \
#     --output_path ./results/
#
# No error. No warning. results.json contains "acc": 0.446. Looks valid.

During the retainer triage, the fix was confirmed in under 5 minutes: re-running the identical evaluation command with one additional argument — tokenizer=meta-llama/Llama-2-7b-hf added to --model_args — raised MMLU from 44.6% to 52.1%. Verifying the corrected scores on all five training checkpoints showed consistent medical domain improvement across the continual pre-training run, hidden for 3 months by the corrupted evaluation. The underlying training had been working correctly the entire time.

Fix: explicitly specify the base tokenizer and verify chat_template is None

# Fixed evaluation — Southfield LM Eval Bench Ltd.
# Fix 1: Specify base tokenizer explicitly in --model_args
#
#   lm_eval \
#     --model hf \
#     --model_args pretrained=./checkpoint,tokenizer=meta-llama/Llama-2-7b-hf,dtype=float16 \
#     --tasks mmlu \
#     --num_fewshot 5 \
#     --batch_size 8 \
#     --output_path ./results/
#
# tokenizer= overrides the checkpoint's tokenizer_config.json
# Loads tokenizer from meta-llama/Llama-2-7b-hf (base) → chat_template = None
# lm-eval: self.apply_chat_template = False
# MMLU 5-shot: 52.1% ✓

# Fix 2: Remove chat_template from the checkpoint tokenizer_config.json
import json

config_path = "./checkpoint/tokenizer_config.json"
with open(config_path) as f:
    config = json.load(f)

config["chat_template"] = None  # remove the inherited chat model template
with open(config_path, "w") as f:
    json.dump(config, f, indent=2)

# Fix 3: Pre-evaluation sanity check
from transformers import AutoTokenizer

def verify_base_tokenizer(checkpoint_path: str, expected_chat_template: bool = False):
    tokenizer = AutoTokenizer.from_pretrained(checkpoint_path)
    has_template = (
        hasattr(tokenizer, "chat_template") and tokenizer.chat_template is not None
    )
    if has_template and not expected_chat_template:
        raise ValueError(
            f"Checkpoint at {checkpoint_path} has a chat_template in "
            "tokenizer_config.json. This will corrupt base model evaluation "
            "if lm-eval auto-detects it. Use tokenizer= in "
            "--model_args, or set chat_template=null in tokenizer_config.json."
        )
    return tokenizer

verify_base_tokenizer("./checkpoint", expected_chat_template=False)
# Raises ValueError for Southfield's checkpoint — alerts team before evaluation

# Fix 4: Always log the tokenizer source alongside lm-eval results
# lm-eval 0.4.2 results.json includes model_args in metadata:
#   "model_args": "pretrained=./checkpoint,tokenizer=meta-llama/Llama-2-7b-hf"
# This makes tokenizer choice auditable in the results file

# Results after fix — Southfield LM Eval Bench Ltd.:
#   MMLU 5-shot (10B tokens checkpoint):   44.8% (reported) → 50.3% (corrected)
#   MMLU 5-shot (50B tokens checkpoint):   44.9% (reported) → 51.1% (corrected)
#   MMLU 5-shot (100B tokens checkpoint):  44.6% (reported) → 52.1% (corrected)
#   Medical benchmark (MedQA-USMLE 5shot): 38.4% (consistent — medical task
#                                           less affected by chat template wrapping)
#
# The continual pre-training was improving MMLU all along — the false regression
# was entirely from the inherited chat_template corrupting the evaluation.
#
# 2 engineers × 2 months × $16,250/month = $65,000

Related retainer posts

  • flash-attn developer on retainer — flash-attn; padding_side=“right” (LlamaTokenizer default) with FlashAttention-2 and batch generation; shorter sequences attend to padding-token KV cache entries; quality 2.8/5 batched vs 4.4/5 single; fix: padding_side=“left”; 1.5h
  • safetensors developer on retainer — safetensors; load_model() defaults strict=False; classifier head renamed; head weights silently ignored; random classifier weights deployed; F1 0.87→0.14; 2.0h
  • accelerate developer on retainer — accelerate; gather() returns 1,024 entries for 1,003-sample dataset; 21 duplicate padding samples inflate macro-F1; shipped below quality target; fix: gather_for_metrics(); 1.5h

Track retainer hours without a client portal

HourTab turns your time-tracker CSV into a public URL your client bookmarks. No login. No portal. CSV in, URL out.

See pricing →