drannarosen/research-workflow/performance-measurement

Claude Code and agent skill by drannarosen/research-workflow

Trust tier 3
  • community
Source check pending

Checking that the SKILL.md file is still in the repository.

Profile before optimizing; measure speedups and strong/weak scaling correctly. Use before optimizing research code or claiming it is fast or scales — measure first on a representative workload, attribute the cost, fix the dominant term, and prove the speedup against a baseline with the science unchanged; for parallel code, measure strong and weak scaling with efficiency, name the breaking point (Karp–Flatt separates serial fraction from overhead), and hold work per worker fixed for O(N²) kernel…

Install

npx vskill@latest install drannarosen/research-workflow/performance-measurement

SKILL.md

The same SKILL.md was published earlier as drannarosen/research-workflow/performance-measurement.

The bottleneck is rarely where intuition points, and "it scales" is a measurement. A performance claim needs a baseline, a correctly timed measurement, and a check that the output didn't change.

Scale the effort to the claim. A quick "is this faster?" while developing needs only a warmed, repeated timing and an output comparison. A speedup or scaling claim you will report, publish, or use to request an allocation needs the full study below, and a scaling study above the project's cost threshold is proposed to the researcher first (→ researcher-in-the-loop).

Single node: measure, then optimize

  • Baseline first: wall-clock and peak memory on a representative workload, before touching code.
  • Optimize the dominant term: by Amdahl, a 10× speedup of a 5% routine saves ~4.5% overall.

Attribute time to functions and lines with a profiler.

  • Time correctly: exclude one-time compile/JIT/cache costs with a warm-up, repeat, and report

median and spread. On GPU, block on async work before stopping the clock (block_until_ready or a host sync); otherwise you time the kernel launch, not the work.

  • One change, re-measure, compare outputs: a speedup that changes the result is a bug.
  • Stop at fast enough, and record what was tried.

Parallel: strong and weak scaling

  • Strong scaling: fixed problem, growing workers. Report speedup and efficiency (speedup ÷

workers). Efficiency always falls; report where it crosses your threshold.

  • Weak scaling: grow the problem with workers; ideal is flat time-to-solution. Hold work per

worker fixed, not particle count: for O(N²) direct summation, doubling workers needs √2 × N, not 2 × N, or you are measuring the algorithm's complexity rather than the parallel efficiency.

  • Name the wall: communication, load imbalance, memory bandwidth, or serial fraction. The

experimentally determined serial fraction (Karp–Flatt) e = (1/S − 1/p) / (1 − 1/p) separates them: constant e with growing p means a true serial fraction; e rising with p means overhead (communication, synchronization, imbalance). Don't attribute a slowdown to "overhead" without this separation.

  • Same answer at every worker count: compare against the serial or reference result; more workers

must not change the science.

  • State the regime: "efficient to 16 GPUs, 60% at 64", not an unqualified "scales". Use three or

more worker counts; two points are not a curve.

JAX: the compile boundary

JAX performance bugs live mostly at the compiler boundary: silent retracing, host-device round-trips, and unbatched dispatch. The forward result is correct; it's just paying 10× for it. Find the compile-boundary cost before reaching for hand-tuned kernels.

A JAX timing or speedup claim excludes compilation, blocks on async dispatch, and is checked against the same output. Which fixes apply depends on the workload.

  • Kill recompilation: jit retraces on new input shapes or Python-level branching. Watch for it

(a vmap or loop whose shape changes every iteration retraces every iteration), keep shapes static, mark true constants static_argnums, and use lax control flow instead of Python loops over traced values.

  • Time honestly: JAX dispatch is async; call block_until_ready() before stopping the clock, and

exclude the first (compiling) call.

  • Cut host-device transfers: avoid .item(), prints, and NumPy conversions inside hot loops (for

example, pulling a scalar to host every step just to log it); keep data on device. One sync per step destroys throughput.

  • Reuse buffers: donate_argnums for update-in-place-friendly long integrations cuts allocation

and peak memory.

  • Shard deliberately: for multi-device, use jax.jit with explicit shardings (jax.sharding.NamedSharding) or jax.shard_map (pjit is the legacy spelling of sharded jit), and verify the

partition does what you think, and that the function uses the extra devices at all, before chasing numbers.

Writing benchmark and convergence tests

Generate benchmarking and validation code for scientific-computing kernels, tailored to the function at hand. Timing loops, DataFrames, and log-log plots need no template. The parts below are the ones that are easy to get wrong: excluding compilation, blocking on async dispatch, fitting the scaling exponent, and checking convergence order rather than just a small error.

