Deterministic metrics: exact match, regex, schema and numeric tolerance

Study time
≈ 1.5 h (estimate)
Needs
L2-M02-L05
Updated
2026-11-03

Progress is saved in this browser only. No account, nothing is sent to a server.

Draft · reviewed by AI, not yet by a person. Content may change. English translation: AI-assisted, not human-reviewed.
On this page

Module: L2-M03 · Duration: ~90 min (estimate, including the independent exercise) · Previous: L2-M02-L05 · Next: L02

1. Introduction

L2-M01 introduced three kinds of grader: code, human, model; L2-M02 gave us a versioned dataset. Now we need a metric function (a code grader) that scores each (case, answer) pair; the pass rate aggregated from it is the metric in the sense of L2-M01. This lesson teaches the cheapest kind: the deterministic metric function (same input, always the same result): exact match, regex (regular expression), finding a number in a reply, comparing numbers with a tolerance, and checking a schema (the structural template of a JSON document).

These functions are almost free, but they hide a question: is the metric itself correct? A hastily written function such as "24" in reply answers with great confidence and is wrong in predictable ways. This lesson teaches writing metric functions and then measuring the metric itself against human labels; the output is a set of tested functions, with a list of what each one does not check.

2. Learning objectives

  1. Choose between exact match, regex, number finding, tolerance and schema for a criterion, and state what each one does not check. Practice: §8.2, §8.3.
  2. Implement exact match with normalisation (NFC, case, whitespace). Practice: §8.2 part B.
  3. Write a number-finding function that matches the whole number, and a tolerance comparison with Fraction, including at the boundary. Practice: §8.3.
  4. Check JSON with a strict schema and point out three ways a loose metric gets bypassed (markdown fences, true in place of a number, duplicate keys). Practice: §8.2 part D, test_strict_json_rejects_fences_duplicates_and_nan.
  5. Measure a metric against human labels with precision and recall. Practice: §8.2 part A, exercise §9.

3. Prerequisites and tools

  • L2-M01-L03: code-based graders, the confusion matrix (tp, fp, fn, tn). This lesson applies the matrix to a metric.
  • Python 3.12 or later, pytest, the code lab code-labs/l2-m03 (self-contained, no API key).

4. Concepts

4.1 Metric, grader and deterministic function

In L2-M01 a grader decides whether one output passes, and a metric is the number aggregated from many gradings. In this module "metric function" means a deterministic grader: it takes a case and an answer and returns pass/fail with a reason. It needs three properties: the same input gives the same result; it never silently accepts broken input (None does not pass); and it knows exactly what it does not measure. Anthropic lists "string match" and "code-graded" among the automatic ways to grade [R1] and notes that a code grader is "Brittle to valid variations that don't match expected patterns exactly" [R2]: cheap, but it rejects valid variations and lets wrong variations through.

To talk about "is the metric correct", treat the metric as a classifier: it accepts or rejects an answer, while a human has decided whether that answer is really right or wrong. Four cells: tp (accepted, answer correct), fp (accepted, answer wrong: a false accept), fn (rejected, answer correct: a false reject), tn (rejected, answer wrong). Precision is, among the answers accepted, the fraction that are really correct: tp / (tp + fp). Recall is, among the answers that are really correct, the fraction that are accepted: tp / (tp + fn). When the denominator is 0 the lab returns None. For a high-risk criterion, a false accept costs more than a false reject.

The loop for checking a metric (diagram below): write the function with boundary tests, run it on answers that already have human labels, compute precision and recall, then either fix the function or accept the remaining false accepts and false rejects and record them in the "does not check" section.

Loop diagram: write the metric function with boundary tests → run it on replies that already have human labels → compute the metric's precision and recall → are the false accepts (fp) and false rejects (fn) acceptable? No: fix the function or change the metric type and repeat; Yes: record what the metric does not check.
Diagram: Metric, grader and deterministic function

4.2 Exact match and normalisation

Exact match compares two strings character by character. Anthropic describes it as "typically after normalizing whitespace and case", suited to answers with a clear category [R1]. Each normalisation step is a decision about what "correct" means: for the gold answer tạ (a Vietnamese weight unit, "quintal"), do Tạ, tạ and tạ. count as correct? The lab's exact_match normalises in this order: NFC, optionally strip punctuation, lowercase, collapse whitespace.

