open-standards/eoc/eoc-rs/crates/eoc-eval/src/math.rs
Transaction Science 6575ff1eb7 Ingest batch 3: 9 more crates across openpay / smart-byte / eoc
openpay/ (+3 crates)
  op-bnpl/        Affirm + Klarna + Afterpay/Clearpay rails. Full lifecycle
                  typestate (Initiated→Approved→Captured→Settled→Refunded).
                  Per-provider sandbox+production base URLs, regions (NA/EU/OC
                  for Klarna; US/AuNz/Gb/Ca/Eu for Afterpay). HMAC-SHA256
                  webhook verification with constant-time compare. 61 tests.
  op-batch/       NACHA ACH (94-char records, PPD/CCD/WEB/TEL/CTX, R01-R99
                  return codes, Same-Day ACH cutoffs); SEPA pain.001.001.09
                  (CT) + pain.008.001.08 (DD) with SCT-Inst flagging; Fedwire
                  MT103/MT202/CHIPS + pacs.008.001.12 / pacs.009.001.10 +
                  UETR; Bacs Standard 18. Per-rail cutoff scheduler. Exception
                  taxonomy unified across rails. 51 tests.
  op-screening/   OFAC SDN + EU consolidated + UN consolidated + HMT UK
                  consolidated + Australia DFAT + Canada SEMA + Japan MOF.
                  Levenshtein + Jaro-Winkler + Soundex + Metaphone + token
                  Jaccard scoring. Unicode NFKD normalisation + Cyrillic /
                  Arabic transliteration. Ed25519-signed BLAKE3-chained
                  audit log. BSA helpers: CTR + SAR pattern detection
                  (structuring, round-dollar, rapid-in-out). 43 tests.

smart-byte/smart-byte-rs/ (+3 crates)
  smart-byte-bbs/      BBS+ signatures (IETF draft-irtf-cfrg-bbs-signatures-08).
                       BLS12-381 keys, signatures, disclosure proofs with
                       cryptographic unlinkability. bbs-2023 Data Integrity
                       cryptosuite. AnonCreds-shaped link secrets +
                       predicate proofs. SecretKey zeroize-on-drop. 49 tests.
  smart-byte-didcomm/  DIDComm v2 messaging per DIF spec. Pack-encrypted
                       (ECDH-1PU + ECDH-ES via X25519), pack-signed (JWS),
                       pack-plaintext. Aries protocols: issue-credential v3,
                       present-proof v3, basic-message, trust-ping, discover-
                       features, out-of-band, coordinate-mediation, message-
                       pickup. Mediator role with pluggable storage. 23 tests.
  smart-byte-mdl/      ISO/IEC 18013-5 mobile driver's licence + 18013-7
                       online presentment. mDoc + MSO with salted-hash
                       selective disclosure (per item; SHA-256 digest tree).
                       org.iso.18013.5.1 namespace + AAMVA add-on. ES256
                       device-auth + issuer-auth. QR-code device-engagement
                       scaffolding. 28 tests.

eoc/eoc-rs/ (+3 crates)
  eoc-local/      Local-inference backends behind one NeuralBackend:
                  llama.cpp (GGUF, Q4/Q5/Q6/Q8/F16/F32 quantisation),
                  MLX (Apple Silicon, feature-gated), MLC-LLM (TVM, feature-
                  gated marker), ONNX Runtime. GGUF file-format reader.
                  HuggingFace tokenizers. Greedy / top-k / top-p / temperature /
                  Mirostat samplers. Model registry scanning ~/.eoc/models/.
                  Joule attribution via eoc-meter. 39 tests.
  eoc-rerank/     BM25 sparse + HNSW dense + RRF + min-max hybrid fusion.
                  Cohere v3.5 + Voyage v2 + bge-reranker v2-m3 + ms-marco
                  MiniLM + ColBERT v2 rerankers. Two-stage pipeline:
                  retrieve top-K hybrid → cross-encoder rerank → top-N.
                  KV-stage recovery shim into the cascade. 31 tests.
  eoc-eval/       15 canonical eval harnesses: MMLU, MMLU-Pro, GPQA,
                  HumanEval (pass@1 with python3 sandbox), BBH, IFEval (25
                  verifiable constraints), AlpacaEval, AGIEval, HellaSwag,
                  ARC (Easy + Challenge), TruthfulQA (MC1+MC2), BoolQ,
                  GSM8K, MATH (boxed-answer equivalence), Winogrande. Real
                  questions in BuiltinSamples. EvalRunner emits joules-per-
                  correct alongside accuracy. 49 tests.

Quality:
- cargo check across all three workspaces: clean
- cargo clippy --all-targets -- -D warnings on every new crate: clean
- 374 new tests, all passing
- #![forbid(unsafe_code)] across every new crate
- No unwrap/expect outside #[cfg(test)]

Rust 1.95.0 edition 2024 (inherited via root rust-toolchain.toml).
2026-05-24 01:09:35 -04:00

