engine.solvers.cost_accounting
engine.solvers.cost_accounting
Agent cost-accounting solvers: what one accepted task costs, and what each lever buys (added 2026-10-20).
Domain implementations behind mlsysim.solvers. Each model is arithmetic on stated inputs: the fitted fall of a fixed capability’s price, cost against score on long-horizon trials, a cohort of one-attempt tasks under a tariff, prefix-cache bills and the payback of one compaction, retry policies under independent attempts, a serial episode under Amdahl’s law and speculative decoding, a tiered model cascade under one gate, admission against a token quota, Kingman’s queue price, renting tokens against owning capacity, a conserved budget across children, architectures with a human fallback, the payback of a one-time adaptation, per-workload levers on cost per accepted task, measured coverage against independent trials, and one server swept across concurrency. None models a particular provider’s billing system.
Classes
| Name | Description |
|---|---|
| AdaptationPaybackModel | Tasks until a one-time adaptation repays its data, training, and evaluation. |
| ArchitectureChoiceModel | Designs priced by automated spend alone and with a human fallback. |
| CohortAttemptCostModel | One configuration’s cohort: one bounded attempt per task, all charges settled. |
| CompactionPaybackModel | One compaction priced against keeping the transcript, under one tariff. |
| ConservedBudgetModel | A root budget kept as settled + reserved + free across two children. |
| DedicatedBreakEvenModel | Renting tokens from an API against owning capacity with a fixed hourly cost. |
| KingmanQueueModel | Kingman’s mean wait for one server at two utilizations, and its holding price. |
| ModelCascadeModel | A tiered cascade under one acceptance gate, priced over a completed cohort. |
| PrefixCacheBillModel | An append-only trajectory billed at the fresh rate, and with ideal prefix reuse. |
| RetryPolicyModel | Bounded attempt policies under independent attempts at a fixed all-in cost. |
| SerialEpisodeModel | One serial episode of disjoint intervals; a faster model shortens only its own. |
| SpeculativeEpisodeModel | Speculative decoding’s decode-stream speedup, composed with a serial episode. |
| TrajectoryAdmissionModel | Admitted trajectories against a token quota, in the mean. |
| WorkloadLeverModel | Cost per accepted task by workload, C_eff = C_attempt / p_acc, and three levers. |
AdaptationPaybackModel
engine.solvers.cost_accounting.AdaptationPaybackModel()Tasks until a one-time adaptation repays its data, training, and evaluation.
Each task’s model usage is steps times (input tokens x input price + output tokens x output price); the break-even count is the investment over the per-task saving, and the first whole task that crosses it.
Methods
| Name | Description |
|---|---|
| solve | Calculate task volume needed to recover adaptation investment. |
solve
engine.solvers.cost_accounting.AdaptationPaybackModel.solve(
base,
adapted,
data_cost,
training_cost,
evaluation_cost,
monthly_volume,
low_volume,
)Calculate task volume needed to recover adaptation investment.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| base | Mapping[str, float] | Baseline mapping: steps, input_tokens, output_tokens, and USD/Mtoken input_price/output_price quantities. | required |
| adapted | Mapping[str, float] | Adapted mapping with the same keys and units as base. | required |
| data_cost | Quantity | One-time data investment, convertible to USD. | required |
| training_cost | Quantity | One-time training investment, convertible to USD. | required |
| evaluation_cost | Quantity | One-time evaluation investment, convertible to USD. | required |
| monthly_volume | int | Positive tasks per month. | required |
| low_volume | int | Positive lower-volume tasks per month. | required |
Returns
| Name | Type | Description |
|---|---|---|
| AdaptationPaybackResult | Step, task, investment, and saving USD quantities; fractional and rounded task break-even counts; payback months and cost shares. |
Notes
Equation: task cost = steps*(input_tokens*input_price + output_tokens*output_price); crossing = investment/(base_task-adapted_task).
Assumptions: Fixed token usage and tariffs; adaptation lowers cost per task; positive volume and investment.
Excludes: Quality changes, model drift, recurring retraining, and discounting.
References
Derivation: Sum data, training, and evaluation investment. Each completed task repays the difference between baseline and adapted usage bills. Divide investment by this difference, then divide tasks by monthly volume.
Examples
>>> from mlsysim.core.units import Q_
>>> base = dict(steps=2, input_tokens=100, output_tokens=10, input_price=Q_('1 USD/Mtoken'), output_price=Q_('2 USD/Mtoken'))
>>> adapted = dict(base, steps=1)
>>> r = AdaptationPaybackModel().solve(base, adapted, Q_('1 USD'), Q_('1 USD'), Q_('1 USD'), 1000, 100)
>>> r.payback_months_low > r.payback_months
TrueArchitectureChoiceModel
engine.solvers.cost_accounting.ArchitectureChoiceModel()Designs priced by automated spend alone and with a human fallback.
A bounded loop stops at its first accepted turn, so turn j is reached by the share that every earlier turn rejected. Rejected tickets go to a person who resolves a fraction of them; cost per resolved ticket divides the combined spend by combined resolution.
Methods
| Name | Description |
|---|---|
| solve | Compare automated attempts and human fallback per resolved ticket. |
solve
engine.solvers.cost_accounting.ArchitectureChoiceModel.solve(
tickets,
single_costs,
single_acceptance,
loop_name,
turn_cost,
turn_acceptance,
check_cost,
human_cost,
human_resolution,
point,
)Compare automated attempts and human fallback per resolved ticket.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| tickets | int | Nonnegative number of initiated tickets in the reporting period. | required |
| single_costs | Mapping[str, Quantity] | Configuration names mapped to per-attempt USD quantities. | required |
| single_acceptance | Mapping[str, float] | Configuration names mapped to acceptance probabilities in (0,1]. | required |
| loop_name | str | Name for the iterative configuration, distinct from single configurations. | required |
| turn_cost | Quantity | Charge per reached loop turn, convertible to USD. | required |
| turn_acceptance | Sequence[float] | Conditional probabilities of acceptance on each reached turn. | required |
| check_cost | Quantity | Charge for checking each attempt, convertible to USD. | required |
| human_cost | Quantity | Fallback human charge per unresolved automated ticket, convertible to USD. | required |
| human_resolution | float | Fraction of fallback tickets resolved by a person, in [0,1]. | required |
| point | float | Dimensionless fraction of human cost used for point_value. | required |
Returns
| Name | Type | Description |
|---|---|---|
| ArchitectureChoiceResult | Per-configuration USD quantity costs, acceptance/resolution fractions, expected loop turns, and period spend and resolved counts. |
Notes
Equation: reach[j] = product(1-turn_acceptance[:j]); total cost = automated + (1-acceptance)*human_cost; resolved = acceptance+(1-acceptance)*human_resolution.
Assumptions: Conditional turn acceptance probabilities in [0,1]; positive acceptance and resolution denominators; constant fallback cost.
Excludes: Quality comparability, correlated human/model mistakes, and queueing delays.
References
Derivation: Multiply conditional rejection probabilities to obtain each turn reach share. Weight automated charges by reach, then add human fallback cost for rejected tickets and divide by total automated-plus-human resolution.
Examples
>>> from mlsysim.core.units import Q_
>>> r = ArchitectureChoiceModel().solve(10, {'single': Q_('1 USD')}, {'single': 0.5}, 'loop', Q_('1 USD'), [0.5, 0.5], Q_('0.1 USD'), Q_('5 USD'), 1.0, 0.01)
>>> r.resolved['loop'] == 1.0
TrueCohortAttemptCostModel
engine.solvers.cost_accounting.CohortAttemptCostModel()One configuration’s cohort: one bounded attempt per task, all charges settled.
The attempt costs its turns of model tokens and environment plus one assessment; the cohort cost per accepted task divides every attempt’s cost by the accepted count, and triage charges each rejected attempt.
Methods
| Name | Description |
|---|---|
| compare | Compare cost and acceptance changes between equivalent cohorts. |
| solve | Calculate settled cohort spend per accepted task. |
compare
engine.solvers.cost_accounting.CohortAttemptCostModel.compare(
baseline,
alternative,
baseline_accepted,
alternative_accepted,
)Compare cost and acceptance changes between equivalent cohorts.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| baseline | CohortAttemptCostResult | Baseline USD costs; denominators must be positive. | required |
| alternative | CohortAttemptCostResult | Alternative USD costs under equivalent task definitions. | required |
| baseline_accepted | int | Positive baseline accepted count. | required |
| alternative_accepted | int | Alternative accepted count over the same cohort size. | required |
Returns
| Name | Type | Description |
|---|---|---|
| TokenPriceComparisonResult | Original cohort results and dimensionless alternative/baseline cost ratios and relative model, attempt, and acceptance reductions. |
Notes
Equation: cost_ratio = alternative.cost_per_accepted / baseline.cost_per_accepted; cuts = 1-alternative/baseline.
Assumptions: Equivalent task mix, acceptance gate, and cohort sizes.
Excludes: Statistical uncertainty and causal attribution.
References
Derivation: Normalize each alternative cost or count by its corresponding baseline. Subtract from one for a relative reduction.
Examples
>>> from mlsysim.core.units import Q_
>>> r = CohortAttemptCostModel().solve(10, 5, Q_('1 USD/Mtoken'), Q_('2 USD/Mtoken'), 1, 100, 10, Q_('1 USD'), Q_('1 USD'), Q_('1 USD'))
>>> CohortAttemptCostModel.compare(r, r, 5, 5).cost_ratio == 1
Truesolve
engine.solvers.cost_accounting.CohortAttemptCostModel.solve(
tasks,
accepted,
input_price,
output_price,
turns,
input_tokens_per_turn,
output_tokens_per_turn,
environment_per_turn,
assessment_per_attempt,
triage_per_rejected,
)Calculate settled cohort spend per accepted task.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| tasks | int | Number of initiated tasks; positive integer. | required |
| accepted | int | Accepted tasks, with 0 < accepted <= tasks. | required |
| input_price | Quantity | Fresh input tariff, as a quantity convertible to USD/Mtoken. | required |
| output_price | Quantity | Output tariff, as a quantity convertible to USD/Mtoken. | required |
| turns | int | Number of model turns; positive integer. | required |
| input_tokens_per_turn | int | Fresh input count per turn, in tokens. | required |
| output_tokens_per_turn | int | Generated count per turn, in tokens. | required |
| environment_per_turn | Quantity | Environment charge per turn, convertible to USD. | required |
| assessment_per_attempt | Quantity | Assessment charge per attempt, convertible to USD. | required |
| triage_per_rejected | Quantity | Human triage charge per rejected attempt, convertible to USD. | required |
Returns
| Name | Type | Description |
|---|---|---|
| CohortAttemptCostResult | Per-attempt and cohort USD amounts as floats, rejected-task counts, USD per accepted task, and rejected-to-accepted count ratio. |
Notes
Equation: C = turns*(input_tokens*p_in + output_tokens*p_out + environment) + assessment; cohort cost per accepted = tasks*C/accepted.
Assumptions: Every task makes one bounded attempt with the same token budget; accepted is positive and no greater than tasks.
Excludes: Taxes, volume discounts, correlated retry costs, and time-varying tariffs.
References
Derivation: Sum token charges and environment charges over turns, then add the once-per-attempt assessment. Multiply by initiated tasks before dividing by accepted tasks so rejected attempts remain in the numerator.
Examples
>>> from mlsysim.core.units import Q_
>>> r = CohortAttemptCostModel().solve(10, 5, Q_('1 USD/Mtoken'), Q_('2 USD/Mtoken'), 1, 100, 10, Q_('1 USD'), Q_('1 USD'), Q_('1 USD'))
>>> r.rejected == 5
TrueCompactionPaybackModel
engine.solvers.cost_accounting.CompactionPaybackModel()One compaction priced against keeping the transcript, under one tariff.
Compacting at call n_c replaces S tokens of context with a S_c-token summary that costs K output tokens and is resent fresh, so the compacting call costs p_out K + p_in S_c more; every later call reads S - S_c fewer cached tokens. Compaction has paid after n* = 1 + ceil(upfront / per-call saving) calls.
Methods
| Name | Description |
|---|---|
| solve | Compute when a context summary repays its token bill. |
solve
engine.solvers.cost_accounting.CompactionPaybackModel.solve(
turns,
first_prompt,
appended,
input_price,
cached_fraction,
output_price,
compact_turn,
compact_to,
summary_tokens,
)Compute when a context summary repays its token bill.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| turns | int | Number of model turns; positive integer. | required |
| first_prompt | int | Initial prompt length, in tokens. | required |
| appended | int | Tokens appended between consecutive calls. | required |
| input_price | Quantity | Fresh input tariff, as a quantity convertible to USD/Mtoken. | required |
| cached_fraction | float | Cached-input price divided by fresh-input price, in [0,1]. | required |
| output_price | Quantity | Output tariff, as a quantity convertible to USD/Mtoken. | required |
| compact_turn | int | One-based compaction call index within the trajectory. | required |
| compact_to | int | Summary context length in tokens, smaller than the replaced context. | required |
| summary_tokens | int | Generated summary tokens billed at the output tariff. | required |
Returns
| Name | Type | Description |
|---|---|---|
| CompactionPaybackResult | Context and remaining-call counts, USD quantity costs and savings, integer break-even call count, and per-horizon net USD floats. |
Notes
Equation: upfront = p_out*summary_tokens + p_in*compact_to; saving = (context_at_compaction-compact_to)*cached_fraction*p_in; crossing = 1+ceil(upfront/saving).
Assumptions: The summary preserves the required task state; compact_turn is within the trajectory; positive cached price and positive token reduction.
Excludes: Changes in answer quality, latency, and later summary regeneration.
References
Derivation: The summary generation and first fresh summary read are upfront charges. Each later call avoids the same cached-context bill. Divide upfront cost by this saving, round up, and include the compaction call.
Examples
>>> from mlsysim.core.units import Q_
>>> r = CompactionPaybackModel().solve(10, 1000, 10, Q_('1 USD/Mtoken'), 0.5, Q_('2 USD/Mtoken'), 2, 100, 10)
>>> r.per_call_saving > Q_('0 USD')
TrueConservedBudgetModel
engine.solvers.cost_accounting.ConservedBudgetModel()A root budget kept as settled + reserved + free across two children.
Granting moves free to reserved; a child that closes settles its charge and returns the rest. A child stopped with a remote operation pending keeps that operation’s enforceable bound reserved until its final bill settles, once per settlement identity however often it is delivered.
Methods
| Name | Description |
|---|---|
| solve | Track settled, reserved, and free budget through child completion. |
solve
engine.solvers.cost_accounting.ConservedBudgetModel.solve(
budget,
planning,
allocations,
settled_children,
pending,
late_charge,
deliveries=2,
)Track settled, reserved, and free budget through child completion.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| budget | int | Total nonnegative integer budget in milli-USD. | required |
| planning | int | Initial settled planning charge in milli-USD. | required |
| allocations | Sequence[int] | Two nonnegative child reservations in milli-USD. | required |
| settled_children | Sequence[int] | Two child settled charges in milli-USD. | required |
| pending | int | Second child pending reservation in milli-USD. | required |
| late_charge | int | Final charge for the pending operation in milli-USD. | required |
| deliveries | int | Positive count of repeated deliveries of the final bill; default 2. | 2 |
Returns
| Name | Type | Description |
|---|---|---|
| ConservedBudgetResult | Ledger states and child balances in integer milli-USD, with settled, reserved, and free components at each transition. |
Notes
Equation: budget = settled + reserved + free at every transition; duplicate delivery of the same settlement identity is applied once.
Assumptions: Two child allocations in common integer budget units; charges fit reservations; nonnegative conserved state.
Excludes: Distributed durability, concurrent ledger races, and remote billing enforcement.
References
Derivation: A grant transfers free funds to reservations. Settlement transfers a charge from reserved to settled and refunds the unused reservation. Deduplicating the final bill prevents repeated delivery from spending twice.
Examples
>>> from mlsysim.core.units import Q_
>>> r = ConservedBudgetModel().solve(1000, 100, [300, 400], [200, 100], 100, 80)
>>> r.settled_final + r.reserved_final + r.free_final == r.budget
TrueDedicatedBreakEvenModel
engine.solvers.cost_accounting.DedicatedBreakEvenModel()Renting tokens from an API against owning capacity with a fixed hourly cost.
The API’s price per output token carries its input mix; owning pays a fixed F per hour plus v per output token. The costs tie at load u* = F / (3600 R (P_eff - v)) of the reference rate R.
Methods
| Name | Description |
|---|---|
| hourly_costs | Price one hour of API usage and dedicated capacity. |
| solve | Find the load where owned capacity matches API cost. |
hourly_costs
engine.solvers.cost_accounting.DedicatedBreakEvenModel.hourly_costs(
load,
reference_rate,
api_price,
fixed,
variable,
)Price one hour of API usage and dedicated capacity.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| load | float | Delivered reference-capacity fraction, in [0,1]. | required |
| reference_rate | Quantity | Positive token-count rate, convertible to inverse seconds. | required |
| api_price | float | Effective API price in USD per million output tokens. | required |
| fixed | float | Fixed ownership charge in USD per hour. | required |
| variable | float | Variable ownership price in USD per million output tokens. | required |
Returns
| Name | Type | Description |
|---|---|---|
| tuple of float | API bill followed by dedicated-capacity bill, both in USD for one hour. |
Notes
Equation: tokens = load*reference_rate*one_hour; API = tokens*api_price/1e6; dedicated = fixed+tokens*variable/1e6.
Assumptions: Constant load and tariff for one hour.
Excludes: Quality differences, autoscaling delays, and extra usage charges.
References
Derivation: Integrate a constant count rate over an hour, multiply by per-token price, then add fixed ownership charges.
Examples
>>> from mlsysim.core.units import Q_
>>> DedicatedBreakEvenModel.hourly_costs(0.0, Q_('100 / s'), 2.0, 1.0, 0.1)
(0.0, 1.0)solve
engine.solvers.cost_accounting.DedicatedBreakEvenModel.solve(
input_per_output,
cached_fraction,
input_price,
cached_price,
output_price,
fixed_per_hour,
variable_price,
reference_rate,
load,
)Find the load where owned capacity matches API cost.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| input_per_output | float | Nonnegative input-token count per output token. | required |
| cached_fraction | float | Fraction of input tokens served from cache, in [0,1]. | required |
| input_price | float | Nonnegative input price in USD per million tokens. | required |
| cached_price | float | Cached input price in USD per million tokens. | required |
| output_price | float | Nonnegative output price in USD per million tokens. | required |
| fixed_per_hour | float | Fixed ownership charge in USD per hour. | required |
| variable_price | float | Variable ownership charge in USD per million output tokens. | required |
| reference_rate | Quantity | Reference output-token count rate, convertible to inverse seconds. | required |
| load | float | Delivered fraction of reference capacity, in [0,1]. | required |
Returns
| Name | Type | Description |
|---|---|---|
| DedicatedBreakEvenResult | Effective prices in USD per million tokens, hourly token counts, hourly USD cost floats, and dimensionless crossing loads. |
Notes
Equation: API effective price = output_price + input_per_output*((1-cached_fraction)*input_price+cached_fraction*cached_price); crossing = fixed_per_hour/(reference_hour_tokens*(API-variable_price)/1e6).
Assumptions: Fixed hourly ownership bill; proportional token cost; cached_fraction in [0,1]; effective API price exceeds variable_price.
Excludes: Autoscaling delays, capacity acquisition, utilization variance, and quality differences.
References
Derivation: Weight fresh and cached input tariffs by their traffic fractions and input/output mix. Equate linear API spend with fixed-plus-variable ownership spend and solve for the delivered fraction of reference capacity.
Examples
>>> from mlsysim.core.units import Q_
>>> r = DedicatedBreakEvenModel().solve(1.0, 0.5, 2.0, 1.0, 3.0, 1.0, 0.1, Q_('100 / s'), 0.5)
>>> r.delivered_hour_tokens == r.reference_hour_tokens * 0.5
TrueKingmanQueueModel
engine.solvers.cost_accounting.KingmanQueueModel()Kingman’s mean wait for one server at two utilizations, and its holding price.
E[W] = (c_a^2 + c_s^2) / 2 * rho / (1 - rho) * E[S]; each second of wait holds resources at holding_rate dollars.
Methods
| Name | Description |
|---|---|
| solve | Estimate mean queue wait and its resource holding cost. |
solve
engine.solvers.cost_accounting.KingmanQueueModel.solve(
service,
arrival_scv,
service_scv,
low,
high,
holding_rate,
)Estimate mean queue wait and its resource holding cost.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| service | Quantity | Positive mean service duration, convertible to seconds. | required |
| arrival_scv | float | Squared coefficient of variation of interarrival times, nonnegative. | required |
| service_scv | float | Squared coefficient of variation of service times, nonnegative. | required |
| low | float | Lower utilization in (0,1). | required |
| high | float | Higher utilization in (0,1). | required |
| holding_rate | float | Holding cost in USD per second of waiting. | required |
Returns
| Name | Type | Description |
|---|---|---|
| KingmanQueueResult | Mean wait quantities in service-time units, holding costs as USD floats, and dimensionless variability, utilization, and wait ratios. |
Notes
Equation: W = service*(arrival_scv+service_scv)/2*rho/(1-rho); holding cost = W_seconds*holding_rate.
Assumptions: Single-server stationary renewal approximation; positive service and variability; 0 < low, high < 1.
Excludes: Tail latency, transient overload, and multiple-server scheduling.
References
Derivation: The Kingman single-server approximation multiplies mean service time by a variability factor and rho/(1-rho). Convert the resulting wait to seconds before applying the holding tariff. This is an approximation, not an exact queueing identity; see calc_kingman_wait_ratio.
Examples
>>> from mlsysim.core.units import Q_
>>> r = KingmanQueueModel().solve(Q_('1 s'), 1.0, 1.0, 0.5, 0.75, 1.0)
>>> r.wait_high > r.wait_low
TrueModelCascadeModel
engine.solvers.cost_accounting.ModelCascadeModel()A tiered cascade under one acceptance gate, priced over a completed cohort.
Every reached tier pays its call and the gate; the cascade’s cost per accepted task divides the whole spend by every tier’s exits. Optionally a harm per false accept at the first tier, whose break-even rate erases the cascade’s saving over the top tier alone.
Methods
| Name | Description |
|---|---|
| solve | Price a completed cohort through sequential model tiers. |
solve
engine.solvers.cost_accounting.ModelCascadeModel.solve(
tasks,
call_costs,
gate_cost,
call_times,
gate_time,
accepted_by_tier,
direct_accepted,
false_accept_rate=None,
harm_per_false_accept=None,
)Price a completed cohort through sequential model tiers.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| tasks | int | Number of initiated tasks; positive integer. | required |
| call_costs | Sequence[float] | Aligned tier call costs in USD per call. | required |
| gate_cost | float | Acceptance-check cost in USD per reached tier. | required |
| call_times | Sequence[float] | Aligned tier call durations in seconds. | required |
| gate_time | float | Check duration in seconds per reached tier. | required |
| accepted_by_tier | Sequence[int] | Counts exiting each tier, bounded by the cohort reaching it. | required |
| direct_accepted | int | Positive number accepted when using the final tier alone. | required |
| false_accept_rate | Optional[float] | Optional fraction of first-tier accepts that are false, in [0,1]. | None |
| harm_per_false_accept | Optional[float] | Optional harm cost in USD per false first-tier accept. | None |
Returns
| Name | Type | Description |
|---|---|---|
| ModelCascadeResult | Reached/accepted counts, conditional acceptance fractions, USD cost floats, mean and worst-path seconds, and optional USD harm costs. |
Notes
Equation: reached[j+1] = reached[j]-accepted[j]; spend = sum(reached[j]*(call_cost[j]+gate_cost)); cost per accepted = spend/sum(accepted).
Assumptions: Each acceptance exits the cascade; aligned tier sequences; positive reached and accepted denominators.
Excludes: Unobserved acceptance quality, correlated latency, and asynchronous tier overlap.
References
Derivation: Only unresolved tasks reach the next tier. Multiply each tier charge and duration by its reached population, then normalize spend by all accepted exits and elapsed work by all initiated tasks.
Examples
>>> from mlsysim.core.units import Q_
>>> r = ModelCascadeModel().solve(10, [1.0, 3.0], 0.1, [1.0, 2.0], 0.1, [5, 4], 9)
>>> r.reached == [10, 5]
TruePrefixCacheBillModel
engine.solvers.cost_accounting.PrefixCacheBillModel()An append-only trajectory billed at the fresh rate, and with ideal prefix reuse.
The logical input is H s0 + delta H (H - 1) / 2; ideal reuse bills only s0 + (H - 1) delta at the input rate and the rest at the cached rate, so caching scales the quadratic term down without removing it. A miss on miss_fraction of the eligible prefix bills it at the full rate.
Methods
| Name | Description |
|---|---|
| solve | Price append-only prompts with ideal prefix reuse. |
solve
engine.solvers.cost_accounting.PrefixCacheBillModel.solve(
turns,
first_prompt,
appended,
output_per_turn,
input_price,
cached_fraction,
output_price,
miss_fraction,
)Price append-only prompts with ideal prefix reuse.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| turns | int | Number of model turns; positive integer. | required |
| first_prompt | int | Initial prompt length, in tokens. | required |
| appended | int | Tokens appended between consecutive calls. | required |
| output_per_turn | int | Generated tokens per turn. | required |
| input_price | Quantity | Fresh input tariff, as a quantity convertible to USD/Mtoken. | required |
| cached_fraction | float | Cached-input price divided by fresh-input price, in [0,1]. | required |
| output_price | Quantity | Output tariff, as a quantity convertible to USD/Mtoken. | required |
| miss_fraction | float | Fraction of reusable prefix charged fresh, in [0,1]. | required |
Returns
| Name | Type | Description |
|---|---|---|
| PrefixCacheBillResult | Sent and fresh token counts, cached and uncached USD quantity bills, dimensionless cost ratios, and per-turn USD amounts as floats. |
Notes
Equation: sent = H*s0 + delta*H*(H-1)/2; fresh = s0 + (H-1)*delta. Cached input costs p_in*(fresh + cached_fraction*(sent-fresh)).
Assumptions: Positive turn count; cached_fraction and miss_fraction lie in [0,1]; only unchanged prefixes are eligible.
Excludes: Cache capacity, eviction, cache-write charges, and changes in generation latency.
References
Derivation: Sum the arithmetic progression of prompt lengths. Each token is fresh on its first appearance; subsequent appearances form the cached portion. Apply the two tariffs separately, then add generated-token cost.
Examples
>>> from mlsysim.core.units import Q_
>>> r = PrefixCacheBillModel().solve(2, 100, 10, 5, Q_('1 USD/Mtoken'), 0.1, Q_('2 USD/Mtoken'), 0.0)
>>> r.sent_tokens == 210 and r.fresh_tokens == 110
TrueRetryPolicyModel
engine.solvers.cost_accounting.RetryPolicyModel()Bounded attempt policies under independent attempts at a fixed all-in cost.
Sequential retry with early stopping covers 1 - (1 - p)^k of tasks in coverage / p attempts on average, so its cost per accepted task is c / p whatever the cap; a batch of k pays for all k.
Methods
| Name | Description |
|---|---|
| solve | Compare bounded sequential retries with a paid batch. |
solve
engine.solvers.cost_accounting.RetryPolicyModel.solve(
pass_probability,
attempt_cost,
max_attempts,
strong_pass_probability,
strong_attempt_cost,
)Compare bounded sequential retries with a paid batch.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| pass_probability | float | Independent per-attempt success probability in (0,1]. | required |
| attempt_cost | Quantity | All-in attempt charge, convertible to USD. | required |
| max_attempts | int | Positive integer cap on attempts. | required |
| strong_pass_probability | float | Comparison configuration success probability in (0,1]. | required |
| strong_attempt_cost | Quantity | Comparison configuration charge, convertible to USD. | required |
Returns
| Name | Type | Description |
|---|---|---|
| RetryPolicyResult | Coverage probability, expected attempt count, USD quantity spends and costs per accepted task, and dimensionless batch premium. |
Notes
Equation: coverage = 1-(1-p)**k; expected attempts = sum((1-p)**j for j in range(k)); sequential spend = cost*expected attempts.
Assumptions: Independent trials with constant success probability in (0,1]; positive max_attempts and positive strong_pass_probability.
Excludes: Correlation across retries, changing attempt difficulty, cancellation, and latency.
References
Derivation: Trial j is reached only if the preceding trials fail. Sum those reach probabilities for expected sequential attempts. A batch pays for every attempt, even when an earlier member would have succeeded.
Examples
>>> from mlsysim.core.units import Q_
>>> r = RetryPolicyModel().solve(0.5, Q_('1 USD'), 2, 0.8, Q_('2 USD'))
>>> r.expected_attempts == 1.5
TrueSerialEpisodeModel
engine.solvers.cost_accounting.SerialEpisodeModel()One serial episode of disjoint intervals; a faster model shortens only its own.
T' = T_other + T_model / s (Amdahl’s law); instant model calls bound the episode speedup at 1 / (1 - f).
Methods
| Name | Description |
|---|---|
| solve | Apply a model-only speedup to a serial episode. |
solve
engine.solvers.cost_accounting.SerialEpisodeModel.solve(
model_intervals,
tests,
lifecycle_intervals,
runtime_intervals,
model_speedup,
)Apply a model-only speedup to a serial episode.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| model_intervals | Sequence[float] | Disjoint model execution durations in seconds. | required |
| tests | float | Test duration in seconds. | required |
| lifecycle_intervals | Sequence[float] | Disjoint startup and shutdown durations in seconds. | required |
| runtime_intervals | Sequence[float] | Other disjoint runtime durations in seconds. | required |
| model_speedup | float | Positive multiplicative acceleration of model intervals. | required |
Returns
| Name | Type | Description |
|---|---|---|
| SerialEpisodeResult | Component, total, changed, and saved durations as second quantities; model fraction and achieved/limiting speedups are dimensionless. |
Notes
Equation: T_new = T_other + T_model/model_speedup; speedup = T_total/T_new.
Assumptions: Nonnegative disjoint intervals; positive speedup and positive non-model time for the finite limiting ratio.
Excludes: Overlap between intervals, queueing, and changes to non-model work.
References
Derivation: Partition elapsed time into model and non-model intervals. Divide only the model sum by the supplied acceleration; leave other intervals unchanged. Zero model time gives the limiting episode speedup.
Examples
>>> from mlsysim.core.units import Q_
>>> r = SerialEpisodeModel().solve([2.0], 1.0, [1.0], [], 2.0)
>>> r.changed_time == Q_('3 s')
TrueSpeculativeEpisodeModel
engine.solvers.cost_accounting.SpeculativeEpisodeModel()Speculative decoding’s decode-stream speedup, composed with a serial episode.
Treats the episode’s model time as pure decode (an optimistic bound): T' = T [(1 - f) + f / S] with S = (m + 1) / (gamma r + 1).
Methods
| Name | Description |
|---|---|
| solve | Propagate decode speedup into serial episode time. |
solve
engine.solvers.cost_accounting.SpeculativeEpisodeModel.solve(
total_time,
decode_fraction,
draft_length,
draft_cost_ratio,
accepted_high,
accepted_low,
)Propagate decode speedup into serial episode time.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| total_time | float | Baseline episode duration in seconds. | required |
| decode_fraction | float | Fraction of episode spent decoding, in [0,1). | required |
| draft_length | int | Positive number of drafted tokens per round. | required |
| draft_cost_ratio | float | Draft-token cost relative to one target step, nonnegative. | required |
| accepted_high | float | Higher assumed mean accepted draft tokens per round. | required |
| accepted_low | float | Lower assumed mean accepted draft tokens per round. | required |
Returns
| Name | Type | Description |
|---|---|---|
| SpeculativeEpisodeResult | Decode speedups, accepted-token break-even count, episode times as second quantities, and dimensionless episode speedup bounds. |
Notes
Equation: S = (accepted+1)/(draft_length*draft_cost_ratio+1); T_new = T*((1-f)+f/S).
Assumptions: Constant draft costs and accepted-token means; decode_fraction in [0,1); accepted counts between zero and draft_length.
Excludes: Prefill acceleration, variable-context memory costs, and overlap with other work.
References
Derivation: A speculative round spends one target step plus the draft-step budget and returns accepted drafts plus a bonus token. Divide returned tokens by normalized round cost, then accelerate only the decode share.
Examples
>>> from mlsysim.core.units import Q_
>>> r = SpeculativeEpisodeModel().solve(10.0, 0.5, 4, 0.1, 3.0, 1.0)
>>> r.episode_time_high < r.episode_time_low
TrueTrajectoryAdmissionModel
engine.solvers.cost_accounting.TrajectoryAdmissionModel()Admitted trajectories against a token quota, in the mean.
Little’s law gives the trajectories present; the call and token rates scale with admissions. At fixed goodput, admissions scale as 1 / alpha, so a relative acceptance drop of 1 - quota_share fills the quota.
Methods
| Name | Description |
|---|---|
| solve | Compare mean trajectory traffic with a token quota. |
solve
engine.solvers.cost_accounting.TrajectoryAdmissionModel.solve(
arrival,
residence,
calls,
tokens_per_call,
quota,
acceptance_drop=None,
)Compare mean trajectory traffic with a token quota.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| arrival | Quantity | Mean trajectory arrival rate, convertible to inverse seconds. | required |
| residence | Quantity | Mean trajectory residence time, convertible to seconds. | required |
| calls | int | Positive calls per trajectory. | required |
| tokens_per_call | int | Positive token count per call. | required |
| quota | Quantity | Positive token-count rate in inverse seconds; token counts are dimensionless here. | required |
| acceptance_drop | Optional[float] | Optional relative acceptance reduction, in [0,1). | None |
Returns
| Name | Type | Description |
|---|---|---|
| TrajectoryAdmissionResult | Mean concurrent trajectories, call and demand rates in the supplied arrival units, tokens per trajectory, and dimensionless quota shares. |
Notes
Equation: concurrent = arrival*residence; demand = arrival*calls*tokens_per_call; quota share = demand/quota.
Assumptions: Stationary mean arrivals and fixed work per trajectory; positive quota and tokens per trajectory; acceptance_drop in [0,1).
Excludes: Burst admission, service-time variability, and enforcement of provider quotas.
References
Derivation: Little’s-law occupancy multiplies mean admission rate by residence time. Each admission induces a fixed number of calls and tokens; their product with admission rate is the mean quota demand.
Examples
>>> from mlsysim.core.units import Q_
>>> r = TrajectoryAdmissionModel().solve(Q_('1 / s'), Q_('2 s'), 2, 10, Q_('100 / s'))
>>> r.concurrent == 2
TrueWorkloadLeverModel
engine.solvers.cost_accounting.WorkloadLeverModel()Cost per accepted task by workload, C_eff = C_attempt / p_acc, and three levers.
Halving the token price saves half the model share; halving the largest term saves half its share; raising acceptance by dp saves dp / (p + dp) of every term, and also removes the handoffs charged per rejected attempt. Acceptance beats halving tokens whenever the model share is below 2 dp / (p + dp).
Methods
| Name | Description |
|---|---|
| solve | Compare token, dominant-cost, and acceptance improvements. |
solve
engine.solvers.cost_accounting.WorkloadLeverModel.solve(
workloads,
acceptance_gain,
)Compare token, dominant-cost, and acceptance improvements.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| workloads | Mapping[str, Mapping[str, float]] | Names mapped to model, environment, assessment, human costs in USD and acceptance in (0,1]; optional handoff replaces human with (1-acceptance)*handoff. | required |
| acceptance_gain | float | Absolute increase in acceptance probability; keeps each probability at most one. | required |
Returns
| Name | Type | Description |
|---|---|---|
| WorkloadLeverResult | Rows with USD attempt and accepted-task costs as floats, the dominant cost-term name, and dimensionless lever savings and shares. |
Notes
Equation: cost per accepted = sum(attempt costs)/acceptance; each lever recomputes this ratio after changing its specified term.
Assumptions: Positive acceptance and total cost; acceptance_gain keeps acceptance at most one; costs use a common currency.
Excludes: Interactions among levers, causal predictions of acceptance, and changed task mix.
References
Derivation: Recompute cost per accepted task after halving model cost, halving the largest cost term, or raising acceptance. If human cost is charged per rejection, recompute that term under the changed rejection fraction.
Examples
>>> from mlsysim.core.units import Q_
>>> w = {'x': dict(model=1.0, environment=2.0, assessment=1.0, human=1.0, acceptance=0.5)}
>>> r = WorkloadLeverModel().solve(w, 0.1)
>>> r.rows['x'].largest_term == 'environment'
True