NFC (Normalization Form C) matters for Vietnamese because the same letter can be stored in two ways: ạ as one precomposed character, or a plus a separate dot-below mark. Unicode calls these two strings canonically equivalent; Form C uses the precomposed character "where possible" [R6]. Without normalising to NFC, two strings that look identical are still not equal. Normalisation does not turn ta into tạ.

An empty gold is rejected (otherwise an empty reply would "match" and pass), and an input that is not a string raises TypeError. OpenAI has a string check: eq returns 1 if the input matches the reference (case-sensitive) and 0 if not, suited to answers with a "straightforward pass or fail" [R3].

4.3 Regex: search within the string or match the whole string

Regex checks a pattern (a regex pattern): does the reply contain a number with a unit, does it have exactly the form "Đáp số: ..." ("Answer: ..."). The classic mistake is to confuse two modes: re.search asks "does the pattern appear anywhere", re.fullmatch asks "does the whole string match the pattern". regex_check(text, pattern, full=False) accepts both. The lab adds a cheap guard: a pattern that can match without consuming any character (it matches the empty string, or matches with width 0 like (?=[0-9]), \b) is rejected, because [0-9]* with re.search accepts every reply, so the test goes green while measuring nothing. The guard only tries a few sample strings and does not catch every bad pattern: a pattern that is too broad, or catastrophic backtracking (a regex that runs extremely slowly on some inputs), both get through.

5. Technical deep dive

5.1 Numbers in a reply: match the whole number

The first function everyone writes is "24" in reply (the lab calls it naive_contains). It is wrong for "Đáp số là 124 viên" (a reply giving a count of tablets), "Được 240 viên" (another such reply), "1.024 viên" (a third one), and wrong in the opposite direction too: gold 6.5 is not inside "6,5 mét" (a length in metres) because Vietnamese uses a decimal comma. extract_numbers(text) reads every number in the string as a Fraction (an exact fraction); contains_number(text, value) asks whether value is in that list. The reading rules, written in the docstring and pinned by tests:

String Read as Reason
được 6 viên. 6 A full stop at the end of a sentence has no digit after it
16 viên 16, does not contain 6 Match the whole number
6,5 13/2 One separator then digits: a decimal
1.000 1000 A head of 1-3 digits not starting with 0, then exactly 3 digits
0.125 1/8 The head starts with 0: a decimal
2.500 2500 Ambiguous, the lab chooses thousands; it cannot be read as 2.5
4,5,6 4, 5 and 6 Several separators not in thousands form
-24 -24 - directly before the number, not after a letter or digit
24.5kg, 2,5m not read A number stuck to letters is not read

to_fraction (used for the gold) reads a string as an ordinary decimal with no thousands separator: to_fraction("1.000") is 1 while extract_numbers reads 1.000 as 1000, so write the gold without a thousands separator. Numbers written in words and full-width digits are not read, and "Không phải 24 đâu em" (a negated reply) still contains 24. contains_number means "the reply states that number", not "the reply is correct".

5.2 Numeric tolerance, exact arithmetic with Fraction

When the answer is a measurement that should accept a small deviation, use a tolerance. Python's math.isclose uses abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol); against 0, isclose(x, 0) is false for every x other than 0 unless a positive abs_tol is given, and NaN is close to no value, not even itself [R4]. The lab's numeric_close(pred, gold, abs_tol, rel_tol) computes with Fraction so the boundary is compared exactly (inclusive: a deviation exactly equal to the tolerance passes), with three differences:

  • The relative part uses only the gold, so the acceptance interval does not shift with the answer: numeric_close(95, 100, rel_tol=0.05) is true, numeric_close(100, 95, rel_tol=0.05) is false because 5 > 0.05 × 95.
  • A float is converted through its shortest string form, so 0.1 + 0.2 is 0.30000000000000004 and is not treated as 0.3; to ignore that noise you must give an abs_tol.
  • bool, NaN, infinity and unknown types are rejected.

The function does not check units, significant digits, or whether the tolerance is reasonable.

5.3 Schema check and strict JSON

