Skip to content

economize.bench

Wall-clock timing, standard prompt suites and an analytic cost model.

Benchmarking: wall-clock timing, standard prompt suites and an analytic cost model.

  • :mod:~economize.bench.timing times model calls and generations with warmup and repeated measurements (CUDA events on one device, synchronised host clocks on several) and reports medians and throughput.
  • :mod:~economize.bench.prompts loads Spec-Bench, GSM8K and HumanEval prompts through datasets; further suites are added by registration in :data:PROMPT_SOURCES.
  • :mod:~economize.bench.cost_model prices the cost log of a generation (FLOPs and bytes per call, a roofline time per call on an accelerator preset) and compares it with plain decoding of the same output. Model families whose configs need special reading register a reader in :data:SHAPE_READERS.

A typical speed measurement::

from economize.bench import benchmark_generation, load_prompts

prompts = load_prompts("spec-bench", limit=80).tokenize(tokenizer, chat=True)
plain = benchmark_generation(lambda ids: model.generate(ids[None].cuda(), max_new_tokens=256)[0, ids.numel():],
                             prompts)
fast = benchmark_generation(lambda ids: model.decode(ids.cuda(), 256), prompts)
print(fast.speedup_over(plain))

CallCost dataclass

CallCost(flops: float = 0.0, bytes: float = 0.0, calls: int = 1)

FLOPs and bytes moved by one or more calls.

intensity property

intensity: float

FLOPs per byte.

seconds

seconds(hardware: Hardware | str) -> float

Roofline time of one call with these totals (sum per-call times for several calls, as :meth:CostReport.seconds does).

CallSpec dataclass

CallSpec(shape: ModelShape | None = None, logits: Literal['all', 'last', 'none'] = 'all', head_rows: int | None = None, extra_params: int = 0)

How the calls of one kind are priced.

Attributes:

Name Type Description
shape ModelShape | None

Whose decoder layers the call's layer range refers to (None: the target model's).

logits Literal['all', 'last', 'none']

Which tokens get logits: "all", "last" or "none".

head_rows int | None

