跳转至

Roofline

本页暂无中文版。以下为英文原文。

This document describes the roofline field in src/tileops/manifest/: what it is, how to author one, and who consumes it.

1. Performance Model

1.1 Baseline Selection

Kernel performance is measured against hardware Speed-of-Light (SOL), not against PyTorch or vendor baselines. The roofline field supplies the per-op inputs this model needs (§2).

1.2 Metric Definition

memory_time  = bytes_moved / hbm_bandwidth
compute_time = total_flops / peak_flops
sol_time     = max(memory_time, compute_time)
efficiency   = sol_time / actual_time

Inputs:

  • bytes_moved, total_flops — manifest roofline (§2).
  • hbm_bandwidth — GPU profile (§5.1), hbm section, effective value.
  • peak_flops — GPU profile section named by op.roof_key() (§1.4), effective value.
  • actual_time — benchmark output (§5.2): device-busy time plus any device copies excluded from it.

Bound type is whichever term dominates sol_time; a tie is memory-bound. It depends on shape, not on the op; the roofline tool computes it per-workload and the manifest does not declare it.

The metric is algorithmic SOL efficiency. Five statements delimit what a reading means:

  1. bytes_moved is the algorithm's minimum traffic, not measured DRAM traffic: each distinct input storage the algorithm reads counts one read, each public output one write, a mutated input on a branch where it is written both, a write_only input one write, and a declared alias one storage. An intermediate never counts, whatever stage produces it, and any other input the algorithm does not read produces no traffic.
  2. An input the algorithm reads in part counts the distinct elements it reads. A formula may charge the whole storage instead where the two differ by under 1% on every workload row.
  3. The metric is defined on a call that binds one storage per declared input, as every workloads row does. An aliasing call such as add(x, x) is priced at two operands; the metric does not describe it.
  4. total_flops follows the §1.3 counting convention, not per-instruction hardware cost; the metric does not certify an SFU-bound kernel as at its limit.
  5. The compute roof is the unit an optimal implementation would use (§1.4), not the unit the current kernel runs on.

Rows the model cannot price honestly are handled three ways:

  • Blank, never guessed — timed without CUPTI, bytes formula yields zero, or no GPU profile matches the device.
  • Labeled latency-bound — sol_time and measured time both below the latency floor: launch overhead dominates and the model has no traction; regression detection still covers the row.
  • Reported as a formula error, never as a fast kernel — the row implies a rate above a theoretical ceiling.

1.3 Convention

Per-element FLOP rule for elementwise ops:

  • One basic arithmetic op (add, sub, mul, div, neg, abs, recip) counts as 1 FLOP.
  • One transcendental call (exp, log, erf, tanh, sin, sqrt, rsqrt, …) counts as 1 FLOP, whatever it costs on the hardware.
  • One compare-and-select (max, min, maximum, minimum, single- or two-bound clamp, relu-style branch, where) counts as 1 FLOP per output element.
  • Predicate-only outputs (eq, gt, etc.) count as 1 FLOP per element.

Composite ops sum their primitives — sigmoid = neg + exp + add + recip = 4 FLOPs/elem; silu = sigmoid + mul = 5 FLOPs/elem.

Beyond the elementwise rule, total_flops is the least arithmetic of the algorithm the op runs:

  • A value the algorithm has already computed is reused, not recomputed.
  • A recurrent op — a linear attention or a state-space scan — whose signature carries a chunk size is priced as the chunked algorithm at that chunk size; one whose signature carries none is priced as its per-token recurrence.
  • An attention forward that produces a softmax-weighted output counts, per score, the QK and PV contractions (2 per multiply-add) and the softmax — scale, running max, subtract, exp, sum: 5. Each output element adds the softmax's normalizing divide.
  • A score computed by a contraction also counts every per-score epilogue the op applies: a softcap's divide, tanh and multiply; an indexer's relu, weight multiply and add into the head sum.
  • A mixture-of-experts op counts every stage it runs — routing, the expert GEMMs, the gated activation, the weighted combine — each as the op that runs that stage alone counts it. An expert that receives no rows reads no weights.
  • An operation that is the identity on the call's dtype counts 0.

