roofline · FLOPs · tensor traffic

Find out why your model is slower than the hardware allows.

neural-cost estimates a network's useful compute and compulsory memory traffic, measures its runtime, and splits the gap to the roofline bound into physical causes. PyTorch, JAX and TensorFlow are optional adapters; the core has zero dependencies.

$ pip install neural-cost
Python 3.11+MIT licensedCPU · CUDA · Apple MPS
profile_mlp.py
from neural_cost import analyze_gap, detect_hardware, estimate_operations
from neural_cost.adapters import TorchAdapter

adapter = TorchAdapter(use_profiler=False)
ops = adapter.operations(model, (x,))
measurement = adapter.benchmark(model, x, repeats=20)
hardware, _ = detect_hardware(device="cpu")

print(analyze_gap(estimate_operations(ops), measurement, hardware).render())
Neural cost gap analysis
  bound: 0.680 ms (compute 0.435 ms, memory 0.680 ms)
  observed: 1.270 ms
  roofline efficiency: 53.5% (memory-bound)
  achieved: 237.834 GFLOP/s, 15.651 GB/s
  next: Memory-bound: consider fusion, reduced precision,
        or fewer materialized tensors.
768→3072→768 MLP, batch 32, Apple M3 CPU, 20 timed runs. Coverage: both Linear layers captured; the GELU between them is not modeled, so the bound slightly understates the work.

Explain the gap, not just its size

A 4% roofline efficiency tells you a workload is slow. It doesn't tell you why.

neural-cost goes further in three ways.

Cross-framework consistency

A PyTorch hook sees one attention op; a JAX trace sees the dot_general, exp and reduce_sum that implement it. cross_check separates granularity-invariant dense FLOPs and unique parameters, and the test suite asserts they match exactly across all three frameworks.

How it's tested

Gap attribution

attribute_gap splits measured runtime into ordered, non-overlapping components that sum exactly to the median: roofline floor, unfused traffic, lost overlap, peak derate, dispatch, kernel inefficiency, jitter and residual.

See the components

Published validation

Three predictors, none fit to the workload it predicts, scored out-of-sample on 95 workloads. The roofline is checked as a true lower bound: any measurement faster than it would falsify the model.

View results

Gap attribution

Every millisecond, accounted for.

Calibration measures throughput as a function of size, from 32² to 4096² matmuls and from cache-resident to DRAM-sized copies, so small kernels are modeled at the rate they actually reach. On async devices only the un-hidden part of launch overhead is charged.

attribute.py
calibration = adapter.calibrate("mps")
kernels = adapter.trace_kernels(model, inputs)

attribution = attribute_gap(
    ops, measurement, hardware, calibration,
    kernel_count=len(kernels),
    isolated_seconds=adapter.replay(ops, "mps"),
    assume_fusion=False,
)
print(attribution.render())
for step in attribution.recommendations():
    print(step)
  1. 01roofline_floor

    FLOPs and fused bytes at datasheet peak with perfect overlap. Nothing can run faster.

  2. 02unfused_traffic

    Extra DRAM round-trips for intermediates a fusing compiler would keep on chip.

  3. 03serialization

    Lost compute/memory overlap: each op bounded by its own roofline.

  4. 04peak_derate

    Datasheet peak vs. measured achievable throughput at each op's size.

  5. 05dispatch

    Per-kernel launch overhead not hidden by async execution, plus per-call sync.

  6. 06kernel_inefficiency

    How much slower each op runs alone than its achievable roofline (op replay).

  7. 07timing_jitter

    Median minus fastest sample.

  8. 08residual

    Composition effects: framework glue, uncaptured ops, cache interference.

Published validation

Out-of-sample error, on real hardware.

The validation benchmark suite runs a grid of MLP, CNN, LSTM and Transformer workloads on every installed backend and scores three predictors: zero-shot (microbenchmark calibration only), op-replay (each op timed alone, then composed) and a leave-one-out 4-parameter fit.

0 / 95lower-bound violations
95workloads, 5 backends
0.89–0.995Spearman ρ, workload ranking
2–22%median error, best predictor
Apple M3. Mean absolute percentage error, median in parentheses. Best predictor per backend in bold.
BackendBound violationsZero-shot MAPEOp-replay MAPELOO fit MAPERank corr.
PyTorch eager, CPU0 / 2363% (68%)25% (18%)51% (52%)0.987
PyTorch eager, MPS0 / 2329% (20%)29% (14%)21% (12%)0.936
JAX jit, CPU0 / 1363% (76%)n/a5% (2%)0.995
JAX jit, MPS0 / 1326% (20%)n/a21% (16%)0.951
TensorFlow graph, CPU0 / 23n/an/a22% (22%)0.954

Most of the remaining error is eager-LSTM decomposition and composition effects that only appear when ops run together, which is what the residual component isolates. Every per-workload number is in VALIDATION_REPORT.md. Run it on your own hardware with python benchmarks/run.py --suites validation.

Frameworks

Bring your own framework. Or none.

The core works on portable Operation records and has no mandatory dependencies. Adapters are optional extras that emit the right operation kind for each layer.

torch

PyTorch

Eager hooks and FX tracing. Linear, Conv2d, Embedding, RNN/GRU/LSTM, MultiheadAttention, norms. Kernel tracing and op replay for attribution.

pip install "neural-cost[torch]"
jax

JAX

jaxpr tracing that recurses into jit, scan, while, cond and custom_jvp, with arbitrary dot_general contractions and NHWC convolutions.

pip install "neural-cost[jax]"
tensorflow

TensorFlow / Keras

Dense, Conv2D, Embedding, GRU/LSTM, MultiHeadAttention, BatchNormalization, LayerNormalization and pooling layers.

pip install "neural-cost[tensorflow]"

Adapter guide · Hardware detection. On Apple Silicon, JAX runs on the GPU through neural-cost[jax-metal] (Apple's Metal plugin) or neural-cost[jax-mps] (community plugin via MLX). Hardware is detected from a chip table, a STREAM triad, nvidia-smi, or a CPU fallback.

LLM serving models

Analytical models for modern inference.

Closed-form cost models for the techniques that dominate LLM serving, each with a gap analysis against your hardware. See LLM serving models and distributed training.

Mixture-of-Experts

Top-k routing, expected loaded experts and memory thrashing at small batch.

Speculative decoding

Breakeven acceptance rate α*, including per-position acceptance profiles.

PagedAttention

Block allocation, fragmentation, prefix sharing and concurrency gain.

Continuous batching

Mixed decode and chunked-prefill iterations and optimal chunk size.

State space models

Mamba / S6 / SSD scans and linear attention.

Training memory

Parameters, gradients, optimizer state and activation bounds.

AI agent skill

Teach your coding agent to profile models.

neural-cost ships an agent skill covering when to use it, which extra to install, per-framework recipes and how to report results. It's bundled with the package, so it always matches the installed API. In Claude Code you can also add it as a plugin. Agent skill docs.

terminal
# Claude Code
neural-cost skill --install ~/.claude/skills

# Any agent that reads AGENTS.md
neural-cost skill --agents-md >> AGENTS.md