Rows of the LM head applied (None: the shape's vocabulary; fewer for a reduced draft vocabulary).

extra_params int

Weight entries applied per token besides the decoder layers and the head (a readout adapter, Medusa heads, an EAGLE layer's fusion).

CostModel

CostModel(target: ModelShape, *, draft: CallSpec | None = None, modules: Mapping[str, CallSpec] | None = None, specs: Mapping[str, CallSpec] | None = None, exact_logits: Literal['all', 'last'] = 'all', weight_bytes: float = 2.0, kv_bytes: float = 2.0)

Prices the cost log of a generation for one architecture.

An event of the decoded model (module None) is priced by its kind through specs. An event of a separate network (module set, such as "draft_model", "eagle3" or "mtp") is priced by that network's entry in modules: its draft steps as the entry says, and its other calls (catching up on or observing committed tokens) without logits. Either way the call runs exactly the layers in :attr:~economize.decoding.CostEvent.layer_indices, which need not be contiguous.

Parameters:

Name Type Description Default
target ModelShape

The shape of the model being decoded.

required
draft CallSpec | None

How draft steps are priced. It prices the "draft" and "draft_wasted" events of the decoded model (default: the target's layers in the event's range, logits over the full vocabulary), and is the default of modules["draft_model"], so a separate draft model passes its own shape here.

None
modules Mapping[str, CallSpec] | None

Pricing of the calls of separate networks, by module name. shape is the network's own (its layers count from 1); None uses the target's shape, for modules that run no layers of their own (Medusa heads, given as extra_params).

None
specs Mapping[str, CallSpec] | None

Pricing of further kinds of events of the decoded model, or replacements of the defaults.

None
exact_logits Literal['all', 'last']

Which tokens of an exact call (other than the prompt's) get logits: "all" when the call verifies drafts, "last" when it only refreshes the cache as in lossy decoding.

'all'
weight_bytes float

Bytes per weight entry (2 for bf16, 1 for fp8 or int8, 0.5 for int4).

2.0
kv_bytes float

Bytes per cached key or value entry.

2.0

Raises:

Type Description
ConfigError

(when pricing) an event names a module without an entry in modules.

spec

spec(kind: str, module: str | None = None) -> CallSpec

The pricing of a call of kind by module (None: the decoded model, where an unknown kind runs the target's layers without logits).

Raises:

Type Description
ConfigError

module has no entry in :attr:modules.

event

event(event: CostEvent) -> CallCost

FLOPs and bytes of one call.

log

log(log: CostLog | Iterable[CostEvent]) -> CostReport

Every call of a generation, priced.

plain_log

plain_log(prompt_tokens: int, generated: int) -> CostLog

The calls of plain decoding: the prompt in one exact call, then one call per generated token but the last (the convention of :meth:CostLog.summary).

plain

plain(prompt_tokens: int, generated: int) -> CostReport

Plain decoding of generated tokens after a prompt of prompt_tokens, priced.

relative

relative(log: CostLog | Iterable[CostEvent], prompt_tokens: int, generated: int, hardware: Hardware | str | None = None) -> dict[str, float]

A generation's cost relative to plain decoding of the same output.

Returns:

Type Description
dict[str, float]

flops, bytes and calls ratios (below 1 is cheaper) and, with hardware, the

dict[str, float]

modelled_seconds ratio of the roofline times and its inverse modelled_speedup. Both are

dict[str, float]

modelled, never measured (time a generation with :func:benchmark_generation for that); seconds

dict[str, float]

and speedup are kept as aliases of the two.

CostReport dataclass

CostReport(calls: tuple[tuple[str, CallCost], ...])

The priced calls of one generation.

seconds

seconds(hardware: Hardware | str) -> float

Sum of the per-call roofline times.

by_kind

by_kind() -> dict[str, CallCost]

Totals per kind of call.

Hardware dataclass

Hardware(name: str, flops: float, bandwidth: float, call_overhead: float = 0.0)

Peak dense throughput and memory bandwidth of an accelerator.

Attributes:

Name Type Description
name str

Display name.

flops float

Peak dense FLOP/s at the weights' precision (bf16 tensor cores for the presets).

bandwidth float

Memory bandwidth in bytes/s.

call_overhead float

Seconds added to every call (kernel launches, host work). The presets set 0: their roofline times leave launch and host overhead out, which favours methods that make many small calls. Measure it on your runtime and set it with dataclasses.replace(get_hardware("a100-80gb"), call_overhead=...) to include it.

ridge property

ridge: float

FLOPs per byte above which a call is compute bound.

ModelShape dataclass

ModelShape(num_layers: int, hidden: int, heads: int, kv_heads: int, head_dim: int, intermediate: int, vocab: int, gated: bool = True, experts: int = 0, active_experts: int = 0, expert_intermediate: int = 0, shared_intermediate: int = 0, shared_gate: bool = True, dense_layers: frozenset[int] = frozenset(), layer_types: tuple[str, ...] = (), sliding_window: int | None = None, chunk_size: int | None = None, layer_parts: tuple[frozenset[str], ...] = (), mixer_params: int = 0, expert_hidden: int = 0)

The sizes of a decoder-only transformer that its cost depends on.

Attributes:

Name Type Description
num_layers int

Decoder layers L.

hidden int

Width of the residual stream d.

heads int

Query heads.

kv_heads int

Key/value heads.

head_dim int

Width of one head.

intermediate int

Width of a dense MLP.

vocab int

Rows of the LM head.

gated bool

Whether the MLP is gated (three matrices, as SwiGLU) or not (two).

experts int

Routed experts per mixture-of-experts layer (0 for a dense model).

active_experts int

Experts each token routes to.

expert_intermediate int

Width of one routed expert.

shared_intermediate int

Total width of the shared experts (0 if none).

shared_gate bool

Whether a sigmoid gate (hidden -> 1) scales the shared experts (Qwen2-MoE) or not (DeepSeek, Llama-4).

dense_layers frozenset[int]

Layers (1-indexed) with a dense MLP in a mixture-of-experts model.

layer_types tuple[str, ...]

Attention type per layer ("full_attention", "sliding_attention", "chunked_attention" or another type that is counted without attention over the context); empty means full attention everywhere.

sliding_window int | None

Keys a sliding-window layer attends to (including the query's own).

chunk_size int | None

Tokens per chunk of a chunked-attention layer (Llama-4): a query attends to the earlier keys of its own chunk.

layer_parts tuple[frozenset[str], ...]

The parts of each layer, out of "attention" (the query, key, value and output projections), "mlp" (a dense MLP, or the mixture of experts of an MoE layer) and "mixer" (a token mixer of mixer_params weights, such as a Mamba-2 block); empty means attention and MLP in every layer. Attention over the context follows layer_types.

mixer_params int

Weight entries of one "mixer" part.

expert_hidden int

Width the routed experts read and write when a latent MoE projects the hidden state down before them and back up after them (Nemotron-H's moe_latent_size); 0: no projection, the experts read the hidden state.

attention_params property

attention_params: int

Weights of the query, key, value and output projections of one layer.

head_params property

head_params: int

Weights of the LM head.

total_params property

total_params: int

Weight matrices of all layers plus the head (a tied embedding counts once).

from_config classmethod

from_config(config: HFConfig, **overrides: Unpack[ShapeFields]) -> ModelShape

Read the shape from a transformers config (the text config of a multimodal one).

The generic reading knows the common config spellings; the family's corrections then fix what it spells differently (the adapter's shape_fields, then the reader registered in :data:SHAPE_READERS for the config's model_type, see :mod:.shape_readers), and overrides replace fields that the config does not describe well.

parts

parts(layer: int) -> frozenset[str]

The parts of layer (1-indexed), see :attr:layer_parts.

is_moe

is_moe(layer: int) -> bool

Whether layer (1-indexed) has a mixture-of-experts MLP.

layer_params

layer_params(layer: int = 1) -> int

Stored weight-matrix entries of layer (1-indexed); biases and norms are left out.

active_params

active_params(layer: int = 1) -> int

Weight-matrix entries one token is multiplied with in layer.

touched_params

touched_params(layer: int, tokens: int) -> float

Expected weight entries that tokens tokens read in layer (distinct experts under uniform routing).

attended_keys

attended_keys(layer: int, position: int, tokens: int) -> int

Keys attended in total by tokens tokens starting at position (token i sees position+i+1, capped at the window of a sliding layer, (position+i) % chunk_size + 1 in a chunked layer; 0 for a layer without attention over the context).

cached_keys

cached_keys(layer: int, end: int, tokens: int = 1) -> int

Key/value entries that a call of tokens tokens ending at position end reads from the cache of layer: the union of the keys its tokens attend to (the window of the first token reaches back window - 1 keys, the chunk of the first token starts at a multiple of the chunk size).

PromptSet dataclass

PromptSet(name: str, texts: tuple[str, ...], categories: tuple[str, ...] = ())

Prompts of one suite.

Attributes:

Name Type Description
name str

The suite.

texts tuple[str, ...]

Prompt texts.

categories tuple[str, ...]

Category per prompt (the suite name when it has none).

by_category

by_category() -> dict[str, list[int]]

Prompt indices per category, in order of first appearance.

tokenize

tokenize(tokenizer: PromptTokenizer, *, chat: bool = False, **template: object) -> list[Tensor]

Token ids [P] per prompt; chat=True wraps each prompt as a user turn of the tokenizer's chat template with the generation prompt appended (template goes to apply_chat_template).

GenerationTiming dataclass

GenerationTiming(prompts: tuple[PromptTiming, ...] = tuple())

A generation benchmark over a prompt set.

Throughput is total tokens over the sum of the per-prompt medians, so long generations weigh more, as they do for a user.

speedup_over

speedup_over(baseline: GenerationTiming) -> float

Throughput relative to baseline (above 1 is faster).

Both timings must cover the same prompts (checked by their number); the token counts may differ, e.g. for a lossy method that stops at another place.

Raises:

Type Description
ConfigError

The two timings have different numbers of prompts.

PromptTiming dataclass

PromptTiming(tokens: int, timing: Timing)

One prompt: tokens generated and the timing of its generation.

Timing dataclass

Timing(samples: tuple[float, ...])

Repeated measurements of one call, in seconds.

spread property

spread: float

Interquartile range (0 for fewer than two samples).

get_hardware

get_hardware(hardware: Hardware | str) -> Hardware

A :class:Hardware itself, or the preset of that name.

load_prompts

load_prompts(name: str, limit: int | None = None, **options: object) -> PromptSet

Load the prompt suite name (see the module docstring), keeping the first limit prompts.

benchmark_generation

benchmark_generation(generate: Callable[[Tensor], object], prompts: Sequence[Tensor], *, warmup: int = 1, repeats: int = 3, warmup_per_prompt: int = 0, devices: Iterable[device | str | int] | None = None) -> GenerationTiming

Time generate(prompt) on every prompt.

Parameters:

Name Type Description Default
generate Callable[[Tensor], object]

Runs one generation and returns its output (see :func:count_tokens), e.g. lambda ids: model.decode(ids, 256).

required
prompts Sequence[Tensor]

Token ids per prompt.

required
warmup int

Untimed generations of the first prompt before the first measurement.

1
repeats int

Timed generations per prompt (the median counts).

3
warmup_per_prompt int

Untimed generations of every prompt before its measurements, for decoders that compile, capture CUDA graphs or grow buffers per prompt length (the median of three or more repeats also drops one such slow run).

0
devices Iterable[device | str | int] | None

The devices the generation computes on (see :func:time_call). Name every GPU of a multi-device generation, e.g. devices=[target_device, drafter_device] for SSD.

None

Raises:

Type Description
ConfigError

No prompts, or a negative warmup.

count_tokens

count_tokens(output: object) -> int

Generated tokens in a generation's output: an int, a token tensor (all its elements, so a [B, N] batch counts B * N including any padding), a sequence of token ids, an object with a tokens attribute (DecodeResult, SSDResult) or a sequence of such outputs (the results of decode_batch), summed.

Raises:

Type Description
TypeError

The output is text or of another type whose tokens cannot be counted.

time_call

time_call(fn: Callable[[], _T], *, warmup: int = 1, repeats: int = 5, devices: Iterable[device | str | int] | None = None) -> tuple[Timing, _T]

Time fn() repeats times after warmup untimed calls.

Parameters:

Name Type Description Default
fn Callable[[], _T]

The call to time.

required
warmup int

Untimed calls first (compilation, CUDA graph capture, allocator growth).

1
repeats int

Timed calls.

5
devices Iterable[device | str | int] | None

The devices fn computes on (default: the current CUDA device, if any). CUDA events time a call on one device; with several the host clock times it after synchronising all of them. A call that computes on two GPUs, such as :class:~economize.distributed.AsyncSpeculativeDecoder with its drafter on a second device, must name both (devices=[target_device, drafter_device]): the default times only the current device and misses work still queued on the other.

None

Returns:

Type Description
tuple[Timing, _T]

The timing and the result of the last call.