open-standards/eoc/eoc-rs/crates/eoc-vendor-api/src/joule_estimator.rs
Transaction Science 01d4ad9c7b Ingest batch 2: 9 new crates across openpay / smart-byte / eoc
openpay/ (+3 crates, ~8400 LOC, 162 tests)
  op-iso8583/         ISO 8583 messages for direct acquirer / card-network
                      connectivity. MTIs, primary+secondary bitmaps, full
                      DE catalogue, BCD/ASCII/EBCDIC/LLVAR/LLLVAR codecs,
                      five dialects (Visa Base I, Mastercard MDS, Amex GNS,
                      Discover, JCB), network-management messages
                      (sign-on/echo/cutover), DE 55 EMV TLV.
  op-mobile-wallets/  Apple Pay (ECDH-P256 + AES-256-GCM), Google Pay ECv2
                      (ECDH + HKDF + AES-256-CTR + HMAC), Samsung Pay. PAN
                      never leaves the decryption boundary as a String;
                      lands in VaultRef. No-PAN-leakage assertions per
                      wallet.
  op-routing/         Least-cost routing + MCC-aware routing + intelligent
                      retry / soft-decline recovery. 231-MCC catalogue.
                      Real ISO 8583 DE-39 soft/hard decline taxonomies.

smart-byte/smart-byte-rs/ (+3 crates, ~7100 LOC, 96 tests)
  smart-byte-vc/      W3C Verifiable Credentials 2.0: VCDM, presentations,
                      Data Integrity proofs (eddsa-jcs-2022), VC-JWT,
                      SD-JWT (selective disclosure), Bitstring Status
                      List 2021. Cargo-bridge maps VCs to Smart Byte
                      envelopes with SAID stability.
  smart-byte-did/     W3C DID resolution: did:key (Ed25519/P-256/secp256k1),
                      did:web (HTTPS), did:peer (numalgo 2+4), did:jwk,
                      did:ion (feature-gated stub). DID URL dereferencer.
  smart-byte-pq/      Post-quantum signatures: ML-DSA-44/65/87 (FIPS 204),
                      SLH-DSA across 12 parameter sets (FIPS 205), FN-DSA
                      (draft FIPS 206, feature-gated). Hybrid Ed25519 +
                      ML-DSA pattern for the transition. Secret-key
                      zeroize-on-drop.

eoc/eoc-rs/ (+3 crates, ~6450 LOC, 76 tests)
  eoc-vendor-api/     NeuralBackend implementations: Anthropic, OpenAI,
                      Google, Mistral, Cohere, Groq, Together, Fireworks.
                      SSE streaming. Prompt-caching where supported.
                      Joule estimates per published energy coefficient
                      (12-model curated table).
  eoc-embeddings/     21 embedding models behind one Embedder trait:
                      OpenAI v3 (3), Cohere v3 (3), Voyage (5), Mistral,
                      Jina, plus local ONNX (BGE x3, nomic, mxbai, GTE,
                      E5) behind 'local' feature. Matryoshka-style
                      dimension projection. Per-content-hash cache.
  eoc-route-learned/  RouteLLM-style matrix-factorisation router +
                      multinomial-logreg classifier + LinUCB / Thompson
                      bandits for online learning. LearnedCascade wraps
                      the rule-based cascade with a confidence-threshold
                      skip policy. Synthetic-eval accuracy: MF 0.935,
                      LogReg 0.980.

Quality:
- cargo check across all three workspaces: clean
- cargo clippy --all-targets -- -D warnings on every new crate: clean
- 334 new tests total; 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-23 18:12:24 -04:00

159 lines
5.6 KiB
Rust