1.4 Compute Roof

Op.roof_key() returns the GPU-profile key (§5.1) of the unit that prices the op's FLOPs — "cuda_core.fp32", "tensor_core.bf16", "tensor_core.fp8", ….

  • The key states the unit an optimal implementation would use, declared by the op author in code. It is never inferred from the running kernel, which would hide the gap the metric exists to expose, nor from the input dtype alone: an fp8-backend attention takes fp16/bf16 tensors.
  • The base default, fp32 CUDA cores, covers elementwise ops, reductions, norms and scans. An op whose FLOPs are matmul contractions declares a tensor-core unit of its contraction dtype, following instance state (a backend switch, a quantized path) where that decides the dtype.
  • The declaration is valid whenever eval_roofline() is, after the op's dtype is bound.
  • A wrong declaration prices the op against the wrong ceiling; the physics check (§4.3) catches it once the implied rate breaches that ceiling.

2. Field Specification

2.1 Output Contract

Per workload, the roofline field yields (flops: int, bytes: int). Consumers read these integers via op.eval_roofline() on an instantiated Op (§4.4). The compute roof is not part of the manifest field; the op declares it in code (§1.4).

2.2 Formula Modes

An entry uses one of two modes:

Mode Form When
Inline flops, optional bytes The formula is an expression.
Func func: "module.path" The formula needs Python logic.

Inline. flops and bytes are expressions in the manifest expression language (manifest.md) over the signature's indices, construction parameters and lets, plus present(t), member(t), bytes(t) and the built-in primitives.

Derived bytes. An entry omitting bytes is charged the minimum traffic of §1.2, each tensor at prod(shape) * bits(dtype) / 8. An input whose contents its requires fixes from other inputs is charged no read; its writes still count. An entry whose traffic differs writes bytes and a test for it.

Func. A module-level function f(call) -> tuple[int, int] in tileops._perf.formulas. It reads the checked call and nothing else: the facts an inline formula reads, each tensor's shape and dtype, the metadata tensors whose values decide traffic (§4.7) and, for a composite, the checked calls of its stages. It never reads the op; a fact the call lacks means the call model is incomplete.

roofline:
  flops: "2 * M * N * K"     # bytes derived from the signature
# or
roofline:
  func: "tileops._perf.formulas.gqa_dense_fwd_roofline"

3. Consumers

src/tileops/manifest/ is the source of truth for the roofline field. These modules read it:

  • Roofline analysis — reads an entry once and answers two questions: every defect it carries, and whether it can be emitted. Owns the name and form rules. Spec: §4.4.
  • Schema validator / CI — structural checks (schema, mode exclusivity, func importability), and it renders the analysis's defects. Does not execute formulas or hold a helper whitelist. Spec: §4.1.
  • Benchmark layer — instantiates an Op per workload and reads (flops, bytes) from op.eval_roofline(). Spec: §4.2.
  • Roofline tool — reads per-workload (flops, bytes), the roof key, and timing from benchmark output, prices them against the GPU profile (§5.1), and emits SOL efficiency and verdicts. Spec: §4.3.
  • Op codegen — emits the eval_roofline() method of every entry (§4.4.1) from what the analysis decided. Judges nothing. Spec: §4.4.

Two auditors check the field's values rather than consume them: the structural oracle (§4.6) and the NCU bytes audit (§4.5).

Tests and workloads are not consumers: they may supply shapes and dtypes but must not define or reinterpret roofline formulas.

4. Consumer Specifications

4.1 Schema Validator / CI

The validator checks structure: each mode has its required field (flops or func), the two modes do not mix, the fields are non-empty strings, and an implemented entry's func path resolves. Names and forms belong to the analysis (§4.4), whose defects the validator renders without keeping its own copy of the rules or the primitives. Numeric values are left to tests, which run the generated eval_roofline() on each workload.