182 lines
5 KiB
Rust

//! MATH — competition mathematics (Hendrycks et al. 2021).
//!
//! Metric: equivalence on the final boxed answer (`\boxed{...}`). We
//! accept either a boxed expression in the response or — as a fallback
//! — the last numeric token, after a light normalisation that strips
//! whitespace, dollar signs, and trailing punctuation.
use async_trait::async_trait;
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::sync::OnceLock;
use crate::builtin_samples;
use crate::error::Result;
use crate::harness::{
DatasetSource, EvalCase, ExpectedAnswer, Harness, Metric, Response, load_raw,
};
/// MATH harness.
pub struct Math;
impl Math {
/// Create a new MATH harness.
pub fn new() -> Self {
Self
}
}
impl Default for Math {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug, Deserialize, Serialize)]
struct RawRow {
id: String,
subject: String,
#[allow(dead_code)]
level: u32,
question: String,
answer: String,
}
/// Strip a `\boxed{...}` wrapper out of `text` and return the inner
/// expression with surrounding whitespace removed.
pub fn extract_boxed(text: &str) -> Option<String> {
// Find the last occurrence of \boxed{ and balance-match its braces.
let idx = text.rfind("\\boxed{")?;
let start = idx + "\\boxed{".len();
let mut depth = 1i32;
let bytes = text.as_bytes();
let mut i = start;
while i < bytes.len() {
match bytes[i] {
b'{' => depth += 1,
b'}' => {
depth -= 1;
if depth == 0 {
return Some(text[start..i].trim().to_string());
}
}
_ => {}
}
i += 1;
}
None
}
/// Normalise a MATH answer string for equivalence comparison.
pub fn normalise_math(answer: &str) -> String {
let mut s = answer.trim().to_string();
// Strip enclosing dollars (display math).
while s.starts_with('$') && s.ends_with('$') && s.len() > 1 {
s = s[1..s.len() - 1].trim().to_string();
}
// Drop common cosmetic differences.
s.retain(|c| !c.is_whitespace());
// Trailing period.
if s.ends_with('.') {
s.pop();
}
s
}
#[async_trait]
impl Harness for Math {
fn name(&self) -> &'static str {
"math"
}
fn metric(&self) -> Metric {
Metric::ExactMatch
}
async fn load(&self, source: DatasetSource) -> Result<Vec<EvalCase>> {
let raw = load_raw(source, builtin_samples::MATH).await?;
let rows: Vec<RawRow> = serde_json::from_str(&raw)?;
Ok(rows
.into_iter()
.map(|r| {
let prompt = format!(
"{}\n\nPut your final answer in \\boxed{{...}}.",
r.question.trim()
);
EvalCase {
id: r.id,
prompt,
expected: ExpectedAnswer::Number(r.answer),
dataset: "math".to_string(),
subject: Some(r.subject),
}
})
.collect())
}
async fn score(&self, response: &Response, expected: &ExpectedAnswer) -> f64 {
let ExpectedAnswer::Number(want) = expected else {
return 0.0;
};
let want_norm = normalise_math(want);
// Prefer a boxed expression in the response.
if let Some(boxed) = extract_boxed(&response.payload)
&& normalise_math(&boxed) == want_norm
{
return 1.0;
}
// Fallback: last bare integer / decimal.
static RE: OnceLock<Regex> = OnceLock::new();
let re = RE.get_or_init(|| Regex::new(r"-?\d+(?:\.\d+)?").unwrap());
if let Some(m) = re.find_iter(&response.payload).last()
&& normalise_math(m.as_str()) == want_norm
{
return 1.0;
}
0.0
}
}
#[cfg(test)]
mod tests {
use super::*;
use eoc_core::JouleCost;
fn resp(s: &str) -> Response {
Response {
payload: s.to_string(),
latency_ms: 1,
joule_cost: JouleCost::estimated(1),
}
}
#[tokio::test]
async fn loads_builtin() {
let cases = Math::new().load(DatasetSource::BuiltinSample).await.unwrap();
assert!(!cases.is_empty());
}
#[test]
fn boxed_extraction() {
assert_eq!(
extract_boxed("So the answer is \\boxed{42}.").as_deref(),
Some("42"),
);
assert_eq!(
extract_boxed("\\boxed{\\frac{5}{6}}").as_deref(),
Some("\\frac{5}{6}"),
);
}
#[tokio::test]
async fn scores_boxed_and_bare() {
let h = Math::new();
let exp = ExpectedAnswer::Number("12".into());
assert_eq!(h.score(&resp("\\boxed{12}"), &exp).await, 1.0);
assert_eq!(h.score(&resp("So 6*2 = 12"), &exp).await, 1.0);
assert_eq!(h.score(&resp("13"), &exp).await, 0.0);
let frac = ExpectedAnswer::Number("\\frac{5}{6}".into());
assert_eq!(h.score(&resp("\\boxed{\\frac{5}{6}}"), &frac).await, 1.0);
}
}