//! Joule estimation from token counts.
//!
//! Commercial vendors do not expose per-call hardware energy counters,
//! so this estimator multiplies reported input/output token counts by
//! per-model energy coefficients curated in
//! [`data/model_energy_profiles.json`](../../data/model_energy_profiles.json).
//!
//! The resulting [`JouleCost`] is always tagged
//! [`JouleSource::Estimated`](eoc_core::JouleSource::Estimated).
use std::collections::BTreeMap;
use eoc_core::{JouleCost, JouleSource};
use serde::Deserialize;
/// Per-model energy profile.
#[derive(Debug, Clone, Deserialize)]
pub struct ModelEnergyProfile {
/// Joules consumed per input (prompt) token.
pub joules_per_input_token: f64,
/// Joules consumed per output (completion) token.
pub joules_per_output_token: f64,
/// Source citation for the coefficients (HF Energy Score, vendor
/// disclosure, or estimator-derivation note).
pub source: String,
}
/// Trait for plugging in a custom joule estimator.
pub trait JouleEstimator: Send + Sync {
/// Estimate the joule cost of an inference given input/output token
/// counts and the model name (vendor-qualified, e.g. `claude-3-5-sonnet`).
fn estimate(&self, input_tokens: u32, output_tokens: u32, model: &str) -> JouleCost;
}
#[derive(Debug, Deserialize)]
struct ProfileFile {
profiles: BTreeMap<String, ModelEnergyProfile>,
}
/// Default estimator backed by the embedded coefficient table.
#[derive(Debug, Clone)]
pub struct DefaultEstimator {
/// model-name → profile.
pub table: BTreeMap<String, ModelEnergyProfile>,
/// Fallback joules per input token when a model is unknown.
pub fallback_input: f64,
/// Fallback joules per output token when a model is unknown.
pub fallback_output: f64,
}
const EMBEDDED_PROFILES: &str = include_str!("../data/model_energy_profiles.json");
impl DefaultEstimator {
/// Construct an estimator from the embedded profile table. Falls
/// back to mid-range coefficients (0.10 J input, 0.50 J output —
/// roughly claude-3.5-sonnet) when a model is unknown.
pub fn builtin() -> Self {
// Parsing the embedded JSON cannot reasonably fail; if it does
// the crate's own data file is malformed, which is a build-time
// bug, not a runtime concern. We fall back to an empty table.
let table = serde_json::from_str::<ProfileFile>(EMBEDDED_PROFILES)
.map(|p| p.profiles)
.unwrap_or_default();
Self {
table,
fallback_input: 0.10,
fallback_output: 0.50,
}
}
/// Construct an estimator from a custom JSON payload (same schema as
/// the embedded file).
pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
let parsed: ProfileFile = serde_json::from_str(json)?;
Ok(Self {
table: parsed.profiles,
fallback_input: 0.10,
fallback_output: 0.50,
})
}
/// Override the fallback coefficients (consumes `self`). Useful for
/// e.g. the Groq backend, whose LPU has dramatically lower per-token
/// energy than a generic GPU.
pub fn with_fallback(mut self, input: f64, output: f64) -> Self {
self.fallback_input = input;
self.fallback_output = output;
self
}
/// Insert or overwrite a model profile (consumes `self`).
pub fn with_profile(mut self, model: impl Into<String>, profile: ModelEnergyProfile) -> Self {
self.table.insert(model.into(), profile);
self
}
}
impl JouleEstimator for DefaultEstimator {
fn estimate(&self, input_tokens: u32, output_tokens: u32, model: &str) -> JouleCost {
let (jin, jout) = match self.table.get(model) {
Some(p) => (p.joules_per_input_token, p.joules_per_output_token),
None => (self.fallback_input, self.fallback_output),
};
let joules = (input_tokens as f64) * jin + (output_tokens as f64) * jout;
// Clamp negatives (shouldn't happen) and convert to micro-joules.
let microjoules = (joules * 1_000_000.0).max(0.0) as u64;
JouleCost {
microjoules,
source: JouleSource::Estimated,
}
}
}
impl Default for DefaultEstimator {
fn default() -> Self {
Self::builtin()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn builtin_loads_known_models() {
let est = DefaultEstimator::builtin();
assert!(est.table.contains_key("claude-3-5-sonnet"));
assert!(est.table.contains_key("gpt-4o"));
assert!(est.table.contains_key("gemini-1.5-pro"));
assert!(est.table.contains_key("llama-3.1-70b"));
assert!(est.table.contains_key("mixtral-8x7b"));
}
#[test]
fn estimate_matches_table_arithmetic() {
let est = DefaultEstimator::builtin();
// claude-3-5-sonnet: 0.10 J/in, 0.50 J/out.
// 1000 in + 500 out = 100 + 250 = 350 J = 350_000_000 µJ.
let cost = est.estimate(1000, 500, "claude-3-5-sonnet");
assert_eq!(cost.microjoules, 350_000_000);
assert_eq!(cost.source, JouleSource::Estimated);
}
#[test]
fn unknown_model_uses_fallback() {
let est = DefaultEstimator::builtin();
let cost = est.estimate(100, 100, "no-such-model");
// 100*0.10 + 100*0.50 = 60 J.
assert_eq!(cost.microjoules, 60_000_000);
}
#[test]
fn custom_fallback_takes_effect() {
let est = DefaultEstimator::builtin().with_fallback(0.001, 0.005);
let cost = est.estimate(1000, 1000, "no-such-model");
// 1000*0.001 + 1000*0.005 = 6 J.
assert_eq!(cost.microjoules, 6_000_000);
}
}