When the system must return JSON (L1-M05), the most useful deterministic metric is a schema check. validate(instance, schema) understands a small set of keywords (type, required, properties, additionalProperties, enum, minimum, maximum, string length, items, array length) and returns a list of errors with paths ($.score: expected integer, got bool). Three choices against bypasses:

  • An unknown keyword raises an error. A schema containing pattern, which the function has not implemented, raises ValueError instead of being ignored and reported "valid"; additionalProperties accepts only true/false, and a schema-valued form also raises. enum compares as JSON: True is not equal to 1.
  • bool is not a number. In Python True is an int; in JSON it is not. And 2.0 is an integer, because JSON Schema says integer matches "any number with a zero fractional part" [R5].
  • Strict JSON. parse_json_strict requires the whole reply to be one JSON value: wrapping markdown fences (three backticks) make it fail, duplicate keys make it fail (json.loads silently keeps the last key by default), and NaN makes it fail.

The specification says minimum and maximum are inclusive bounds [R5]; this lesson reads only the validation part, and additionalProperties, which belongs to the core specification, is not read. Passing the schema can still be wrong: {"verdict": "ok", "score": 3} is valid even when the right answer is bad. A schema measures shape, not content.

6. The QA perspective

6.1 Measuring the metric itself: precision and recall against human labels

The lab has 30 fictional answers for the results 24; 6.5; 1000 or 2.5 (data/l01_numbers.jsonl), each with a human label "states the right result": 16 are correct. Two metrics:

Metric tp fp fn tn precision recall
Substring (naive_contains) 11 6 5 8 0.647 0.688
Whole-number match (contains_number) 15 3 1 11 0.833 0.938

The substring metric falsely accepts 6 and falsely rejects 5. Whole-number match still falsely accepts 3: N04 ("Không phải 24 đâu em": negation), N09 ("Có thể là 24 hoặc 25": hedged), N25 ("Tổng cộng 1,000 viên", gold 1000: a Vietnamese reader takes 1,000 as one, the function reads it as an English-style thousands separator); and falsely rejects 1: N08, "Hai mươi bốn viên" (the number in words). Each error is a named blind spot.

Exact match on 12 short answers (7 correct): with no normalisation it accepts 1 correct answer, with case and whitespace normalisation it accepts 4, and adding punctuation stripping gives 5. All three produce no false accept (fp = 0) but wrongly reject most of the correct answers ("tạ, tức 100 ki-lô-gam" and "Đáp án là tạ" are rejected in every variant): the typical shape of a strict metric, high precision, low recall. The sample sizes 30 and 12 are small: the rates describe only the lab.

6.2 What each metric does not check, and how they get bypassed

Metric Catches Does not check
exact_match Case, whitespace, Unicode form Synonyms, longer phrasing, missing diacritics
regex_check One defined form; a pattern matching empty or width 0 (via a few trial strings) A pattern right on the examples tried but wrong on others, backtracking
contains_number A whole number, including 24,0; the minus sign (-24 does not contain 24) Negation, hedging, numbers in words, 2.500, English-style 1,000, a number stuck to a unit (24.5kg, 2,5m: not read, so never "contained")
numeric_close A deviation within tolerance, exactly at the boundary Units, significant digits
validate Missing keys, wrong types, out of range, extra keys Whether the content is right or wrong

Three inputs to try on every metric, following the advice "Make your graders resistant to bypasses or hacks" [R2]: the empty string, an input of the wrong type (None, a number instead of a string), and a hedged answer. The first two can be caught by the function; the third cannot: it needs a small sample reviewed by a human (L2-M05).

6.3 Writing tests for the metric function itself

A minimal test suite has: correct answers in several forms (24, 24,0, Đáp số: 24), near-miss wrong answers (124, 240, 1.024), boundaries (tolerance exactly at the edge, and on both sides of it), empty and wrong type, and known blind-spot cases (a test that asserts the current behaviour, with a comment). The lab puts test_whole_number_match_beats_substring next to test_contains_number_does_not_read_negation_or_locale: one test proves what the function can do, the other pins what it cannot do.

7. Real-world scenarios

Scenario 1 (fictional): "Green tests, wrong answers". The HocVui Tutor team wrote the metric "states the right result" as str(gold) in reply and reported 92% passing. A manual reviewer saw many "passing" replies passing only because 124, 240, 1.024 contain 24. Measuring against human labels (§6.1) gives a precision of 0.647. They switched to whole-number match (0.833) and recorded the three remaining blind spots.