4.2 Benchmark Layer

  • Each workload row is instantiated as manifest.md § Workloads defines, and op.eval_roofline() gives its (flops, bytes); a benchmark never computes them itself (§4.4.5).
  • Benchmark output records (flops, bytes) and the roof key from op.roof_key() (§1.4), so the roofline tool reads them without instantiating ops.

4.3 Roofline Tool

Inputs:

  • Benchmark output, carrying per-workload timing, the (flops, bytes) from op.eval_roofline(), and the roof key from op.roof_key().
  • GPU profile (§5.1), selected by matching the profile's gpu field against the measured device name; no match leaves every SOL reading blank.

Per-workload outputs: SOL efficiency, bound type, latency-bound labels, anomaly reports.

The roofline tool reads pre-computed numbers and never instantiates an Op (§4.4.5).

  • Anomaly. Efficiency above the calibrated ceiling by more than 5% means the formula or the calibration is wrong. The row is reported, not counted as fast.
  • Physics check. A row whose implied rate (bytes / time or flops / time) exceeds the theoretical ceiling of its roof is physically impossible. It is reported as a formula error and fails the run's health; this is the standing guard on overestimated formulas. Exact values are checked by the structural oracle (§4.6), reads against hardware counters by the bytes audit (§4.5).

4.4 Op Codegen

Analysis and emission run for every entry, whatever its status.

An inline entry is decided from the entry alone — no op instance, no tensor library, no device — which is what lets the validator (§4.1) ask the question wherever the manifest can be read. The validator imports a func path only for an implemented entry; emission imports it when the entry's class is created.

The analysis is the authoritative gate for name and form correctness. A formula referencing an unknown name or violating a layer's form constraints fails it, and a manifest that fails it cannot land. Numeric correctness is exercised by tests.

Analysis and emission are separate: analysis reads the entry and decides, emission writes the method from those decisions and decides nothing. Three properties follow, and each is a rule:

  • Total. Analysis accepts whatever YAML produced and never raises on it. A defect is a verdict, not an exception.
  • Lossless. A fact is absent, malformed or valid, and the three are distinguished. Collapsing the first two makes a missing dependency indistinguishable from a satisfied one.
  • Accumulating. A defect does not stop the pass. A judgment that cannot be reached for want of a fact is recorded as unreached, naming the fact.

4.4.1 Generated Method

Every manifest entry is served by a generated eval_roofline() returning (flops: int, bytes: int). The method belongs to that entry: a subclass with its own entry receives its own evaluator rather than inheriting another entry's formula. It is emitted per discriminant point, like the call checks, and evaluates over the op's last completed call. The signature is part of the shared Op interface defined in ops-design-reference.md.

4.4.2 Manifest Inputs

Codegen reads the formula mode of §2.2: an inline body folded at each point, or a call to func with the checked call.

4.4.3 Namespace

An inline formula calls only the primitive set (manifest.md § Derived Indices and Primitives); a primitive is added there and nowhere else.

4.4.4 Evaluation Timing

eval_roofline() prices Op.last_call, the last completed call, so no op can be priced before its first forward(). It recomputes each time and holds no cache, which would outlive the shapes it was computed for. A call's record never changes, and a failed call keeps the previous one. Metadata contents are read when the formula runs, so a caller pricing a call as it ran leaves them unchanged until then; a call on meta tensors holds no values, and a formula that reads them raises OpNotAvailableError.

4.4.5 Evaluator Surface Boundary

Roofline expressions live in one place at run time: the plain Python body of each op's eval_roofline(), emitted once from checked expressions. Nothing parses or evaluates a formula string at run time, and no other evaluator, op-local or manifest-level, is built.

4.5 Bytes Audit (NCU)

The bytes audit compares an op's bytes formula against DRAM counters. Its verdict covers the read side only: writes still resident in L2 when the kernel ends fall outside the profiled range, so the write side is measured and reported but never judged.

The read-side verdict rests on two premises:

  • Each kernel is replayed from cold caches, which can only inflate a multi-kernel op's reads.
  • Every conforming implementation fetches what the formula charges. A call where some input positions decide nothing breaks it: a kernel may skip those loads, while the formula charges the whole input (§4.7).

