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.timingtimes 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.promptsloads Spec-Bench, GSM8K and HumanEval prompts throughdatasets; further suites are added by registration in :data:PROMPT_SOURCES. - :mod:
~economize.bench.cost_modelprices 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)
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 ( |
logits |
Literal['all', 'last', 'none']
|
Which tokens get logits: |
head_rows |
int | None
|
Rows of the LM head applied ( |
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 |
None
|
modules
|
Mapping[str, CallSpec] | None
|
Pricing of the calls of separate networks, by module name. |
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'
|
weight_bytes
|
float
|
Bytes per weight entry ( |
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 |
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
|
|
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]
|
|
dict[str, float]
|
|
dict[str, float]
|
modelled, never measured (time a generation with :func: |
dict[str, float]
|
and |
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 |
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 |
hidden |
int
|
Width of the residual stream |
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 ( |
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 ( |
shared_gate |
bool
|
Whether a sigmoid gate ( |
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 ( |
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 |
mixer_params |
int
|
Weight entries of one |
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 |
attention_params
property
¶
attention_params: int
Weights of the query, key, value and output projections of one layer.
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.
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.
get_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: |
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: |
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 |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Timing, _T]
|
The timing and the result of the last call. |