Scenario 2 (fictional): "The schema got bypassed". The original metric ran json.loads and then checked the key verdict. The system sometimes wraps its JSON in a markdown fence, json.loads raises, the team caught the error and counted it as "skipped": the pass rate came out higher than the truth. With the lab's grade_cases, a metric that raises is counted as a fail with a reason.

8. Hands-on tutorial

8.1 Setup

cd academy-content/code-labs/l2-m03
python3 -m venv .venv && source .venv/bin/activate     # Windows: .venv\Scripts\activate
python -m pip install -r requirements.txt
python -m pytest            # 63 passed

8.2 Run the demo

python -m lab.demo l01

Output (copied from a real run on Python 3.14.6 and 3.12.14, 2026-11-03; the two versions give identical output):

A. does the reply state the right number? 30 replies, human truth: 16 correct
   substring    tp=11 fp=6 fn=5 tn=8  precision 0.647 recall 0.688
                false accepts ['N04', 'N05', 'N06', 'N09', 'N10', 'N26']  false rejects ['N08', 'N17', 'N21', 'N22', 'N27']
   whole number tp=15 fp=3 fn=1 tn=11  precision 0.833 recall 0.938
                false accepts ['N04', 'N09', 'N25']  false rejects ['N08']
B. exact match on 12 short answers, three normalisations (tp of 7 correct, fp)
   none          tp=1 fp=0
   case+space    tp=4 fp=0
   +punctuation  tp=5 fp=0
C. numeric tolerance, computed exactly
   0.1 + 0.2 as the float 0.30000000000000004
   equal to 0.3 with no tolerance: False
   equal to 0.3 with abs_tol 1e-9: True
   6.55 vs 6.5, abs_tol 0.05 (edge, inclusive): True
   95 vs 100 and 100 vs 95 at rel_tol 0.05: True / False
D. schema check of four replies
   {"verdict": "ok", "score": 3}                -> 0 error(s)
   {"verdict": "meh", "score": 4, "extra": 1}   -> 3 error(s)
   {"verdict": "ok", "score": true}             -> 1 error(s)
   same JSON inside a markdown code fence       -> 1 error(s)

Reading the output:

  • A. The substring metric falsely accepts 6 and falsely rejects 5; whole-number match falsely accepts 3 (N04, N09, N25) and falsely rejects 1 (N08). Open data/l01_numbers.jsonl and read each of these ids.
  • B. All three give fp = 0 but accept only 1, 4 and 5 of the 7 correct answers.
  • C. The two numbers 95 and 100 give different results depending on direction because the relative part uses the gold; 6.55 against 6.5 with tolerance 0.05 passes right at the edge.
  • D. Four replies: valid; wrong enum, over maximum and an extra key (3 errors); true where a number is required (1 error); JSON inside a markdown fence (1 error).

8.3 Try the boundaries yourself

Save it as try_l01.py in the lab's root folder (next to lab/) (next to lab/), run python try_l01.py, then delete the file:

from lab import deterministic as d

# 1. whole number versus substring
for reply in ["Đáp số là 124 viên.", "Được 6 viên.", "Tổng cộng 1.000 viên.", "Kết quả là 2.500.", "Kết quả là -24.", "Đáp số 24.5kg"]:
    print(repr(reply), [str(x) for x in d.extract_numbers(reply)])
print(d.naive_contains("Đáp số là 124 viên.", "24"), d.contains_number("Đáp số là 124 viên.", "24"))

# 2. a regex that matches the empty string is refused
try:
    d.regex_check("anything", r"[0-9]*")
except ValueError as e:
    print("ValueError:", e)

# 3. tolerance at the edge
print(d.numeric_close("6.55", "6.5", abs_tol="0.05"), d.numeric_close("6.5500001", "6.5", abs_tol="0.05"))

# 4. schema errors
schema = {"type": "object", "required": ["score"], "properties": {"score": {"type": "integer", "minimum": 0, "maximum": 3}}}
print(d.schema_check('{"score": true}', schema))
print(d.schema_check('{"score": 2.0}', schema))

Output (identical on Python 3.14.6 and 3.12.14):

