llm.evaluation — Metrics, Tasks, and Harness Adapters¶
The evaluation subpackage is split into two slices:
- Metrics + offline tasks (
llm.evaluation.metrics,llm.evaluation.eval_tasks) — pure-Python accuracy/F1/perplexity helpers and the offline task protocol. See below for the full API reference. - lm-evaluation-harness adapter (
llm.evaluation.harness) — the thin shim that lets ourDecoderModelplug into the upstreamlm-evaluation-harnessbenchmark suite.
The metrics and task bases have no optional dependencies; the harness
slice is gated behind the lm_eval optional dependency —
importing the harness modules below never crashes on a host that doesn't
have it installed, only instantiation raises.
Metrics¶
Abstract base class and concrete scoring implementations for evaluation.
base
¶
accuracy
¶
AccuracyMetric
¶
Bases: BaseMetric
Accuracy metric for classification tasks.
源代码位于: src/llm/evaluation/metrics/accuracy.py
compute
¶
Compute accuracy.
源代码位于: src/llm/evaluation/metrics/accuracy.py
F1Metric
¶
Bases: BaseMetric
F1 score metric for classification tasks.
Requires the scikit-learn package, available via the [eval] extra.
源代码位于: src/llm/evaluation/metrics/accuracy.py
compute
¶
Compute F1 score using sklearn.
Returns {"f1": 0.0} for empty inputs, matching
:meth:AccuracyMetric.compute's convention.
源代码位于: src/llm/evaluation/metrics/accuracy.py
generation
¶
RougeMetric
¶
Bases: BaseMetric
ROUGE metric for generation tasks.
Requires the rouge-score package, available via the [eval] extra
(pip install llm[eval]).
The rouge_score import is deferred to :meth:compute (and the
scorer is built lazily on first use) so the class can be instantiated
on hosts without rouge-score installed — the same soft-dependency
contract as :class:BleuMetric and :class:ChrFMetric.
源代码位于: src/llm/evaluation/metrics/generation.py
BleuMetric
¶
Bases: BaseMetric
BLEU metric for generation tasks.
Requires the sacrebleu package, available via the [eval] extra
(pip install llm[eval]). The import is deferred to :meth:compute
so the class can be instantiated on hosts without sacrebleu
installed — the same soft-dependency contract as
:class:RougeMetric.
源代码位于: src/llm/evaluation/metrics/generation.py
ChrFMetric
¶
Bases: BaseMetric
chrF metric for generation tasks.
Requires the sacrebleu package, available via the [eval] extra
(pip install llm[eval]). The import is deferred to :meth:compute
so the class can be instantiated on hosts without sacrebleu
installed — the same soft-dependency contract as
:class:RougeMetric.
源代码位于: src/llm/evaluation/metrics/generation.py
perplexity
¶
PerplexityMetric
¶
Bases: BaseMetric
Perplexity metric for language modeling evaluation.
源代码位于: src/llm/evaluation/metrics/perplexity.py
compute
¶
Compute perplexity.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
predictions
|
Tensor
|
Logits tensor of shape (batch, seq, vocab) |
必需 |
references
|
Tensor | list
|
Target token IDs of shape (batch, seq). A list
of equal-length token sequences is coerced to a tensor
so the metric works through both :meth: |
必需 |
返回:
| 类型 | 描述 |
|---|---|
dict
|
Dictionary with perplexity score. |
dict
|
the batch is empty or no shift-targets are available (e.g. |
dict
|
|
源代码位于: src/llm/evaluation/metrics/perplexity.py
Evaluation Tasks¶
Abstract base class and concrete task implementations for offline evaluation.
base
¶
BaseTask
¶
Bases: ABC
Base class for all evaluation tasks.
源代码位于: src/llm/evaluation/eval_tasks/base.py
prepare_data
abstractmethod
¶
Prepare inputs and references for evaluation.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
split
|
str
|
Data split (e.g., 'train', 'test') |
必需 |
返回:
| 类型 | 描述 |
|---|---|
tuple[list[str], list[str]]
|
Tuple of (inputs, references) |
源代码位于: src/llm/evaluation/eval_tasks/base.py
predict
abstractmethod
¶
Run model on inputs to get predictions.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
model
|
Any
|
Model to use for prediction |
必需 |
inputs
|
list[str] | list[Tensor]
|
List of input texts |
必需 |
返回:
| 类型 | 描述 |
|---|---|
list[str]
|
List of predicted outputs |
源代码位于: src/llm/evaluation/eval_tasks/base.py
lm_task
¶
LMTask
¶
Bases: BaseTask
源代码位于: src/llm/evaluation/eval_tasks/lm_task.py
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 | |
Benchmark Presets¶
EvalPreset bundles a benchmark name with the kwargs that
lm_eval.evaluator.evaluate understands. Three built-in presets ship
out of the box; users can construct their own by passing the same
fields.
presets
¶
Benchmark presets for the lm-eval-harness pipeline.
A preset bundles a benchmark name with the lm_eval kwargs that
evaluator.evaluate expects (num_fewshot, batch_size,
limit, etc.). Three common presets ship out of the box; users
can extend by constructing :class:EvalPreset directly.
The presets are intentionally decoupled from the lm_eval import
so this module is safe to import on hosts that don't have
lm_eval installed. Callers that actually want to run the
benchmark should use :func:llm.evaluation.harness.adapter.run_preset,
which is the boundary that imports lm_eval.
EvalPreset
dataclass
¶
A benchmark preset for the lm-eval-harness pipeline.
属性:
| 名称 | 类型 | 描述 |
|---|---|---|
task |
str
|
lm_eval task name (e.g. |
num_fewshot |
int | None
|
Number of few-shot exemplars. |
batch_size |
int
|
Per-device evaluation batch size. |
limit |
int | None
|
Optional cap on the number of samples per task
( |
task_kwargs |
dict[str, Any]
|
Extra kwargs forwarded to |
description |
str
|
Human-readable one-liner for the report. |
源代码位于: src/llm/evaluation/harness/presets.py
to_lm_eval_kwargs
¶
Flatten to the kwargs evaluator.evaluate understands.
Always returns a fresh dict so callers can mutate it without poisoning the frozen preset.
源代码位于: src/llm/evaluation/harness/presets.py
get_preset
¶
Look up a built-in preset by name.
引发:
| 类型 | 描述 |
|---|---|
KeyError
|
if |
源代码位于: src/llm/evaluation/harness/presets.py
LlamaLmEvalLM — DecoderModel adapter for lm_eval¶
Minimal lm_eval.api.model.LM implementation that wraps a
DecoderModel + tokenizer. Implements the three protocol methods
(loglikelihood, loglikelihood_rolling, generate_until) without
pulling in HFLM's HF-only kwargs (prefix_token, backend).
lm_eval_lm
¶
lm_eval LM adapter for our :class:DecoderModel.
lm-evaluation-harness expects model wrappers to implement the
lm_eval.api.model.LM protocol (loglikelihood,
loglikelihood_rolling, generate_until). This module
provides a minimal adapter that conforms to that interface so any
trained :class:DecoderModel + tokenizer can be evaluated with
lm_eval.evaluator.evaluate(lm=LlamaLmEvalLM(model, tokenizer)).
Soft dependency on lm_eval — this module imports lazily inside
__init__ so importing :mod:llm.evaluation.harness.lm_eval_lm
never raises on hosts without lm_eval installed. The
ImportError fires at __init__ time with the install hint.
Why a dedicated wrapper rather than reusing :class:HFLM?
HFLM's surface requires a torch.device and several HF-only
arguments (prefix_token, backend) that don't apply here.
A 100-line minimal adapter keeps the dependency tree honest and
the contract obvious.
LlamaLmEvalLM
¶
Minimal :class:lm_eval.api.model.LM adapter for DecoderModel.
Implements just enough of the lm_eval protocol to run the
standard multiple-choice (loglikelihood) and generation
(generate_until) tasks. Each request is processed individually
with a single forward pass; batch_size controls how many
requests are handled between no_grad context rebuilds and
Python-side bookkeeping, not the model's batch dimension.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
model
|
Any
|
A trained :class: |
必需 |
tokenizer
|
Any
|
Tokenizer with |
必需 |
batch_size
|
int
|
Maximum number of requests per forward pass. |
8
|
max_length
|
int | None
|
Hard cap on sequence length (model's
|
None
|
device
|
str | device | None
|
Target device; defaults to the model's parameter device. |
None
|
源代码位于: src/llm/evaluation/harness/lm_eval_lm.py
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 | |
loglikelihood
¶
Compute (log_likelihood, is_greedy_match) for each request.
Each request is an lm_eval.api.request.Request whose
args is (context_str, continuation_str). Returns a
list of (sum_logprob, is_greedy) tuples.
源代码位于: src/llm/evaluation/harness/lm_eval_lm.py
loglikelihood_rolling
¶
Compute total log-probability of each string (perplexity-style).
Returns list[float] — one scalar sum-log-prob per request,
matching the lm_eval LM.loglikelihood_rolling protocol.
源代码位于: src/llm/evaluation/harness/lm_eval_lm.py
generate_until
¶
Greedy generation until until token sequences appear.
Each request is an lm_eval.api.request.Request whose
args is (context_str, {"until": [...], "max_gen_toks": N}).
源代码位于: src/llm/evaluation/harness/lm_eval_lm.py
LmEvalAdapter — top-level driver¶
Preset lookup, kwarg merging, and structured result flattening on top
of lm_eval.evaluator.
adapter
¶
Adapter for lm-evaluation-harness.
Two responsibilities:
LmEvalAdapter— thin wrapper aroundlm_eval.evaluatorthat adds structured result handling and preset support.run_preset— convenience that ties a preset, an LM, and the evaluator together.
The :mod:llm.evaluation.harness.presets module is safe to import
without lm_eval installed; the lm_eval import boundary lives
here so the project's existing [eval] optional-dependency group
keeps working.
LmEvalAdapter
¶
Adapter for lm-evaluation-harness.
Adds:
- Preset lookup —
run_preset(preset_name, lm)resolves a :class:EvalPresetby name (built-in or user-supplied) and runs the benchmark. - Structured result flattening — :meth:
summarizeextractsacc/acc_norm/perplexity/f1/ etc. from the nested lm_eval result shape into a flat{task_name: {metric: value}}dict.
源代码位于: src/llm/evaluation/harness/adapter.py
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 | |
list_tasks
¶
evaluate
¶
Run evaluation on specified tasks.
Mirrors the lm_eval evaluator.evaluate signature; see
lm_eval docs for the kwargs surface.
源代码位于: src/llm/evaluation/harness/adapter.py
run_preset
¶
Run a benchmark by preset (name or :class:EvalPreset).
Merges the preset's :meth:EvalPreset.to_lm_eval_kwargs with
any caller-supplied kwargs (caller wins on conflicts).
源代码位于: src/llm/evaluation/harness/adapter.py
run_benchmark
¶
Run a single benchmark task by name (no preset lookup).
summarize
staticmethod
¶
Flatten lm_eval's nested result tree into a flat metric map.
lm_eval's evaluator.simple_evaluate returns:
.. code-block:: python
{
"results": {
"task_name": {
"acc,none": 0.42,
"acc_norm,none": 0.45,
...
},
...
},
"groups": {...},
"configs": {...},
}
This helper extracts the results block and splits each
comma-separated key ("acc,none" -> metric "acc",
subset "none") so callers can serialize it as a flat
dict.
Notes:
- Only the
resultsblock is flattened;groupsandconfigsare intentionally ignored. - Booleans are dropped (Python's
boolis a subclass ofint, but a metric of valueTrueis almost certainly a bug — string aliases are usually what you'd see). - Non-numeric values (e.g. string aliases) are silently skipped, keeping the output strictly numeric.
源代码位于: src/llm/evaluation/harness/adapter.py
run_preset
¶
Convenience entry point: build an adapter and run a preset.
End-to-end usage¶
See the Evaluation guide for a worked example (preset selection, result flattening, soft-dependency contract).