Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
184 changes: 147 additions & 37 deletions crates/common/src/limits/weight.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,18 @@
// ============================================================================
// Weighted-token converter
//
// Maps `(model_id, raw_input_tokens, raw_output_tokens)` to a single
// integer "weighted token" cost using each model's per-direction
// weight from the `models` table.
// Maps a request's token counts to a single integer "weighted token"
// cost using each model's weights from the `models` table.
//
// weighted = round(input × input_weight + output × output_weight)
// weighted = round(input × input_weight
// + cache_read × cache_read_weight
// + cache_write × cache_write_weight (or _1h_)
// + output × output_weight)
//
// Input read from or written to the upstream's prompt cache is priced
// apart from plain input: a cache read costs a fraction of it, a write a
// premium. Unset cache weights follow the input weight — see
// `Weights::resolve` for the ratios.
//
// Used by the gateway hot path to feed `sliding::check_and_record`
// (tokens metric) and `budget::add_weighted_tokens`. The weights
Expand All @@ -30,27 +37,76 @@ use std::collections::HashMap;
use std::sync::Arc;
use std::time::{Duration, Instant};

use rust_decimal::Decimal;
use rust_decimal::prelude::ToPrimitive;
use sqlx::PgPool;
use tokio::sync::RwLock;

const CACHE_TTL: Duration = Duration::from_secs(300);
const MAX_ENTRIES: usize = 1024;

#[derive(Debug, Clone, Copy)]
/// Cache read, as a share of the input weight, when the model sets none.
/// Anthropic bills a cache read at 0.1× input, as do OpenAI's newest
/// models; older OpenAI models discount less (0.5×, 0.25×), and a model
/// served there should set its own.
pub const CACHE_READ_RATIO: f64 = 0.1;
/// Cache write (5-minute), as a share of the input weight, when unset.
/// Anthropic's 1.25×. OpenAI does not bill writes, and reports none.
pub const CACHE_WRITE_RATIO: f64 = 1.25;
/// Cache write with a 1-hour lifetime, as a share of the input weight,
/// when unset. Anthropic's 2×.
pub const CACHE_WRITE_1H_RATIO: f64 = 2.0;

/// A model's weights, each against the platform baseline price for its
/// direction: the three cache weights, like the input weight, against
/// the input price.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Weights {
pub input: f64,
pub output: f64,
pub cache_read: f64,
pub cache_write: f64,
pub cache_write_1h: f64,
}