'Đáp số là 124 viên.' ['124']
'Được 6 viên.' ['6']
'Tổng cộng 1.000 viên.' ['1000']
'Kết quả là 2.500.' ['2500']
'Kết quả là -24.' ['-24']
'Đáp số 24.5kg' []
True False
ValueError: pattern '[0-9]*' matches without consuming text and would accept any reply
True False
['$.score: expected integer, got bool']
[]

Reading: -24 is a negative number and 24.5kg is not read (§5.1); 2.500 is 2500; the pattern [0-9]* is rejected; a tolerance exactly at the edge passes; 2.0 is a valid integer while true is not.

8.4 Run the lesson's tests

python -m pytest tests/test_l01_deterministic.py -v

Result: 21 passed. Read test_exact_match_fails_closed, test_metric_vs_human_truth_on_shipped_numbers and test_numeric_tolerance_boundary_is_inclusive_and_exact.

8.5 Troubleshooting

Symptom Cause Fix
ValueError: pattern ... matches without consuming text The pattern can match empty or at width 0 (*, ?, (?=...)) Narrow it with + or an anchor
A Unicode test fails on another machine The file is in NFD form Convert to NFC (tests/test_lab_hygiene.py)

9. Independent exercise

Problem: Write the metric "length answer" for a fictional HocVui Tutor feature, measure a naive rule, and record the blind spots.

Requirements: complete exercises/test_l01_metrics.py:

  1. TODO 1: write answer_ok(reply, gold) with gold = "2,5 m". It passes if and only if the reply contains the same numeric value (2,5, 2.5, 2,50 count as the same) immediately before the unit m or mét (one space or none), each as a whole token. It must not pass: 12,5 m, 25 m, 2,5 mm, 2,5 mẫu, 2,5 m2, a missing unit, the empty string, a changed unit (250 cm).
  2. TODO 2: fill in NAIVE_FALSE_ACCEPTS (the ids that the naive rule "both the string 2,5 and the string m appear in the reply" accepts while the human label is wrong) and NAIVE_PRECISION (the precision of the naive rule on all 18 answers, written as a fraction string such as "3/5").
  3. TODO 3: write the blind-spot note (see Deliverable).

Test data: exercises/length_cases.json (18 fictional answers with labels). The test adds boundary cases from outside the file: answer_ok("13 m", "3 m") is false, and the gold may be 0.5 m.

Deliverable: answer_ok, NAIVE_FALSE_ACCEPTS, NAIVE_PRECISION, and at the end of the file exercises/test_l01_metrics.py one comment line # BLIND SPOTS: followed by at least two more comment lines, each of at least 5 words, stating what your answer_ok does not check.

Acceptance criteria: python -m pytest exercises/test_l01_metrics.py passes (4 tests, of which test_blind_spots_comment_exists reads the file itself). The test only counts lines and words; whether the blind spots are real is for you and a reviewer to judge.

Hint: try 12,5 m and 2,5 mm first. Think about token boundaries on both sides of the number and of the unit; you can use deterministic.to_fraction to compare values.

10. Knowledge check

0/18 done · Results are kept in this browser only.

P02 · True or false

An answer that passes validate with the schema {"verdict": "ok", "score": 3} has correct content.

P04 · Select all that apply

With gold 24, which answers does contains_number(reply, "24") accept? Select all that apply.

P05 · Put in order

Put the loop for checking a metric function in order (diagram in §4.1).

  1. Compute the metric's precision and recall from the tp, fp, fn, tn matrix
  2. Read the leaked and falsely rejected answers, and decide what level is acceptable
  3. Write the function with boundary tests
  4. Fix the function or change the metric type, or write down what the metric does not check
  5. Run the function on the answers that already have human labels

P06 · Match

Match each metric function with what it does not check.

P07 · Spot the bug

The function below computes the schema pass rate of a batch of replies, but it has a bug that makes the rate higher than the real one when the system sometimes wraps the JSON in a markdown fence. Find the bug.

import json
from lab.deterministic import validate

def schema_pass_rate(replies, schema):
    passed = total = 0
    for reply in replies:
        try:
            errors = validate(json.loads(reply), schema)
        except ValueError:
            continue
        total += 1
        passed += not errors
    return passed / total

P08 · Short answer

Write two "not checked" lines for contains_number so the report reader knows what still leaks and what is falsely rejected, based on the three sentences N04, N09 and N08.