A call that breaks the second premise is configured in the audit script, not the manifest, as a when over the call and the reason. A shortfall inside the condition is EXEMPT; rows outside it are judged as usual. Review reads the reason, which must come from a measurement of the behaviour it names.

(flops, bytes) carries no read/write split, so an audited op states its read half in Op.eval_roofline_read_bytes(). Summing the input tensors is no substitute: a routed MoE reads only the experts its routing selects. An op that declares nothing gets NO-VERDICT, which is not a pass.

Verdict Meaning
FAIL Measured reads fall short of the declared read half.
WARN Measured reads far exceed it: multi-pass or replay cost.
EXEMPT They fall short inside a configured exception: reported, not judged.
SKIPPED Never run, or the formula declares no read at all.
ERROR The audit did not produce a usable measurement.
NO-VERDICT No read half was declared.

Workloads come from the manifest's own rows and cover the formula's branch signatures. Scaled-up shapes are not used: they can cross kernel-selection thresholds and audit an implementation the benchmark never runs.

4.6 Structural Oracle (tests)

A CI test recomputes each bytes value from the tensors the workload binds, by the rules of §2.2 and without reading the roofline block, and requires equality with eval_roofline(). The two share only the minimum-traffic definition, so a coefficient slip, a missed output or a broadcast counted at the wrong shape breaks the equality. Content-dependent traffic is recounted the same way: the case builds the selecting tensor itself. Coverage is golden workloads per op, not randomized sweeps.

Coverage is two levels and an implemented op sits at exactly one:

Level Case Shares with the formula
One A binder builds it from the signature, one workload row, the dtypes and the mutation marks. An op reaches this level by being recountable, not by being listed. The minimum-traffic definition, the op's statement of its output extents, and the manifest's output-dtype resolution. Never the roofline block.
Two Hand-written, for a call the contract does not settle. Written beside the case.

A completeness test keeps the two total: an op added to the manifest is recounted by the binder or fails until a hand-written case recounts it.

4.7 Value-Determined Traffic

A few ops move an amount their inputs' values decide: a routed MoE reads the experts topk_ids names, a sparse attention the blocks its selection kept. Such a formula prices this call, not an average over calls of that shape:

  • It reads the checked call's metadata tensors — the routing, the offsets, the block table — and never a quantity the op computed for itself, which would make a recount an identity.
  • A deciding value may reach the formula through a sub-op's checked call, in stages.
  • A data-dependent cost that no checked call carries is priced at its data-independent lower bound, the least the signature admits for every value. It can understate efficiency, never overstate it, so it remains the algorithm's minimum traffic (§1.2).
  • Its workload row builds those inputs from a generator of its own, not the global stream: a draw added anywhere upstream would otherwise move the traffic and the efficiency the row reports.
  • It states what decided the number in Op.roofline_data_terms(), which the benchmark records beside the reading. Nothing judges it; it is what makes a moved number readable.

Where the row states the deciding values — a packed batch's lengths — the recount restates them and stays at level one. Where the values are drawn per call, the recount runs the workload that draws them, and the op sits at level two.

5. Reference

5.1 GPU Profile

Hardware parameters are theoretical values with calibration factors from one-time microbenchmark measurements: effective = theoretical × calibration. A profile stores the two inputs, never the derived value, and is selected by matching the device name.

Every calibration is the envelope over the conditions its microbenchmark measures: the maximum, never a typical value, so readings above 100% stay reserved for formula errors. A legitimate kernel above the ceiling means the measured conditions must widen. Each condition's own fraction is kept beside the envelope.

A profile may also hold a measured latency with no datasheet value, such as the busy time one more dependent kernel launch adds. A latency is stored as the median, not an envelope: kernel selection charges it as a typical cost.

Kernel selection reads profile values only through the device facts. A device whose profile lacks a value a kernel prices a choice with keeps that kernel's unpriced default.

5.2 Benchmark–Roofline Decoupling

The benchmark records raw time and (flops, bytes) per workload; the roofline tool is a separate step that prices those records against the GPU profile. Historical data can then be re-priced when a profile changes, and the same records feed regression detection and dashboards.