What to deliver
  1. Benchmark code tailored to the function.
  2. The expected scaling (O(n), O(n²), O(n log n), ...) or convergence order, derived from the

algorithm before running. This is the prediction the measurement is compared against.

  1. Problem sizes that span the regime of interest (sizes can't be chosen automatically; small sizes

are dominated by overhead).

  1. How to read the result, per the sections above.

Any pass/fail threshold in generated tests (the order tolerance, the 1e-6 below) is a placeholder the researcher sets, not a default (→ researcher-in-the-loop). Timings depend on hardware; record it (→ run-reproducibility).

Timing: warm up, then repeat

For NumPy, warm up once per size (caches, lazy imports), then timeit.repeat(..., number=1, repeat=n_runs) and report the spread, not a single run. For JAX, compile once outside the loop, warm up once per shape (each new shape traces and compiles), and block on async dispatch before stopping the clock:

python
import jax, jax.numpy as jnp, numpy as np, pandas as pd, timeit
def benchmark_jax_function(func, sizes, n_runs=5):
compiled_func = jax.jit(func) # compile once, outside the loop
results = []
for n in sizes:
data = jnp.array(np.random.randn(n))
_ = compiled_func(data).block_until_ready() # warm-up: trace + compile for this shape
times = []
for _ in range(n_runs):
start = timeit.default_timer()
_ = compiled_func(data).block_until_ready() # otherwise you time the launch, not the work
times.append(timeit.default_timer() - start)
results.append({'n': n, 'median_time': np.median(times), 'iqr_time': np.subtract(*np.percentile(times, [75, 25]))})
return pd.DataFrame(results)
def fit_scaling(results):
"""Fit t = a * n^b in log-log space; return (a, b)."""
b, log_a = np.polyfit(np.log10(results['n']), np.log10(results['median_time']), 1)
return 10**log_a, b

Compare the fitted b with the expected exponent, and fit only over sizes past the overhead-dominated regime. For weak-scaling sweeps, hold work per worker fixed (√2 × N per doubling for O(N²) kernels).

Convergence order

A small error at one resolution says nothing about order. Fit the observed order over the asymptotic levels only (errors above round-off, below saturation) and compare it with the theoretical order (→ numerical-method-validation, Required statement). rel_tol is the researcher's to set; ~10% is the usual starting proposal.

python
def test_convergence_order(solver, analytic, problem, expected_order, rel_tol,
resolutions=(32, 64, 128, 256), floor=None):
exact = analytic(problem)
h = np.array([1.0 / n for n in resolutions])
errors = np.array([np.max(np.abs(solver(problem, resolution=n) - exact)) for n in resolutions])
keep = errors > (floor if floor is not None else 100 * np.finfo(errors.dtype).eps)
assert keep.sum() >= 3, "need >= 3 levels above the round-off floor"
p_obs = np.polyfit(np.log(h[keep]), np.log(errors[keep]), 1)[0]
assert abs(p_obs - expected_order) <= rel_tol * expected_order, \
f"observed order {p_obs:.2f}, expected {expected_order}"
Validation against an analytic solution

Validation needs a known solution or a literature result. Example: the Plummer density profile.

python
def test_against_analytic():
def analytic_solution(r):
M, a = 1.0, 1.0
return (3*M)/(4*np.pi*a**3) * (1 + (r/a)**2)**(-2.5)
r = np.logspace(-2, 2, 100)
rel_error = np.abs(compute_density(r) - analytic_solution(r)) / analytic_solution(r)
assert np.max(rel_error) < 1e-6

Related

  • jax-code-validator — correctness of JAX tracing; the compile-boundary section here is its performance sibling.
  • numerical-method-validation — plan invariants and diagnostic plots before benchmark code exists; the theoretical order a convergence test asserts.
  • numerical-precision — float32/64 choices that trade speed against accuracy.
  • run-reproducibility — record the hardware and configuration each timing or scaling point ran on.
  • adversarial-result-check — stress-test a performance or accuracy claim before reporting it.
  • researcher-in-the-loop — a costly scaling study is proposed first; thresholds in generated tests are the researcher's.

Security

  • Security scanPassed, 90 of 100Pattern checks on the skill's files.
  • Model reviewPassed

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

7-day trend score
0

Not refreshed yet.

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/drannarosen/research-workflow/performance-measurement/badge)](https://verified-skill.com/skills/drannarosen/research-workflow/performance-measurement)

Something wrong with this skill or its page? Tell us.