P09 · Essay

The team ran exact_match on 12 short answers (7 of them correct) and saw fp = 0 at all three normalization levels, so it concluded "the metric is safe". Write 5-8 sentences: where that conclusion is half right, what the other half is missing, and what you would write in the blind-spot section.

P10 · Recall

Lesson: L2-M01-L03

According to L2-M01-L03 §4.1, what is the characteristic weakness of a code grader, and which sentence in this lesson's lab illustrates it?

P11 · Select all that apply

Which numeric_close calls return False? Select all that apply.

P12 · True or false

With every exact_match normalization step on (NFC, strip punctuation, lowercase, collapse whitespace), "ta" and "tạ" are treated as the same answer.

P13 · Fill in the blank

Run schema_check with the schema verdict in ok or bad, score an integer from 0 to 3, no extra keys. The number of errors: {"verdict": "meh", "score": 4, "extra": 1} gets ___ errors, {"verdict": "ok", "score": true} gets ___ errors, and the same JSON {"verdict": "ok", "score": 3} wrapped in a markdown fence gets ___ errors.

P14 · Select all that apply

Three inputs to try on every metric are the empty string, a wrong-type input and a hedged answer. Select all that correctly describe what a metric function can do by itself.

P15 · Recall

Lesson: L2-M02-L05

The set of 30 human-labeled answers gets 6 more answers and the labels of 2 old ones are corrected. By the convention of L2-M02-L05 §4.1, which version level must go up?

P16 · Multiple choice

The team checks "states 24" with regex_check(reply, r"24"). For the sentence "Đáp số: 124" ("The answer: one hundred twenty-four"), what is the result and the right fix?

P17 · Multiple choice

What does extract_numbers("Kết quả là 2.500.") ("The result is two thousand five hundred, or two point five.") return?

11. Summary

  • Concepts: a deterministic metric function is a pure function of (case, answer); each normalisation step is a decision about the definition; the metric's precision and recall against human labels.
  • Skills: matching with NFC; regex search versus fullmatch; reading numbers and tolerance with Fraction; a strict schema.
  • Traps: "24" in reply; a pattern that matches empty; relative tolerance when the gold is 0; raising an error and treating it as skipped; believing that passing the schema means correct.
  • You can now: write a metric function, measure it on labelled answers, and say which kinds of answers it falsely accepts and falsely rejects.

12. References

ID Title Publisher URL Accessed Relevance
R1 Define success criteria and build evaluations (Develop tests) Anthropic https://platform.claude.com/docs/en/test-and-evaluate/develop-tests 2026-11-03 Exact match, code-graded (read 100,000/152,950 characters)
R2 Demystifying evals for AI agents Anthropic https://www.anthropic.com/engineering/demystifying-evals-for-ai-agents 2026-11-03 Weaknesses of code graders; resisting bypasses
R3 Graders (string check graders) OpenAI https://developers.openai.com/api/docs/guides/graders 2026-11-03 String check eq
R4 math.isclose Python Software Foundation https://docs.python.org/3/library/math.html 2026-11-03 Tolerance formula, comparison with 0, NaN
R5 JSON Schema Validation, draft 2020-12 JSON Schema organization https://json-schema.org/draft/2020-12/json-schema-validation 2026-11-03 integer, minimum, maximum (validation part only)
R6 UAX #15: Unicode Normalization Forms Unicode Consortium https://www.unicode.org/reports/tr15/ 2026-11-03 NFC, canonical equivalence (introduction)

Key terms (English ↔ Vietnamese)

English Tiếng Việt
Deterministic metric Hàm metric tất định (grader bằng code; cùng đầu vào, cùng kết quả)
Exact match So khớp chính xác
Normalisation (NFC) Chuẩn hóa (NFC của Unicode)
Regex Regex (biểu thức chính quy)
Tolerance Dung sai (tuyệt đối, tương đối)
Schema check Kiểm schema (khuôn cấu trúc JSON)
Precision Precision: tỷ lệ đúng trong số câu metric chấp nhận
Recall Recall: tỷ lệ metric chấp nhận trong số câu thật sự đúng
False accept / false reject Lọt (chấp nhận câu sai) / oan (từ chối câu đúng)
Fail closed Từ chối khi đầu vào hỏng