impl Default for Weights {
fn default() -> Self {
impl Weights {
/// The weights in force, from a `models` row: an unset cache weight
/// is the input weight times its ratio above.
pub fn resolve(
input: f64,
output: f64,
cache_read: Option<f64>,
cache_write: Option<f64>,
cache_write_1h: Option<f64>,
) -> Self {
Self {
input: 1.0,
output: 1.0,
input,
output,
cache_read: cache_read.unwrap_or(input * CACHE_READ_RATIO),
cache_write: cache_write.unwrap_or(input * CACHE_WRITE_RATIO),
cache_write_1h: cache_write_1h.unwrap_or(input * CACHE_WRITE_1H_RATIO),
}
}
}

impl Default for Weights {
fn default() -> Self {
Self::resolve(1.0, 1.0, None, None, None)
}
}

/// One request's tokens, split the way they are priced. `input` is the
/// input that was neither read from nor written to the prompt cache.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct TokenCounts {
pub input: i64,
pub cache_read: i64,
pub cache_write: i64,
/// The cache writes had a 1-hour lifetime.
pub cache_write_1h: bool,
pub output: i64,
}

#[derive(Clone)]
struct CacheEntry {
weights: Weights,
Expand Down Expand Up @@ -91,19 +147,25 @@ impl WeightCache {
}

// Slow path: query PG, then upsert into the cache.
let weights = match sqlx::query_as::<_, (rust_decimal::Decimal, rust_decimal::Decimal)>(
"SELECT input_weight, output_weight FROM models WHERE model_id = $1",
type Row = (
Decimal,
Decimal,
Option<Decimal>,
Option<Decimal>,
Option<Decimal>,
);
let weights = match sqlx::query_as::<_, Row>(
"SELECT input_weight, output_weight, \
cache_read_weight, cache_write_weight, cache_write_1h_weight \
FROM models WHERE model_id = $1",
)
.bind(model_id)
.fetch_optional(pool)
.await
{
Ok(Some((i, o))) => {
use rust_decimal::prelude::ToPrimitive;
Weights {
input: i.to_f64().unwrap_or(1.0),
output: o.to_f64().unwrap_or(1.0),
}
Ok(Some((i, o, cr, cw, cw1h))) => {
let f = |d: Decimal| d.to_f64().unwrap_or(1.0);
Weights::resolve(f(i), f(o), cr.map(f), cw.map(f), cw1h.map(f))
}
Ok(None) => Weights::default(),
Err(e) => {
Expand Down Expand Up @@ -150,47 +212,95 @@ impl WeightCache {
/// through. The hot path looks like:
///
/// let mult = state.weight_cache.get(&state.db, &request.model).await;
/// let weighted = weighted_tokens(input, output, mult);
pub fn weighted_tokens(input_tokens: i64, output_tokens: i64, mult: Weights) -> i64 {
// Cast to f64 for the multiplication then round back. i64 is
// plenty for any token count (max ~9.2e18).
let w = (input_tokens.max(0) as f64) * mult.input + (output_tokens.max(0) as f64) * mult.output;
w.round().max(0.0) as i64
/// let weighted = weighted_tokens(&counts, mult);
pub fn weighted_tokens(t: &TokenCounts, w: Weights) -> i64 {
let n = |x: i64| x.max(0) as f64;
let write = if t.cache_write_1h {
w.cache_write_1h
} else {
w.cache_write
};
// f64 then round back. i64 is plenty for any token count (max ~9.2e18).
let sum = n(t.input) * w.input
+ n(t.cache_read) * w.cache_read
+ n(t.cache_write) * write
+ n(t.output) * w.output;
sum.round().max(0.0) as i64
}

#[cfg(test)]
mod tests {
use super::*;

fn plain(input: i64, output: i64) -> TokenCounts {
TokenCounts {
input,
output,
..Default::default()
}
}

fn weights(input: f64, output: f64) -> Weights {
Weights::resolve(input, output, None, None, None)
}

#[test]
fn weighted_tokens_default_is_raw_sum() {
let m = Weights::default();
assert_eq!(weighted_tokens(100, 50, m), 150);
assert_eq!(weighted_tokens(&plain(100, 50), Weights::default()), 150);
}

#[test]
fn weighted_tokens_scales_each_direction() {
let m = Weights {
input: 1.0,
output: 3.0,
};
// 100 input + 50 output × 3 = 100 + 150 = 250
assert_eq!(weighted_tokens(100, 50, m), 250);
assert_eq!(weighted_tokens(&plain(100, 50), weights(1.0, 3.0)), 250);
}

#[test]
fn weighted_tokens_clamps_negatives() {
let m = Weights::default();
assert_eq!(weighted_tokens(-1, -1, m), 0);
assert_eq!(weighted_tokens(&plain(-1, -1), Weights::default()), 0);
}

#[test]
fn weighted_tokens_rounds() {
let m = Weights {
input: 1.5,
output: 0.5,
};
// 3 × 1.5 = 4.5 ; 1 × 0.5 = 0.5 ; sum = 5.0
assert_eq!(weighted_tokens(3, 1, m), 5);
assert_eq!(weighted_tokens(&plain(3, 1), weights(1.5, 0.5)), 5);
}

#[test]
fn cache_weights_follow_the_input_weight_when_unset() {
let w = weights(2.0, 1.0);
assert_eq!(w.cache_read, 0.2);
assert_eq!(w.cache_write, 2.5);
assert_eq!(w.cache_write_1h, 4.0);
}

#[test]
fn cache_reads_and_writes_are_weighted_apart_from_plain_input() {
let t = TokenCounts {
input: 100,
cache_read: 1000,
cache_write: 400,
cache_write_1h: false,
output: 10,
};
// 100 + 1000 × 0.1 + 400 × 1.25 + 10 = 100 + 100 + 500 + 10
assert_eq!(weighted_tokens(&t, Weights::default()), 710);
let t = TokenCounts {
cache_write_1h: true,
..t
};
// 100 + 100 + 400 × 2 + 10
assert_eq!(weighted_tokens(&t, Weights::default()), 1010);
}

#[test]
fn a_set_cache_weight_is_used_as_is() {
let w = Weights::resolve(1.0, 1.0, Some(0.5), Some(1.0), None);
let t = TokenCounts {
cache_read: 100,
cache_write: 100,
..Default::default()
};
assert_eq!(weighted_tokens(&t, w), 150);
}
}
9 changes: 9 additions & 0 deletions crates/common/src/models/provider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,15 @@ pub struct Model {
pub input_weight: Decimal,
/// Relative output-token cost factor.
pub output_weight: Decimal,
/// Cache-read input, against the input baseline. `None` ⇒
/// `input_weight × 0.1` (see `limits::weight::Weights::resolve`).
pub cache_read_weight: Option<Decimal>,
/// Cache-write input (5-minute), against the input baseline.
/// `None` ⇒ `input_weight × 1.25`.
pub cache_write_weight: Option<Decimal>,
/// Cache-write input with a 1-hour lifetime. `None` ⇒
/// `input_weight × 2`.
pub cache_write_1h_weight: Option<Decimal>,
/// Per-model routing strategy override.
/// `None` ⇒ inherit `gateway.default_routing_strategy`.
/// One of `weighted` / `latency` / `health` / `latency_health`.
Expand Down
Loading
Loading