pallasbench-robust / robust_eval.py
EvanOLeary's picture
Initial PallasBench Robust GPU Kernel Benchmark dataset
b95dd27
Raw
History Blame Contribute Delete
22 kB
"""Robust evaluation framework for PallasBench.
Adapts SakanaAI robust-kbench CUDA verification filters to the JAX/Pallas
kernel ecosystem and adds tiling analysis, IR capture, and hardware-aware
throughput metrics targeting A100 GPUs.
"""
from __future__ import annotations
import difflib
import inspect
import math
import re
import subprocess
import time
from dataclasses import dataclass, field, asdict
from datetime import datetime, timezone
from typing import Any, Callable, Sequence
import jax
import jax.numpy as jnp
import numpy as np
from pallasbench.utils import generate_inputs, check_correctness, time_fn
# ---------------------------------------------------------------------------
# Constants
# ---------------------------------------------------------------------------
A100_BANDWIDTH_GB_S = 2039.0
A100_SM_COUNT = 108
TRITON_BLOCK_ELEMENT_LIMIT = 1_048_576 # 1M elements
# ===================================================================
# 1. Robustness Filters (adapted from robust-kbench forward filters)
# ===================================================================
def filter_output_range(
pallas_fn: Callable,
input_shapes: Sequence[tuple[int, ...]],
num_seeds: int = 10,
dtype: str = "float32",
) -> bool:
"""Return True if ALL outputs across seeds fall within (-0.01, 0.01).
A True result is suspicious: the kernel may be producing near-zero
constant output regardless of input, indicating it ignores its inputs
or has a hardcoded return value.
"""
outputs = []
for seed in range(num_seeds):
inputs = generate_inputs(input_shapes, dtype=dtype, seed=seed)
try:
out = pallas_fn(*inputs)
jax.block_until_ready(out)
outputs.append(np.asarray(out, dtype=np.float32))
except Exception:
return False
if not outputs:
return False
stacked = np.stack(outputs)
return bool(np.all((stacked > -0.01) & (stacked < 0.01)))
def filter_output_std(
pallas_fn: Callable,
input_shapes: Sequence[tuple[int, ...]],
num_seeds: int = 10,
dtype: str = "float32",
) -> bool:
"""Return True if the per-element std across seeds is < 0.01 everywhere.
A True result is suspicious: the kernel produces nearly identical outputs
no matter which random seed generated the inputs.
"""
outputs = []
for seed in range(num_seeds):
inputs = generate_inputs(input_shapes, dtype=dtype, seed=seed)
try:
out = pallas_fn(*inputs)
jax.block_until_ready(out)
outputs.append(np.asarray(out, dtype=np.float32))
except Exception:
return False
if not outputs:
return False
stacked = np.stack(outputs)
stds = np.std(stacked, axis=0)
return bool(np.all(stds < 0.01))
def filter_output_axes(
pallas_fn: Callable,
input_shapes: Sequence[tuple[int, ...]],
num_seeds: int = 10,
dtype: str = "float32",
) -> bool:
"""Return True if the output has low variance along any axis.
Checks each axis of the stacked output tensor; if ANY axis has all
standard deviations below 0.01 that axis carries no information, which
is suspicious for a legitimate computation.
"""
outputs = []
for seed in range(num_seeds):
inputs = generate_inputs(input_shapes, dtype=dtype, seed=seed)
try:
out = pallas_fn(*inputs)
jax.block_until_ready(out)
outputs.append(np.asarray(out, dtype=np.float32))
except Exception:
return False
if not outputs:
return False
stacked = np.stack(outputs)
for axis in range(stacked.ndim):
axis_std = np.std(stacked, axis=axis)
if np.all(axis_std < 0.01):
return True
return False
def filter_input_impact(
pallas_fn: Callable,
input_shapes: Sequence[tuple[int, ...]],
num_seeds: int = 5,
dtype: str = "float32",
) -> bool:
"""Return True if different inputs produce the same output.
Runs the kernel with varying input seeds. If the per-element std
across runs is < 0.01 everywhere the kernel does not actually depend
on its inputs.
"""
outputs = []
for seed in range(num_seeds):
inputs = generate_inputs(input_shapes, dtype=dtype, seed=seed)
try:
out = pallas_fn(*inputs)
jax.block_until_ready(out)
outputs.append(np.asarray(out, dtype=np.float32))
except Exception:
return False
if not outputs:
return False
stacked = np.stack(outputs)
stds = np.std(stacked, axis=0)
return bool(np.all(stds < 0.01))
def filter_llm_sanity(kernel_source: str) -> dict[str, bool]:
"""Static-analysis heuristics for suspicious Pallas kernel source.
Returns a dict with boolean flags:
- is_redundant: source appears to hardcode outputs or ignore BlockRef
inputs entirely
- is_trivial: kernel body is trivially short or calls the JAX baseline
function directly (defeating the purpose of a custom kernel)
"""
is_redundant = False
is_trivial = False
src = kernel_source.strip()
lines = [
l.strip()
for l in src.splitlines()
if l.strip() and not l.strip().startswith("#")
]
body_lines = [
l
for l in lines
if not l.startswith("def ")
and not l.startswith("import ")
and not l.startswith("from ")
]
# Hardcoded constant stores: writing a literal scalar to the output ref
hardcoded_patterns = [
r"o_ref\[.*\]\s*=\s*[\d.]+",
r"o_ref\[.*\]\s*=\s*jnp\.(zeros|ones|full)\b",
r"output_ref\[.*\]\s*=\s*[\d.]+",
]
for pat in hardcoded_patterns:
if re.search(pat, src):
is_redundant = True
break
# Check if kernel never reads from input refs
ref_read_pattern = r"[a-zA-Z_]+_ref\[.*\]"
ref_reads = re.findall(ref_read_pattern, src)
write_refs = re.findall(r"(o_ref|out_ref|output_ref)\[", src)
if write_refs and not any(
r
for r in ref_reads
if not re.match(r"(o_ref|out_ref|output_ref)\[", r)
):
is_redundant = True
# Trivially short body (e.g. single-line pass-through)
if len(body_lines) <= 2:
is_trivial = True
# Calls baseline JAX functions internally
baseline_markers = [
"jax_baseline",
"jax.nn.relu",
"jax.nn.gelu",
"jax.nn.softmax",
"jax.nn.log_softmax",
"jnp.dot(",
"jnp.matmul(",
]
for marker in baseline_markers:
if marker in src:
is_trivial = True
break
return {"is_redundant": is_redundant, "is_trivial": is_trivial}
# ===================================================================
# 2. Tiling Analysis
# ===================================================================
def analyze_tiling(
pallas_fn: Callable,
input_shapes: Sequence[tuple[int, ...]],
dtype: str = "float32",
) -> dict[str, Any]:
"""Extract tiling metadata from a Pallas kernel via Jaxpr tracing.
Returns a dict with:
- grid: tuple of grid dimensions (or None if not extractable)
- block_shape: tuple of block dimensions (or None)
- block_elements: total elements per block
- triton_limit: the 1M element ceiling
- tiling_efficiency_pct: block_elements / triton_limit * 100
- sm_coverage: grid product vs A100 SM count
"""
result: dict[str, Any] = {
"grid": None,
"block_shape": None,
"block_elements": 0,
"triton_limit": TRITON_BLOCK_ELEMENT_LIMIT,
"tiling_efficiency_pct": 0.0,
"sm_coverage": 0.0,
}
try:
inputs = generate_inputs(input_shapes, dtype=dtype, seed=0)
abs_inputs = [jax.ShapeDtypeStruct(x.shape, x.dtype) for x in inputs]
jaxpr = jax.make_jaxpr(pallas_fn)(*abs_inputs)
jaxpr_str = str(jaxpr)
grid_match = re.search(r"grid=\(([^)]+)\)", jaxpr_str)
if grid_match:
dims = tuple(
int(x.strip())
for x in grid_match.group(1).split(",")
if x.strip()
)
result["grid"] = dims
grid_product = math.prod(dims)
result["sm_coverage"] = grid_product / A100_SM_COUNT
block_match = re.search(r"block_shape=\(([^)]+)\)", jaxpr_str)
if block_match:
bshape = tuple(
int(x.strip())
for x in block_match.group(1).split(",")
if x.strip()
)
result["block_shape"] = bshape
block_elems = math.prod(bshape)
result["block_elements"] = block_elems
result["tiling_efficiency_pct"] = (
block_elems / TRITON_BLOCK_ELEMENT_LIMIT * 100.0
)
except Exception:
pass
return result
# ===================================================================
# 3. IR Capture
# ===================================================================
def capture_jaxpr(
pallas_fn: Callable,
input_shapes: Sequence[tuple[int, ...]],
dtype: str = "float32",
) -> str:
"""Return the Jaxpr text for the given Pallas function."""
try:
inputs = generate_inputs(input_shapes, dtype=dtype, seed=0)
abs_inputs = [jax.ShapeDtypeStruct(x.shape, x.dtype) for x in inputs]
jaxpr = jax.make_jaxpr(pallas_fn)(*abs_inputs)
return str(jaxpr)
except Exception as exc:
return f"<jaxpr capture failed: {exc}>"
def capture_stablehlo(
pallas_fn: Callable,
input_shapes: Sequence[tuple[int, ...]],
dtype: str = "float32",
) -> str:
"""Return the StableHLO text for the given Pallas function."""
try:
inputs = generate_inputs(input_shapes, dtype=dtype, seed=0)
lowered = jax.jit(pallas_fn).lower(*inputs)
return lowered.as_text(dialect="stablehlo")
except Exception as exc:
return f"<stablehlo capture failed: {exc}>"
def capture_all_ir(
pallas_fn: Callable,
input_shapes: Sequence[tuple[int, ...]],
dtype: str = "float32",
) -> dict[str, Any]:
"""Capture all available IR representations.
Returns a dict with:
- jaxpr: Jaxpr text
- stablehlo: StableHLO text
- triton_ir_size_bytes: approximate byte-size of the Triton-IR
(estimated from the StableHLO text length as a proxy since
direct Triton-IR capture requires lowering through the GPU
compiler which is not always available)
"""
jaxpr_text = capture_jaxpr(pallas_fn, input_shapes, dtype=dtype)
stablehlo_text = capture_stablehlo(pallas_fn, input_shapes, dtype=dtype)
triton_ir_size = len(stablehlo_text.encode("utf-8"))
return {
"jaxpr": jaxpr_text,
"stablehlo": stablehlo_text,
"triton_ir_size_bytes": triton_ir_size,
}
# ===================================================================
# 4. Hardware Metrics Helpers
# ===================================================================
def _gpu_memory_used_mb() -> float:
"""Query current GPU memory usage via nvidia-smi."""
try:
out = subprocess.check_output(
[
"nvidia-smi",
"--query-gpu=memory.used",
"--format=csv,noheader,nounits",
],
text=True,
timeout=5,
)
return float(out.strip().splitlines()[0])
except Exception:
return 0.0
def _compute_throughput(
input_shapes: Sequence[tuple[int, ...]],
dtype: str,
kernel_time_ms: float,
) -> tuple[float, float]:
"""Return (throughput_gb_s, hw_bw_util_pct) for read+write traffic."""
bytes_per_elem = jnp.dtype(dtype).itemsize
total_elements = sum(math.prod(s) for s in input_shapes)
# Assume read all inputs + write one output the size of the first input
read_bytes = total_elements * bytes_per_elem
write_bytes = math.prod(input_shapes[0]) * bytes_per_elem
total_bytes = read_bytes + write_bytes
if kernel_time_ms <= 0:
return 0.0, 0.0
throughput_gb_s = (total_bytes / 1e9) / (kernel_time_ms / 1e3)
hw_bw_util_pct = (throughput_gb_s / A100_BANDWIDTH_GB_S) * 100.0
return throughput_gb_s, hw_bw_util_pct
# ===================================================================
# 5. RobustPallasResult
# ===================================================================
@dataclass
class RobustPallasResult:
"""Complete evaluation record for a single PallasBench kernel."""
# Identity
task_name: str = ""
level: int = 0
category: str = ""
input_shapes: list[tuple[int, ...]] = field(default_factory=list)
dtype: str = "float32"
# Correctness
correct: bool = False
errors: list[str] = field(default_factory=list)
multi_seed_correct: bool = False
multi_dtype_correct: bool = False
# Performance
baseline_time_ms: float = 0.0
kernel_time_ms: float = 0.0
speedup: float = 0.0
# Hardware metrics
throughput_gb_s: float = 0.0
hw_bw_util_pct: float = 0.0
gpu_mem_delta_mb: float = 0.0
# Robustness filters
filter_output_range: bool = False
filter_output_std: bool = False
filter_output_axes: bool = False
filter_input_impact: bool = False
filter_llm_sanity: dict[str, bool] = field(default_factory=dict)
# Tiling
grid_dims: tuple | None = None
block_shape: tuple | None = None
block_elements: int = 0
tiling_efficiency: float = 0.0
# IR
jaxpr: str = ""
stablehlo: str = ""
# Source tracking
original_source: str = ""
fixed_source: str = ""
diff: str = ""
# Metadata
timestamp: str = ""
def to_dict(self) -> dict[str, Any]:
"""Serialize to a plain dictionary."""
return asdict(self)
@property
def is_robust(self) -> bool:
"""True when the kernel passes all robustness filters."""
sanity = self.filter_llm_sanity or {}
return (
self.correct
and not self.filter_output_range
and not self.filter_output_std
and not self.filter_output_axes
and not self.filter_input_impact
and not sanity.get("is_redundant", False)
and not sanity.get("is_trivial", False)
)
@property
def summary_line(self) -> str:
"""One-line human-readable status string."""
status = "ROBUST" if self.is_robust else "FLAGGED"
return (
f"[{status}] {self.task_name}: "
f"correct={self.correct} speedup={self.speedup:.2f}x "
f"throughput={self.throughput_gb_s:.1f} GB/s "
f"bw_util={self.hw_bw_util_pct:.1f}%"
)
# ===================================================================
# 6. Main Evaluation Entry Point
# ===================================================================
def _check_multi_seed(
pallas_fn: Callable,
baseline_fn: Callable,
input_shapes: Sequence[tuple[int, ...]],
dtype: str,
n_seeds: int = 10,
atol: float = 1e-3,
rtol: float = 1e-3,
) -> bool:
"""Correctness check across many random seeds."""
for seed in range(n_seeds):
inputs = generate_inputs(input_shapes, dtype=dtype, seed=seed)
try:
out_k = pallas_fn(*inputs)
out_b = baseline_fn(*inputs)
jax.block_until_ready(out_k)
jax.block_until_ready(out_b)
if out_k.shape != out_b.shape:
return False
if not jnp.allclose(out_k, out_b, atol=atol, rtol=rtol):
return False
except Exception:
return False
return True
def _check_multi_dtype(
pallas_fn: Callable,
baseline_fn: Callable,
input_shapes: Sequence[tuple[int, ...]],
dtypes_to_test: Sequence[str] = ("float32", "float16", "bfloat16"),
atol: float = 1e-2,
rtol: float = 1e-2,
) -> bool:
"""Correctness check across multiple dtypes."""
for dt in dtypes_to_test:
try:
inputs = generate_inputs(input_shapes, dtype=dt, seed=0)
out_k = pallas_fn(*inputs)
out_b = baseline_fn(*inputs)
jax.block_until_ready(out_k)
jax.block_until_ready(out_b)
if out_k.shape != out_b.shape:
return False
out_k_f32 = out_k.astype(jnp.float32)
out_b_f32 = out_b.astype(jnp.float32)
if not jnp.allclose(out_k_f32, out_b_f32, atol=atol, rtol=rtol):
return False
except Exception:
return False
return True
def _compute_diff(original: str, fixed: str) -> str:
"""Unified diff between original and fixed source."""
if not original and not fixed:
return ""
orig_lines = original.splitlines(keepends=True)
fixed_lines = fixed.splitlines(keepends=True)
return "".join(
difflib.unified_diff(
orig_lines,
fixed_lines,
fromfile="original",
tofile="fixed",
)
)
def evaluate_kernel_robust(
pallas_fn: Callable,
baseline_fn: Callable,
input_shapes: Sequence[tuple[int, ...]],
task_name: str = "unnamed",
level: int = 0,
category: str = "",
dtype: str = "float32",
n_correctness: int = 5,
n_warmup: int = 10,
n_trials: int = 100,
atol: float = 1e-3,
rtol: float = 1e-3,
filter_seeds: int = 10,
original_source: str = "",
fixed_source: str = "",
) -> RobustPallasResult:
"""Run the full robust evaluation pipeline for a single Pallas kernel.
This is the main entry point that orchestrates:
1. Standard correctness and timing from PallasBench
2. Multi-seed and multi-dtype correctness
3. All four robustness filters (range, std, axes, input_impact)
4. Static LLM sanity analysis on kernel source
5. Tiling analysis via Jaxpr inspection
6. IR capture (Jaxpr + StableHLO)
7. Hardware throughput and memory delta
8. Source diff tracking
"""
result = RobustPallasResult(
task_name=task_name,
level=level,
category=category,
input_shapes=list(input_shapes),
dtype=dtype,
timestamp=datetime.now(timezone.utc).isoformat(),
)
# --- Correctness -------------------------------------------------------
correct, errors = check_correctness(
pallas_fn=pallas_fn,
baseline_fn=baseline_fn,
input_shapes=input_shapes,
dtype=dtype,
n_checks=n_correctness,
atol=atol,
rtol=rtol,
)
result.correct = correct
result.errors = errors
result.multi_seed_correct = _check_multi_seed(
pallas_fn,
baseline_fn,
input_shapes,
dtype,
n_seeds=filter_seeds,
atol=atol,
rtol=rtol,
)
result.multi_dtype_correct = _check_multi_dtype(
pallas_fn,
baseline_fn,
input_shapes,
)
# --- Timing ------------------------------------------------------------
inputs = generate_inputs(input_shapes, dtype=dtype, seed=42)
result.baseline_time_ms = time_fn(
baseline_fn,
inputs,
n_warmup=n_warmup,
n_trials=n_trials,
)
result.kernel_time_ms = time_fn(
pallas_fn,
inputs,
n_warmup=n_warmup,
n_trials=n_trials,
)
result.speedup = (
result.baseline_time_ms / result.kernel_time_ms
if result.kernel_time_ms > 0
else 0.0
)
# --- Hardware metrics --------------------------------------------------
mem_before = _gpu_memory_used_mb()
warmup_out = pallas_fn(*inputs)
jax.block_until_ready(warmup_out)
mem_after = _gpu_memory_used_mb()
result.gpu_mem_delta_mb = mem_after - mem_before
tp, bw = _compute_throughput(input_shapes, dtype, result.kernel_time_ms)
result.throughput_gb_s = tp
result.hw_bw_util_pct = bw
# --- Robustness filters ------------------------------------------------
result.filter_output_range = filter_output_range(
pallas_fn,
input_shapes,
num_seeds=filter_seeds,
dtype=dtype,
)
result.filter_output_std = filter_output_std(
pallas_fn,
input_shapes,
num_seeds=filter_seeds,
dtype=dtype,
)
result.filter_output_axes = filter_output_axes(
pallas_fn,
input_shapes,
num_seeds=filter_seeds,
dtype=dtype,
)
result.filter_input_impact = filter_input_impact(
pallas_fn,
input_shapes,
num_seeds=min(filter_seeds, 5),
dtype=dtype,
)
# Source-level sanity (use fixed_source if available, else try inspect)
source_text = fixed_source or original_source
if not source_text:
try:
source_text = inspect.getsource(pallas_fn)
except (TypeError, OSError):
source_text = ""
result.filter_llm_sanity = (
filter_llm_sanity(source_text) if source_text else {}
)
# --- Tiling analysis ---------------------------------------------------
tiling = analyze_tiling(pallas_fn, input_shapes, dtype=dtype)
result.grid_dims = tiling["grid"]
result.block_shape = tiling["block_shape"]
result.block_elements = tiling["block_elements"]
result.tiling_efficiency = tiling["tiling_efficiency_pct"]
# --- IR capture --------------------------------------------------------
result.jaxpr = capture_jaxpr(pallas_fn, input_shapes, dtype=dtype)
result.stablehlo = capture_stablehlo(pallas_fn, input_shapes, dtype=dtype)
# --- Source tracking ---------------------------------------------------
result.original_source = original_source
result.fixed_source = fixed_source
result.diff = _compute_diff(original_source, fixed_source)
return result