geudrik's picture
download
raw
44.4 kB
"""Deterministic 8-case selection and concurrency benchmark suite for Clairic 27B.
Covers the primary execution paths in `clairic_runtime`:
1. Text scalar + list extraction (parallel AR + literal grounding + spans + p_null)
2. SaaS contract table-row object extraction + absent nullable fields (_null_recovery)
3. Single-image itemized receipt (ViT + image_rows inventory/cohort + AR)
4. Two-page Purchase Order images (27B scalar detail view + PO spelling + multi-salt media groups)
5. Pure ClairicHead readout (compute + estimate + multi-step forecast w/ quantiles + duration)
6. Hybrid multimodal + AR extraction + ClairicHead compute/estimate/forecast in one request
7. Long-context (10K+ chars) financial/operations report with both AR and ClairicHead fields
8. Fast compact triage schema (latency/concurrency floor)
Note: The boundary-protected NVFP4+FP8 layer map (`0..3, 56..63` in FP8) was selected after
observing a `case5.closing_inventory` defect on an all-MLP NVFP4 checkpoint on this 8-case suite.
Use `heldout_suite.py` (12 disjoint cases) for out-of-sample validation.
"""
from __future__ import annotations
import base64
import io
import math
from typing import Any
from PIL import Image, ImageDraw, ImageFont
def _font(size: int = 22, bold: bool = False) -> Any:
candidates = (
[
"/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
"/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf",
]
if bold
else [
"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
"/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf",
]
)
for path in candidates:
try:
return ImageFont.truetype(path, size=size)
except OSError:
continue
try:
return ImageFont.load_default(size=size)
except TypeError:
return ImageFont.load_default()
def _png_data_uri(img: Image.Image) -> str:
buf = io.BytesIO()
img.save(buf, format="PNG")
return "data:image/png;base64," + base64.b64encode(buf.getvalue()).decode("ascii")
def render_receipt_image() -> str:
img = Image.new("RGB", (760, 960), "white")
draw = ImageDraw.Draw(img)
f_title = _font(30, bold=True)
f_head = _font(22, bold=True)
f_body = _font(20, bold=False)
y = 40
draw.text((220, y), "HARBORVIEW ROASTERS", fill="black", font=f_title)
y += 44
draw.text((210, y), "418 Pier Ave, Seattle, WA 98101", fill="black", font=f_body)
y += 32
draw.text((235, y), "Receipt #: HVR-2026-8841", fill="black", font=f_body)
y += 30
draw.text((245, y), "Date: 2026-10-14 08:42", fill="black", font=f_body)
y += 40
draw.line((50, y, 710, y), fill="black", width=2)
y += 18
draw.text((60, y), "ITEM", fill="black", font=f_head)
draw.text((460, y), "QTY", fill="black", font=f_head)
draw.text((590, y), "AMOUNT", fill="black", font=f_head)
y += 34
draw.line((50, y, 710, y), fill="black", width=1)
y += 20
rows = [
("Cortado 8oz", "2", "9.50"),
("Almond Croissant", "1", "5.25"),
("Whole Bean Ethiopia 340g", "1", "19.00"),
("Sparkling Water", "2", "6.00"),
]
for name, qty, amt in rows:
draw.text((60, y), name, fill="black", font=f_body)
draw.text((475, y), qty, fill="black", font=f_body)
draw.text((595, y), f"${amt}", fill="black", font=f_body)
y += 38
y += 16
draw.line((50, y, 710, y), fill="black", width=2)
y += 22
draw.text((430, y), "Subtotal:", fill="black", font=f_body)
draw.text((595, y), "$39.75", fill="black", font=f_body)
y += 34
draw.text((430, y), "Sales Tax:", fill="black", font=f_body)
draw.text((595, y), "$4.01", fill="black", font=f_body)
y += 34
draw.text((430, y), "Tip:", fill="black", font=f_body)
draw.text((595, y), "$6.00", fill="black", font=f_body)
y += 40
draw.text((430, y), "TOTAL PAID:", fill="black", font=f_head)
draw.text((590, y), "$49.76", fill="black", font=f_head)
y += 55
draw.text((60, y), "Payment Method: Visa Contactless **** 4912", fill="black", font=f_body)
return _png_data_uri(img)
def render_po_pages() -> list[str]:
p1 = Image.new("RGB", (900, 1100), "white")
d1 = ImageDraw.Draw(p1)
f_title = _font(32, bold=True)
f_head = _font(22, bold=True)
f_body = _font(20, bold=False)
d1.text((60, 45), "PURCHASE ORDER", fill="black", font=f_title)
d1.text((560, 52), "PO Number: PO-94720-BX", fill="black", font=f_head)
d1.text((560, 88), "Issue Date: 2026-11-03", fill="black", font=f_body)
d1.text((560, 118), "Page 1 of 2", fill="black", font=f_body)
d1.line((60, 160, 840, 160), fill="black", width=2)
d1.text((60, 185), "BUYER:", fill="black", font=f_head)
d1.text((60, 218), "Kestrel Robotics Inc.", fill="black", font=f_body)
d1.text((60, 248), "1200 Industrial Pkwy, Austin, TX", fill="black", font=f_body)
d1.text((480, 185), "VENDOR:", fill="black", font=f_head)
d1.text((480, 218), "Apex Precision Optics LLC", fill="black", font=f_body)
d1.text((480, 248), "77 Photonics Way, Boulder, CO", fill="black", font=f_body)
d1.line((60, 305, 840, 305), fill="black", width=2)
d1.text((60, 325), "SKU", fill="black", font=f_head)
d1.text((220, 325), "DESCRIPTION", fill="black", font=f_head)
d1.text((590, 325), "QTY", fill="black", font=f_head)
d1.text((690, 325), "LINE TOTAL", fill="black", font=f_head)
d1.line((60, 360, 840, 360), fill="black", width=1)
p1_items = [
("APO-LENS-12", "12mm Telecentric C-Mount Lens", "10", "$4,200.00"),
("APO-FILT-850", "850nm Bandpass Optical Filter", "25", "$1,875.00"),
]
y = 385
for sku, desc, qty, total in p1_items:
d1.text((60, y), sku, fill="black", font=f_body)
d1.text((220, y), desc, fill="black", font=f_body)
d1.text((600, y), qty, fill="black", font=f_body)
d1.text((695, y), total, fill="black", font=f_body)
y += 46
d1.text((60, 980), "Continued on Page 2...", fill="black", font=f_body)
p2 = Image.new("RGB", (900, 1100), "white")
d2 = ImageDraw.Draw(p2)
d2.text((60, 45), "PURCHASE ORDER (CONTINUED)", fill="black", font=f_head)
d2.text((560, 45), "PO Number: PO-94720-BX", fill="black", font=f_head)
d2.text((560, 80), "Page 2 of 2", fill="black", font=f_body)
d2.line((60, 125, 840, 125), fill="black", width=2)
d2.text((60, 150), "SKU", fill="black", font=f_head)
d2.text((220, 150), "DESCRIPTION", fill="black", font=f_head)
d2.text((590, 150), "QTY", fill="black", font=f_head)
d2.text((690, 150), "LINE TOTAL", fill="black", font=f_head)
d2.line((60, 185, 840, 185), fill="black", width=1)
d2.text((60, 210), "APO-CAL-GRID", fill="black", font=f_body)
d2.text((220, y := 210), "Glass Distortion Calibration Target", fill="black", font=f_body)
d2.text((600, y), "4", fill="black", font=f_body)
d2.text((695, y), "$1,120.00", fill="black", font=f_body)
d2.line((60, 310, 840, 310), fill="black", width=2)
d2.text((480, 340), "Items Subtotal:", fill="black", font=f_body)
d2.text((695, 340), "$7,195.00", fill="black", font=f_body)
d2.text((480, 380), "Insured Freight:", fill="black", font=f_body)
d2.text((695, 380), "$185.00", fill="black", font=f_body)
d2.text((480, 430), "GRAND TOTAL (USD):", fill="black", font=f_head)
d2.text((690, 430), "$7,380.00", fill="black", font=f_head)
d2.text((60, 520), "Payment Terms: Net 30 Days. Tax Exempt Certificate on file.", fill="black", font=f_body)
return [_png_data_uri(p1), _png_data_uri(p2)]
def build_suite() -> list[dict[str, Any]]:
receipt_uri = render_receipt_image()
po_uris = render_po_pages()
long_sections = []
for region_idx, (region, rev, tickets, sla) in enumerate(
[
("US-West", "1,420,500.00", 312, "99.94%"),
("US-East", "2,185,000.00", 489, "99.91%"),
("EU-Central", "1,760,250.00", 275, "99.97%"),
("AP-Northeast", "980,750.00", 194, "99.89%"),
("UK-South", "845,100.00", 163, "99.95%"),
("CA-Central", "512,400.00", 98, "99.96%"),
],
start=1,
):
filler = (
f"Section {region_idx} ({region} Operations): During Q3 2026, regional cluster {region} "
f"processed enterprise edge workloads across 14 availability zones with zero Priority-0 outages. "
f"Recognized quarterly recurring revenue for {region} reached ${rev} across {tickets} active enterprise "
f"support escalations, maintaining an observed uptime SLA of {sla}. Capacity expansion for {region} "
f"remains on schedule with standardized rack deployments, fiber cross-connect audits, automated "
f"BGP failover drills, and quarterly thermal envelope verification completed without incident. "
) * 3
long_sections.append(filler)
long_report_state = (
"GLOBAL OPERATIONS & REVENUE BRIEFING — Q3 2026\n"
"Prepared by: Meridian Cloud Infrastructure Finance\n"
"Report Date: 2026-10-05\n"
"Executive Summary: Total consolidated Q3 2026 ARR stood at $30,816,000.00 with 1,531 total tickets.\n"
"Historical quarterly ARR ($M) over the past 6 quarters: 22.4, 24.1, 25.8, 27.3, 29.0, 30.8.\n\n"
+ "\n\n".join(long_sections)
)
return [
{
"id": "case1_text_invoice",
"category": "ar_text_scalars_and_list",
"request": {
"state": (
"INVOICE #INV-2026-0419\n"
"Vendor: Northwind Industrial Supply Co.\n"
"Customer: Cascade BioLabs\n"
"Issued: 2026-09-02 | Due: 2026-10-02\n"
"Currency: USD\n"
"Line Items:\n"
"- Sterile Pipette Tips (10 boxes): $420.00\n"
"- Borosilicate Beaker Set: $310.50\n"
"- Nitrile Gloves Case: $349.50\n"
"Subtotal: $1,080.00\n"
"Tax: $0.00 (Research Exempt)\n"
"Total Due: $1,080.00\n"
"Status: UNPAID"
),
"fields": {
"invoice_number": {"type": "text", "instructions": "The invoice identifier."},
"vendor": {"type": "text", "instructions": "The issuing vendor name."},
"issued_date": {"type": "date", "instructions": "The printed invoice issue date."},
"due_date": {"type": "date", "instructions": "The printed payment due date."},
"total_due": {"type": "number", "decimals": 2, "source_only": True, "instructions": "Total amount due."},
"tax_exempt": {"type": "boolean", "instructions": "Whether the invoice is marked tax or research exempt."},
"status": {"type": "enum", "enum": ["PAID", "UNPAID", "VOID"], "instructions": "Payment status."},
"purchase_order": {"type": "text", "instructions": "Customer PO number if explicitly stated."},
"item_names": {
"type": "list",
"items": "text",
"instructions": "Purchased line item names in order, excluding prices.",
},
},
},
"expected": {
"invoice_number": "INV-2026-0419",
"vendor": "Northwind Industrial Supply Co.",
"issued_date": "2026-09-02",
"due_date": "2026-10-02",
"total_due": 1080.0,
"tax_exempt": True,
"status": "UNPAID",
"purchase_order": None,
},
"expected_all": {
"invoice_number": "INV-2026-0419",
"vendor": "Northwind Industrial Supply Co.",
"issued_date": "2026-09-02",
"due_date": "2026-10-02",
"total_due": 1080.0,
"tax_exempt": True,
"status": "UNPAID",
"purchase_order": None,
"item_names": [
"Sterile Pipette Tips (10 boxes)",
"Borosilicate Beaker Set",
"Nitrile Gloves Case",
],
},
},
{
"id": "case2_text_table_objects",
"category": "ar_table_objects_and_nulls",
"request": {
"state": (
"Order Summary — Reference: ORD-7712\n"
"Account Manager: Elena Rostova\n"
"Discount Code: NONE APPLIED\n\n"
"| SKU | Plan | Seats | Annual Fee |\n"
"|---|---|---|---|\n"
"| ENT-CORE | Enterprise Core | 150 | 45000.00 |\n"
"| SEC-AUDIT | Audit Log Add-on | 150 | 9000.00 |\n"
"| SUP-24X7 | Dedicated TAM | 1 | 12000.00 |\n"
),
"fields": {
"order_ref": {"type": "text", "instructions": "Order reference code."},
"account_manager": {"type": "text", "instructions": "Named account manager."},
"vat_registration": {"type": "text", "instructions": "Customer VAT registration number if printed."},
"subscriptions": {
"type": "list",
"items": {
"type": "object",
"properties": {
"sku": {"type": "text", "instructions": "SKU code."},
"seats": {"type": "number", "integer": True, "instructions": "Seat count."},
"annual_fee": {"type": "number", "decimals": 2, "instructions": "Annual fee."},
},
},
"instructions": "Extract each subscription row in table order.",
},
},
},
"expected": {
"order_ref": "ORD-7712",
"account_manager": "Elena Rostova",
"vat_registration": None,
},
"expected_all": {
"order_ref": "ORD-7712",
"account_manager": "Elena Rostova",
"vat_registration": None,
"subscriptions": [
{"sku": "ENT-CORE", "seats": 150, "annual_fee": 45000.0},
{"sku": "SEC-AUDIT", "seats": 150, "annual_fee": 9000.0},
{"sku": "SUP-24X7", "seats": 1, "annual_fee": 12000.0},
],
},
},
{
"id": "case3_image_receipt",
"category": "multimodal_receipt_ar",
"request": {
"state": "Extract the receipt header, totals, and purchased items from the attached receipt image.",
"images": [receipt_uri],
"fields": {
"merchant": {"type": "text", "instructions": "Merchant name at top of receipt."},
"receipt_number": {"type": "text", "instructions": "Printed receipt number."},
"receipt_date": {"type": "date", "instructions": "Printed receipt date."},
"subtotal": {"type": "number", "decimals": 2, "source_only": True, "instructions": "Subtotal before tax and tip."},
"tax": {"type": "number", "decimals": 2, "source_only": True, "instructions": "Sales tax amount."},
"total_paid": {"type": "number", "decimals": 2, "source_only": True, "instructions": "Final total paid."},
"line_items": {
"type": "list",
"items": {
"type": "object",
"properties": {
"name": {"type": "text", "instructions": "Item name."},
"qty": {"type": "number", "integer": True, "instructions": "Quantity."},
"amount": {"type": "number", "decimals": 2, "instructions": "Line dollar amount."},
},
},
"instructions": "Purchased items in receipt order.",
},
},
},
"expected": {
"merchant": "HARBORVIEW ROASTERS",
"receipt_number": "HVR-2026-8841",
"receipt_date": "2026-10-14",
"subtotal": 39.75,
"tax": 4.01,
"total_paid": 49.76,
},
"expected_all": {
"merchant": "HARBORVIEW ROASTERS",
"receipt_number": "HVR-2026-8841",
"receipt_date": "2026-10-14",
"subtotal": 39.75,
"tax": 4.01,
"total_paid": 49.76,
"line_items": [
{"name": "Cortado 8oz", "qty": 2, "amount": 9.5},
{"name": "Almond Croissant", "qty": 1, "amount": 5.25},
{"name": "Whole Bean Ethiopia 340g", "qty": 1, "amount": 19.0},
{"name": "Sparkling Water", "qty": 2, "amount": 6.0},
],
},
},
{
"id": "case4_two_page_po_images",
"category": "multimodal_two_page_po_detail",
"request": {
"state": "Two-page purchase order scan.",
"images": po_uris,
"fields": {
"po_number": {"type": "text", "instructions": "Purchase order reference number."},
"buyer_name": {"type": "text", "instructions": "Buyer company name."},
"vendor_name": {"type": "text", "instructions": "Vendor company name."},
"issue_date": {"type": "date", "instructions": "Printed PO issue date."},
"freight": {"type": "number", "decimals": 2, "source_only": True, "instructions": "Insured freight charge."},
"grand_total": {"type": "number", "decimals": 2, "source_only": True, "instructions": "Grand total USD on page 2."},
"tax_exempt": {"type": "boolean", "instructions": "Whether tax exempt certificate is noted on file."},
"skus": {
"type": "list",
"items": "text",
"instructions": "All ordered SKU codes across both pages in order.",
},
},
},
"expected": {
"po_number": "PO-94720-BX",
"buyer_name": "Kestrel Robotics Inc.",
"vendor_name": "Apex Precision Optics LLC",
"issue_date": "2026-11-03",
"freight": 185.00,
"grand_total": 7380.00,
"tax_exempt": True,
},
"expected_all": {
"po_number": "PO-94720-BX",
"buyer_name": "Kestrel Robotics Inc.",
"vendor_name": "Apex Precision Optics LLC",
"issue_date": "2026-11-03",
"freight": 185.00,
"grand_total": 7380.00,
"tax_exempt": True,
"skus": ["APO-LENS-12", "APO-FILT-850", "APO-CAL-GRID"],
},
},
{
"id": "case5_clairic_head_typed",
"category": "clairic_head_compute_estimate_forecast",
"request": {
"state": (
"Warehouse telemetry for SKU-400:\n"
"- Opening inventory: 1,250 units\n"
"- Inbound shipment received: 400 units\n"
"- Damaged/quarantined units: 35 units\n"
"- Fulfilled customer orders: 615 units\n"
"- Picking shift duration: 6 hours 30 minutes\n"
"- Daily outbound demand over the last 7 days (units): 82, 85, 84, 88, 90, 89, 92."
),
"reference_date": "2026-11-01",
"fields": {
"closing_inventory": {
"type": "compute",
"decimals": 0,
"instructions": "Compute closing sellable inventory: opening + inbound - damaged - fulfilled.",
},
"net_change": {
"type": "compute",
"decimals": 0,
"instructions": "Compute net sellable inventory change (inbound - damaged - fulfilled).",
},
"shift_minutes": {
"type": "duration",
"unit": "minutes",
"instructions": "Picking shift duration in minutes.",
},
"next_day_demand": {
"type": "estimate",
"min": 50,
"max": 150,
"instructions": "Estimated outbound demand tomorrow.",
},
"four_day_demand_forecast": {
"type": "forecast",
"min": 50,
"max": 150,
"horizon": 4,
"interval": "day",
"instructions": "Forecast daily outbound demand for the next 4 days.",
},
},
"options": {"include_quantiles": True},
},
"expected": {
"closing_inventory": 1000,
"net_change": -250,
},
"expected_all": {
"closing_inventory": 1000,
"net_change": -250,
"shift_minutes": 390,
},
},
{
"id": "case6_hybrid_multimodal_ar_and_head",
"category": "hybrid_image_ar_plus_clairic_head",
"request": {
"state": (
"Expense audit note: The employee has a $75.00 daily meal stipend. "
"Historical daily meal spend ($) this week: 42.00, 46.50, 48.00, 49.76."
),
"images": [receipt_uri],
"fields": {
"merchant": {"type": "text", "instructions": "Merchant on the attached receipt."},
"receipt_total": {"type": "number", "decimals": 2, "source_only": True, "instructions": "Total paid on receipt."},
"within_stipend": {"type": "boolean", "instructions": "Is the receipt total within the $75.00 daily meal stipend?"},
"remaining_stipend": {
"type": "compute",
"decimals": 2,
"instructions": "Compute remaining daily stipend ($75.00 minus total paid on receipt).",
},
"tomorrow_meal_spend": {
"type": "estimate",
"min": 0,
"max": 100,
"instructions": "Estimated meal spend tomorrow based on this week's trend.",
},
},
"options": {"include_quantiles": True},
},
"expected": {
"merchant": "HARBORVIEW ROASTERS",
"receipt_total": 49.76,
"within_stipend": True,
"remaining_stipend": 25.24,
},
"expected_all": {
"merchant": "HARBORVIEW ROASTERS",
"receipt_total": 49.76,
"within_stipend": True,
"remaining_stipend": 25.24,
},
},
{
"id": "case7_long_context_mixed",
"category": "long_context_ar_plus_head",
"request": {
"state": long_report_state,
"fields": {
"prepared_by": {"type": "text", "instructions": "Organization that prepared the briefing."},
"report_date": {"type": "date", "instructions": "Printed report date."},
"consolidated_arr": {"type": "number", "decimals": 2, "source_only": True, "instructions": "Total consolidated Q3 2026 ARR in dollars."},
"eu_central_revenue": {"type": "number", "decimals": 2, "source_only": True, "instructions": "Q3 2026 quarterly recurring revenue for EU-Central."},
"uk_south_tickets": {"type": "number", "integer": True, "source_only": True, "instructions": "Active enterprise support escalations for UK-South."},
"had_p0_outage": {"type": "boolean", "instructions": "Did any region experience a Priority-0 outage in Q3 2026?"},
"chief_auditor": {"type": "text", "instructions": "Named external chief auditor if stated."},
"us_combined_qrr": {
"type": "compute",
"decimals": 2,
"instructions": "Compute combined quarterly recurring revenue of US-West plus US-East in dollars.",
},
"q4_arr_millions_estimate": {
"type": "estimate",
"min": 20,
"max": 45,
"instructions": "Estimated Q4 2026 ARR ($M) continuing the 6-quarter historical trend.",
},
},
"options": {"include_quantiles": True},
},
"expected": {
"prepared_by": "Meridian Cloud Infrastructure Finance",
"report_date": "2026-10-05",
"consolidated_arr": 30816000.0,
"eu_central_revenue": 1760250.0,
"uk_south_tickets": 163,
"had_p0_outage": False,
"chief_auditor": None,
"us_combined_qrr": 3605500.0,
},
"expected_all": {
"prepared_by": "Meridian Cloud Infrastructure Finance",
"report_date": "2026-10-05",
"consolidated_arr": 30816000.0,
"eu_central_revenue": 1760250.0,
"uk_south_tickets": 163,
"had_p0_outage": False,
"chief_auditor": None,
"us_combined_qrr": 3605500.0,
},
},
{
"id": "case8_compact_triage",
"category": "fast_compact_ar",
"request": {
"state": "Alert #ALT-509: BGP session down on router edge-fra-04 (ASN 13335) at 14:19:08 UTC. Severity: CRITICAL.",
"fields": {
"alert_id": {"type": "text", "instructions": "Alert ID."},
"router": {"type": "text", "instructions": "Router hostname."},
"asn": {"type": "number", "integer": True, "source_only": True, "instructions": "ASN number."},
"severity": {"type": "enum", "enum": ["LOW", "HIGH", "CRITICAL"], "instructions": "Severity level."},
},
},
"expected": {
"alert_id": "ALT-509",
"router": "edge-fra-04",
"asn": 13335,
"severity": "CRITICAL",
},
"expected_all": {
"alert_id": "ALT-509",
"router": "edge-fra-04",
"asn": 13335,
"severity": "CRITICAL",
},
},
]
def _values_equal_expected(exp_v: Any, got_v: Any) -> bool:
if isinstance(exp_v, float) and isinstance(got_v, (int, float)) and not isinstance(got_v, bool):
return abs(float(got_v) - exp_v) <= 1e-2
if isinstance(exp_v, int) and not isinstance(exp_v, bool) and isinstance(got_v, (int, float)) and not isinstance(got_v, bool):
return abs(float(got_v) - float(exp_v)) <= 1e-2
if isinstance(exp_v, list) and isinstance(got_v, list):
if len(exp_v) != len(got_v):
return False
return all(_values_equal_expected(a, b) for a, b in zip(exp_v, got_v))
if isinstance(exp_v, dict) and isinstance(got_v, dict):
if set(exp_v.keys()) != set(got_v.keys()):
return False
return all(_values_equal_expected(exp_v[k], got_v[k]) for k in exp_v)
return got_v == exp_v
def evaluate_ground_truth(
suite: list[dict[str, Any]],
responses: dict[str, dict[str, Any]],
*,
key: str = "expected_all",
) -> dict[str, Any]:
"""Evaluate responses directly against ground-truth `expected` or `expected_all` annotations."""
total = 0
passed = 0
mismatches: list[dict[str, Any]] = []
for case in suite:
cid = case["id"]
exp_map = case.get(key) or case.get("expected", {})
resp = responses.get(cid, {})
answers = resp.get("answers", {})
for fname, exp_v in exp_map.items():
total += 1
f_obj = answers.get(fname, {})
got_v = f_obj.get("value")
if _values_equal_expected(exp_v, got_v):
passed += 1
else:
mismatches.append(
{
"case": cid,
"field": fname,
"expected": exp_v,
"got": got_v,
"failure_reason": f_obj.get("failure_reason"),
}
)
return {
"key": key,
"passed": passed,
"total": total,
"accuracy": round(passed / max(1, total), 6),
"mismatches": mismatches,
}
def _extract_field_quantile_rels(g_field: dict[str, Any], c_field: dict[str, Any]) -> tuple[list[float], list[float]]:
"""Return `(p10_p50_p90_rels, full_99_quantile_rels)` for an `estimate` or `forecast` field."""
band_rels: list[float] = []
grid_rels: list[float] = []
for k in ("p10", "median", "p90"):
gv, cv = g_field.get(k), c_field.get(k)
if isinstance(gv, (int, float)) and isinstance(cv, (int, float)):
band_rels.append(abs(float(cv) - float(gv)) / max(abs(float(gv)), 1.0))
elif isinstance(gv, list) and isinstance(cv, list) and len(gv) == len(cv):
for a, b in zip(gv, cv):
if isinstance(a, (int, float)) and isinstance(b, (int, float)):
band_rels.append(abs(float(b) - float(a)) / max(abs(float(a)), 1.0))
gq, cq = g_field.get("quantiles"), c_field.get("quantiles")
if isinstance(gq, list) and isinstance(cq, list) and len(gq) == len(cq):
for a, b in zip(gq, cq):
if isinstance(a, (int, float)) and isinstance(b, (int, float)):
grid_rels.append(abs(float(b) - float(a)) / max(abs(float(a)), 1.0))
g_steps, c_steps = g_field.get("steps"), c_field.get("steps")
if isinstance(g_steps, list) and isinstance(c_steps, list) and len(g_steps) == len(c_steps):
for gs, cs in zip(g_steps, c_steps):
if isinstance(gs, dict) and isinstance(cs, dict):
sq_g, sq_c = gs.get("quantiles"), cs.get("quantiles")
if isinstance(sq_g, list) and isinstance(sq_c, list) and len(sq_g) == len(sq_c):
for a, b in zip(sq_g, sq_c):
if isinstance(a, (int, float)) and isinstance(b, (int, float)):
grid_rels.append(abs(float(b) - float(a)) / max(abs(float(a)), 1.0))
return band_rels, grid_rels
def compare_against_golden(
golden: dict[str, dict[str, Any]],
candidate: dict[str, dict[str, Any]],
) -> dict[str, Any]:
"""Compare candidate responses against golden reference responses with explicit per-rule metrics."""
total_fields = 0
matching_fields = 0
discrete_total = 0
discrete_exact_matches = 0
float_total = 0
float_tol_matches = 0
float_exact_1e6_matches = 0
est_total = 0
est_8pct_matches = 0
est_5pct_matches = 0
est_2pct_matches = 0
null_decision_matches = 0
confidence_diffs: list[float] = []
max_conf_detail: dict[str, Any] | None = None
item_confidence_diffs: list[float] = []
p_null_diffs: list[float] = []
max_pnull_detail: dict[str, Any] | None = None
estimate_rel_diffs: list[float] = []
max_est_detail: dict[str, Any] | None = None
quantile_fields_compared = 0
quantile_rel_diffs: list[float] = []
max_quantile_detail: dict[str, Any] | None = None
thresholds = (0.50, 0.70, 0.80, 0.90)
threshold_flips: dict[str, int] = {f"{t:.2f}": 0 for t in thresholds}
threshold_flip_details: dict[str, list[dict[str, Any]]] = {f"{t:.2f}": [] for t in thresholds}
confidence_fields_compared = 0
mismatches: list[dict[str, Any]] = []
pass_deltas: list[dict[str, Any]] = []
golden_total_passes = 0
candidate_total_passes = 0
golden_total_out_tokens = 0
candidate_total_out_tokens = 0
for case_id, g_resp in golden.items():
c_resp = candidate.get(case_id)
if c_resp is None:
mismatches.append({"case": case_id, "error": "missing_case"})
continue
g_usage = g_resp.get("usage", {})
c_usage = c_resp.get("usage", {})
g_passes = int(g_usage.get("passes", 0))
c_passes = int(c_usage.get("passes", 0))
g_out_tok = int(g_usage.get("output_tokens", 0))
c_out_tok = int(c_usage.get("output_tokens", 0))
golden_total_passes += g_passes
candidate_total_passes += c_passes
golden_total_out_tokens += g_out_tok
candidate_total_out_tokens += c_out_tok
if g_passes != c_passes or g_out_tok != c_out_tok:
pass_deltas.append(
{
"case": case_id,
"golden_passes": g_passes,
"candidate_passes": c_passes,
"golden_output_tokens": g_out_tok,
"candidate_output_tokens": c_out_tok,
}
)
g_ans = g_resp["answers"]
c_ans = c_resp["answers"]
for fname, g_field in g_ans.items():
total_fields += 1
c_field = c_ans.get(fname, {})
gv, cv = g_field.get("value"), c_field.get("value")
ftype = g_field.get("type")
if (gv is None) == (cv is None):
null_decision_matches += 1
if ftype in ("estimate", "forecast"):
est_total += 1
field_max_rel: float | None = None
if ftype == "estimate" and isinstance(gv, (int, float)) and isinstance(cv, (int, float)):
denom = max(abs(float(gv)), 1.0)
rel = abs(float(cv) - float(gv)) / denom
estimate_rel_diffs.append(rel)
field_max_rel = rel
elif (
ftype == "forecast"
and isinstance(gv, list)
and isinstance(cv, list)
and len(gv) == len(cv)
):
rels = [abs(float(a) - float(b)) / max(abs(float(a)), 1.0) for a, b in zip(gv, cv)]
estimate_rel_diffs.extend(rels)
field_max_rel = max(rels) if rels else 0.0
if field_max_rel is not None:
if max_est_detail is None or field_max_rel > max_est_detail["rel_diff"]:
max_est_detail = {
"case": case_id,
"field": fname,
"golden": gv,
"candidate": cv,
"rel_diff": round(field_max_rel, 6),
}
if field_max_rel <= 0.02:
est_2pct_matches += 1
if field_max_rel <= 0.05:
est_5pct_matches += 1
if field_max_rel <= 0.08:
est_8pct_matches += 1
matching_fields += 1
else:
mismatches.append(
{
"case": case_id,
"field": fname,
"type": ftype,
"golden": gv,
"candidate": cv,
"rel_diff": round(field_max_rel, 6),
}
)
else:
mismatches.append({"case": case_id, "field": fname, "type": ftype, "golden": gv, "candidate": cv})
band_rels, grid_rels = _extract_field_quantile_rels(g_field, c_field)
all_q_rels = band_rels if band_rels else grid_rels
if band_rels or grid_rels:
quantile_fields_compared += 1
quantile_rel_diffs.extend(band_rels)
q_max = max(all_q_rels)
if max_quantile_detail is None or q_max > max_quantile_detail["max_rel_diff"]:
max_quantile_detail = {
"case": case_id,
"field": fname,
"max_p10_p50_p90_rel_diff": round(max(band_rels), 6) if band_rels else 0.0,
"max_99grid_rel_diff": round(max(grid_rels), 6) if grid_rels else 0.0,
"max_rel_diff": round(q_max, 6),
"golden_p10_p50_p90": [g_field.get("p10"), g_field.get("median"), g_field.get("p90")],
"candidate_p10_p50_p90": [c_field.get("p10"), c_field.get("median"), c_field.get("p90")],
}
elif isinstance(gv, float) and not isinstance(gv, bool):
float_total += 1
if isinstance(cv, (int, float)) and not isinstance(cv, bool):
if math.isclose(float(gv), float(cv), rel_tol=1e-6, abs_tol=1e-6):
float_exact_1e6_matches += 1
if math.isclose(float(gv), float(cv), rel_tol=1e-4, abs_tol=1e-2):
float_tol_matches += 1
matching_fields += 1
else:
mismatches.append({"case": case_id, "field": fname, "type": ftype, "golden": gv, "candidate": cv})
else:
mismatches.append({"case": case_id, "field": fname, "type": ftype, "golden": gv, "candidate": cv})
else:
discrete_total += 1
if gv == cv:
discrete_exact_matches += 1
matching_fields += 1
else:
mismatches.append({"case": case_id, "field": fname, "type": ftype, "golden": gv, "candidate": cv})
g_conf = g_field.get("confidence")
c_conf = c_field.get("confidence")
if isinstance(g_conf, (int, float)) and isinstance(c_conf, (int, float)):
confidence_fields_compared += 1
cdiff = abs(float(g_conf) - float(c_conf))
confidence_diffs.append(cdiff)
if max_conf_detail is None or cdiff > max_conf_detail["abs_diff"]:
max_conf_detail = {
"case": case_id,
"field": fname,
"golden_confidence": round(float(g_conf), 6),
"candidate_confidence": round(float(c_conf), 6),
"abs_diff": round(cdiff, 6),
}
for t in thresholds:
tk = f"{t:.2f}"
if (float(g_conf) >= t) != (float(c_conf) >= t):
threshold_flips[tk] += 1
threshold_flip_details[tk].append(
{
"case": case_id,
"field": fname,
"golden_confidence": round(float(g_conf), 4),
"candidate_confidence": round(float(c_conf), 4),
}
)
g_ic = g_field.get("confidences")
c_ic = c_field.get("confidences")
if isinstance(g_ic, list) and isinstance(c_ic, list) and len(g_ic) == len(c_ic):
for a, b in zip(g_ic, c_ic):
if isinstance(a, (int, float)) and isinstance(b, (int, float)):
item_confidence_diffs.append(abs(float(a) - float(b)))
g_pn = g_field.get("p_null")
c_pn = c_field.get("p_null")
if isinstance(g_pn, (int, float)) and isinstance(c_pn, (int, float)):
pndiff = abs(float(g_pn) - float(c_pn))
p_null_diffs.append(pndiff)
if max_pnull_detail is None or pndiff > max_pnull_detail["abs_diff"]:
max_pnull_detail = {
"case": case_id,
"field": fname,
"golden_p_null": round(float(g_pn), 6),
"candidate_p_null": round(float(c_pn), 6),
"abs_diff": round(pndiff, 6),
}
return {
"total_fields": total_fields,
"matching_fields": matching_fields,
"field_agreement_rate": round(matching_fields / max(1, total_fields), 6),
"discrete_exact_matches": discrete_exact_matches,
"discrete_total": discrete_total,
"float_tol_matches": float_tol_matches,
"float_exact_1e6_matches": float_exact_1e6_matches,
"float_total": float_total,
"estimate_forecast_8pct_matches": est_8pct_matches,
"estimate_forecast_5pct_matches": est_5pct_matches,
"estimate_forecast_2pct_matches": est_2pct_matches,
"estimate_forecast_total": est_total,
"null_decision_matches": null_decision_matches,
"mean_abs_confidence_diff": round(sum(confidence_diffs) / len(confidence_diffs), 6) if confidence_diffs else 0.0,
"max_abs_confidence_diff": round(max(confidence_diffs), 6) if confidence_diffs else 0.0,
"max_confidence_diff_detail": max_conf_detail,
"max_abs_item_confidence_diff": round(max(item_confidence_diffs), 6) if item_confidence_diffs else 0.0,
"confidence_fields_compared": confidence_fields_compared,
"confidence_threshold_flips": threshold_flips,
"confidence_threshold_flip_details": threshold_flip_details,
"mean_abs_p_null_diff": round(sum(p_null_diffs) / len(p_null_diffs), 6) if p_null_diffs else 0.0,
"max_abs_p_null_diff": round(max(p_null_diffs), 6) if p_null_diffs else 0.0,
"max_p_null_diff_detail": max_pnull_detail,
"mean_estimate_rel_diff": round(sum(estimate_rel_diffs) / len(estimate_rel_diffs), 6) if estimate_rel_diffs else 0.0,
"max_estimate_rel_diff": round(max(estimate_rel_diffs), 6) if estimate_rel_diffs else 0.0,
"max_estimate_diff_detail": max_est_detail,
"quantile_fields_compared": quantile_fields_compared,
"mean_quantile_rel_diff": round(sum(quantile_rel_diffs) / len(quantile_rel_diffs), 6) if quantile_rel_diffs else 0.0,
"max_quantile_rel_diff": round(max(quantile_rel_diffs), 6) if quantile_rel_diffs else 0.0,
"max_quantile_diff_detail": max_quantile_detail,
"golden_total_passes": golden_total_passes,
"candidate_total_passes": candidate_total_passes,
"golden_total_output_tokens": golden_total_out_tokens,
"candidate_total_output_tokens": candidate_total_out_tokens,
"pass_and_token_deltas": pass_deltas,
"mismatches": mismatches,
}
if __name__ == "__main__":
suite = build_suite()
print(
f"Built {len(suite)} selection-suite cases with "
f"{sum(len(c['request']['fields']) for c in suite)} public fields "
f"({sum(len(c['expected']) for c in suite)} v1 expected, "
f"{sum(len(c['expected_all']) for c in suite)} deterministic expected)."
)

Xet Storage Details

Size:
44.4 kB
·
Xet hash:
2b86f97b0135b9e4a725ed8832ba3e7ab0c5b6c6150e7f264c48dcaaa8bb2244

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.