From 15d69922663290230df83f7cb88e1baaa6b04aa5 Mon Sep 17 00:00:00 2001 From: Mark Saroufim Date: Mon, 30 Nov 2026 20:26:40 -0800 Subject: [PATCH 1/2] Start fresh PMPP v3 leaderboards with hardened evaluations --- .github/workflows/pmpp-v2-checkers.yml | 8 +- README.md | 2 +- problems/pmpp_v2.yaml | 20 +- problems/pmpp_v3.yaml | 71 ++++ problems/pmpp_v3/README.md | 19 + problems/pmpp_v3/conv2d_py/reference.py | 66 +++ .../conv2d_py/solutions/correct/ref.py | 10 + .../conv2d_py/solutions/wrong/empty.py | 7 + problems/pmpp_v3/conv2d_py/submission.py | 17 + problems/pmpp_v3/conv2d_py/task.py | 13 + problems/pmpp_v3/conv2d_py/task.yml | 50 +++ problems/pmpp_v3/eval.py | 375 ++++++++++++++++++ problems/pmpp_v3/grayscale_py/reference.py | 44 ++ .../grayscale_py/solutions/correct/ref.py | 11 + .../grayscale_py/solutions/wrong/empty.py | 8 + problems/pmpp_v3/grayscale_py/submission.py | 10 + problems/pmpp_v3/grayscale_py/task.py | 14 + problems/pmpp_v3/grayscale_py/task.yml | 44 ++ problems/pmpp_v3/histogram_py/reference.py | 56 +++ .../histogram_py/solutions/correct/ref.py | 8 + .../histogram_py/solutions/wrong/empty.py | 7 + problems/pmpp_v3/histogram_py/submission.py | 16 + problems/pmpp_v3/histogram_py/task.py | 11 + problems/pmpp_v3/histogram_py/task.yml | 49 +++ problems/pmpp_v3/matmul_py/reference.py | 23 ++ .../matmul_py/solutions/correct/ref.py | 8 + .../solutions/wrong/low-precision.py | 8 + problems/pmpp_v3/matmul_py/submission.py | 6 + problems/pmpp_v3/matmul_py/task.py | 11 + problems/pmpp_v3/matmul_py/task.yml | 47 +++ problems/pmpp_v3/prefixsum_py/reference.py | 58 +++ .../prefixsum_py/solutions/correct/ref.py | 8 + .../prefixsum_py/solutions/wrong/empty.py | 7 + problems/pmpp_v3/prefixsum_py/submission.py | 15 + problems/pmpp_v3/prefixsum_py/task.py | 12 + problems/pmpp_v3/prefixsum_py/task.yml | 66 +++ problems/pmpp_v3/sort_py/reference.py | 61 +++ .../pmpp_v3/sort_py/solutions/correct/ref.py | 11 + .../pmpp_v3/sort_py/solutions/wrong/empty.py | 7 + problems/pmpp_v3/sort_py/submission.py | 18 + problems/pmpp_v3/sort_py/task.py | 12 + problems/pmpp_v3/sort_py/task.yml | 55 +++ problems/pmpp_v3/template.py | 5 + problems/pmpp_v3/utils.py | 212 ++++++++++ problems/pmpp_v3/vectoradd_py/reference.py | 38 ++ .../correct/submission_cuda_inline.py | 84 ++++ .../solutions/correct/submission_mojo.py | 109 +++++ .../solutions/correct/submission_triton.py | 38 ++ problems/pmpp_v3/vectoradd_py/submission.py | 7 + problems/pmpp_v3/vectoradd_py/task.py | 11 + problems/pmpp_v3/vectoradd_py/task.yml | 44 ++ problems/pmpp_v3/vectorsum_py/reference.py | 55 +++ .../vectorsum_py/solutions/correct/pytorch.py | 12 + .../vectorsum_py/solutions/wrong/cheat.py | 16 + problems/pmpp_v3/vectorsum_py/submission.py | 62 +++ problems/pmpp_v3/vectorsum_py/task.py | 9 + problems/pmpp_v3/vectorsum_py/task.yml | 44 ++ tests/pmpp_v2/conftest.py | 13 +- tests/pmpp_v2/test_checkers.py | 8 +- 59 files changed, 2117 insertions(+), 19 deletions(-) create mode 100644 problems/pmpp_v3.yaml create mode 100644 problems/pmpp_v3/README.md create mode 100644 problems/pmpp_v3/conv2d_py/reference.py create mode 100644 problems/pmpp_v3/conv2d_py/solutions/correct/ref.py create mode 100644 problems/pmpp_v3/conv2d_py/solutions/wrong/empty.py create mode 100644 problems/pmpp_v3/conv2d_py/submission.py create mode 100644 problems/pmpp_v3/conv2d_py/task.py create mode 100644 problems/pmpp_v3/conv2d_py/task.yml create mode 100644 problems/pmpp_v3/eval.py create mode 100644 problems/pmpp_v3/grayscale_py/reference.py create mode 100644 problems/pmpp_v3/grayscale_py/solutions/correct/ref.py create mode 100644 problems/pmpp_v3/grayscale_py/solutions/wrong/empty.py create mode 100644 problems/pmpp_v3/grayscale_py/submission.py create mode 100644 problems/pmpp_v3/grayscale_py/task.py create mode 100644 problems/pmpp_v3/grayscale_py/task.yml create mode 100644 problems/pmpp_v3/histogram_py/reference.py create mode 100644 problems/pmpp_v3/histogram_py/solutions/correct/ref.py create mode 100644 problems/pmpp_v3/histogram_py/solutions/wrong/empty.py create mode 100644 problems/pmpp_v3/histogram_py/submission.py create mode 100644 problems/pmpp_v3/histogram_py/task.py create mode 100644 problems/pmpp_v3/histogram_py/task.yml create mode 100644 problems/pmpp_v3/matmul_py/reference.py create mode 100644 problems/pmpp_v3/matmul_py/solutions/correct/ref.py create mode 100644 problems/pmpp_v3/matmul_py/solutions/wrong/low-precision.py create mode 100644 problems/pmpp_v3/matmul_py/submission.py create mode 100644 problems/pmpp_v3/matmul_py/task.py create mode 100644 problems/pmpp_v3/matmul_py/task.yml create mode 100644 problems/pmpp_v3/prefixsum_py/reference.py create mode 100644 problems/pmpp_v3/prefixsum_py/solutions/correct/ref.py create mode 100644 problems/pmpp_v3/prefixsum_py/solutions/wrong/empty.py create mode 100644 problems/pmpp_v3/prefixsum_py/submission.py create mode 100644 problems/pmpp_v3/prefixsum_py/task.py create mode 100644 problems/pmpp_v3/prefixsum_py/task.yml create mode 100644 problems/pmpp_v3/sort_py/reference.py create mode 100644 problems/pmpp_v3/sort_py/solutions/correct/ref.py create mode 100644 problems/pmpp_v3/sort_py/solutions/wrong/empty.py create mode 100644 problems/pmpp_v3/sort_py/submission.py create mode 100644 problems/pmpp_v3/sort_py/task.py create mode 100644 problems/pmpp_v3/sort_py/task.yml create mode 100644 problems/pmpp_v3/template.py create mode 100644 problems/pmpp_v3/utils.py create mode 100644 problems/pmpp_v3/vectoradd_py/reference.py create mode 100644 problems/pmpp_v3/vectoradd_py/solutions/correct/submission_cuda_inline.py create mode 100644 problems/pmpp_v3/vectoradd_py/solutions/correct/submission_mojo.py create mode 100644 problems/pmpp_v3/vectoradd_py/solutions/correct/submission_triton.py create mode 100644 problems/pmpp_v3/vectoradd_py/submission.py create mode 100644 problems/pmpp_v3/vectoradd_py/task.py create mode 100644 problems/pmpp_v3/vectoradd_py/task.yml create mode 100644 problems/pmpp_v3/vectorsum_py/reference.py create mode 100644 problems/pmpp_v3/vectorsum_py/solutions/correct/pytorch.py create mode 100644 problems/pmpp_v3/vectorsum_py/solutions/wrong/cheat.py create mode 100644 problems/pmpp_v3/vectorsum_py/submission.py create mode 100644 problems/pmpp_v3/vectorsum_py/task.py create mode 100644 problems/pmpp_v3/vectorsum_py/task.yml diff --git a/.github/workflows/pmpp-v2-checkers.yml b/.github/workflows/pmpp-v2-checkers.yml index b965164bf..c53627903 100644 --- a/.github/workflows/pmpp-v2-checkers.yml +++ b/.github/workflows/pmpp-v2-checkers.yml @@ -1,15 +1,21 @@ -name: PMPP v2 checker regression tests +name: PMPP v2 and v3 checker regression tests on: pull_request: paths: - "problems/pmpp_v2/**" + - "problems/pmpp_v3/**" + - "problems/pmpp_v2.yaml" + - "problems/pmpp_v3.yaml" - "tests/pmpp_v2/**" - ".github/workflows/pmpp-v2-checkers.yml" push: branches: [main] paths: - "problems/pmpp_v2/**" + - "problems/pmpp_v3/**" + - "problems/pmpp_v2.yaml" + - "problems/pmpp_v3.yaml" - "tests/pmpp_v2/**" - ".github/workflows/pmpp-v2-checkers.yml" diff --git a/README.md b/README.md index 7557c8cd4..a51761a33 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ This repo holds reference kernels for the KernelBot which hosts regular competit You can see what's going on [gpumode.com](https://www.gpumode.com/) ## Competitions -1. [PMPP practice problems](https://github.com/gpu-mode/reference-kernels/tree/main/problems/pmpp_v2) +1. [PMPP v3 practice problems](problems/pmpp_v3) ([v2 archive](problems/pmpp_v2)) 2. [AMD $100K kernel competition](problems/amd) 3. [BioML kernels](problems/bioml) 4. [AMD $100K distributed kernel competition](problems/amd_distributed) diff --git a/problems/pmpp_v2.yaml b/problems/pmpp_v2.yaml index 3bdf6777e..970191361 100644 --- a/problems/pmpp_v2.yaml +++ b/problems/pmpp_v2.yaml @@ -1,13 +1,13 @@ name: pmpp_v2 Practice Problems # when does this end (individual problems might close earlier) -deadline: "" +deadline: "2026-12-01T04:21:18Z" # A description for this particular competition description: "" # the list of problems problems: - directory: pmpp_v2/conv2d_py name: conv2d_v2 - deadline: "2100-12-31" + deadline: "2026-12-01T04:21:18Z" gpus: - B200 - H100 @@ -15,7 +15,7 @@ problems: - L4 - directory: pmpp_v2/grayscale_py name: grayscale_v2 - deadline: "2100-12-31" + deadline: "2026-12-01T04:21:18Z" gpus: - B200 - H100 @@ -23,7 +23,7 @@ problems: - L4 - directory: pmpp_v2/histogram_py name: histogram_v2 - deadline: "2100-12-31" + deadline: "2026-12-01T04:21:18Z" gpus: - B200 - H100 @@ -31,7 +31,7 @@ problems: - L4 - directory: pmpp_v2/matmul_py name: matmul_v2 - deadline: "2100-12-31" + deadline: "2026-12-01T04:21:18Z" gpus: - B200 - H100 @@ -39,7 +39,7 @@ problems: - L4 - directory: pmpp_v2/prefixsum_py name: prefixsum_v2 - deadline: "2100-12-31" + deadline: "2026-12-01T04:21:18Z" gpus: - B200 - H100 @@ -47,7 +47,7 @@ problems: - L4 - directory: pmpp_v2/sort_py name: sort_v2 - deadline: "2100-12-31" + deadline: "2026-12-01T04:21:18Z" gpus: - B200 - H100 @@ -55,7 +55,7 @@ problems: - L4 - directory: pmpp_v2/vectoradd_py name: vectoradd_v2 - deadline: "2100-12-31" + deadline: "2026-12-01T04:21:18Z" gpus: - B200 - H100 @@ -63,9 +63,9 @@ problems: - L4 - directory: pmpp_v2/vectorsum_py name: vectorsum_v2 - deadline: "2100-12-31" + deadline: "2026-12-01T04:21:18Z" gpus: - B200 - H100 - A100 - - L4 \ No newline at end of file + - L4 diff --git a/problems/pmpp_v3.yaml b/problems/pmpp_v3.yaml new file mode 100644 index 000000000..38c671d09 --- /dev/null +++ b/problems/pmpp_v3.yaml @@ -0,0 +1,71 @@ +name: pmpp_v3 Practice Problems +# when does this end (individual problems might close earlier) +deadline: "" +# A description for this particular competition +description: "" +# the list of problems +problems: + - directory: pmpp_v3/conv2d_py + name: conv2d_v3 + deadline: "2100-12-31" + gpus: + - B200 + - H100 + - A100 + - L4 + - directory: pmpp_v3/grayscale_py + name: grayscale_v3 + deadline: "2100-12-31" + gpus: + - B200 + - H100 + - A100 + - L4 + - directory: pmpp_v3/histogram_py + name: histogram_v3 + deadline: "2100-12-31" + gpus: + - B200 + - H100 + - A100 + - L4 + - directory: pmpp_v3/matmul_py + name: matmul_v3 + deadline: "2100-12-31" + gpus: + - B200 + - H100 + - A100 + - L4 + - directory: pmpp_v3/prefixsum_py + name: prefixsum_v3 + deadline: "2100-12-31" + gpus: + - B200 + - H100 + - A100 + - L4 + - directory: pmpp_v3/sort_py + name: sort_v3 + deadline: "2100-12-31" + gpus: + - B200 + - H100 + - A100 + - L4 + - directory: pmpp_v3/vectoradd_py + name: vectoradd_v3 + deadline: "2100-12-31" + gpus: + - B200 + - H100 + - A100 + - L4 + - directory: pmpp_v3/vectorsum_py + name: vectorsum_v3 + deadline: "2100-12-31" + gpus: + - B200 + - H100 + - A100 + - L4 diff --git a/problems/pmpp_v3/README.md b/problems/pmpp_v3/README.md new file mode 100644 index 000000000..07498d4ed --- /dev/null +++ b/problems/pmpp_v3/README.md @@ -0,0 +1,19 @@ +# PMPP v3 practice problems + +PMPP v3 starts eight fresh leaderboards with the current hardened evaluations +from reference-kernels commit `4c06b025c9193d80f6748e3139d6e5e17423ad7a`. +The v2 leaderboard results remain available as an archive. + +Use the names in [pmpp_v3.yaml](../pmpp_v3.yaml): `conv2d_v3`, `grayscale_v3`, +`histogram_v3`, `matmul_v3`, `prefixsum_v3`, `sort_v3`, `vectoradd_v3`, and +`vectorsum_v3`. All eight support B200, H100, A100, and L4. + +```sh +popcorn submit --leaderboard grayscale_v3 --gpu B200 --mode leaderboard submission.py +``` + +The checks require plain, materialized tensors with the expected shape, dtype, +device, and finite values. Sorting checks the exact sorted input; prefix sum uses +a tolerance based on input magnitude. Ranked runs regenerate inputs and check +every timed output. V3 preserves those checks, test cases, and benchmark shapes +in an independent directory so later changes can be versioned separately. diff --git a/problems/pmpp_v3/conv2d_py/reference.py b/problems/pmpp_v3/conv2d_py/reference.py new file mode 100644 index 000000000..0f8cb10f5 --- /dev/null +++ b/problems/pmpp_v3/conv2d_py/reference.py @@ -0,0 +1,66 @@ +from utils import make_match_reference, DeterministicContext +import torch +import torch.nn.functional as F +from task import input_t, output_t + + +def ref_kernel(data: input_t) -> output_t: + """ + Reference implementation of 2D convolution using PyTorch. + Args: + data: Tuple of (input tensor, kernel tensor) + Returns: + Output tensor after convolution + """ + with DeterministicContext(): + input_tensor, kernel, output = data + return F.conv2d( + input_tensor, + kernel, + # No padding and no striding + stride=1, + padding=0, + ) + + +def generate_input( + size: int, kernelsize: int, channels: int, batch: int, seed: int +) -> input_t: + """ + Generates random input and kernel tensors. + Returns: + Tuple of (input tensor, kernel tensor) + """ + gen = torch.Generator(device="cuda") + gen.manual_seed(seed) + + # Generate input tensor: [batch, in_channels, height, width] + input_tensor = torch.randn( + batch, channels, size, size, device="cuda", dtype=torch.float32, generator=gen + ).contiguous() + + # Generate kernel tensor: [out_channels, in_channels, kernel_height, kernel_width] + # Here we use same number of output channels as input channels for simplicity + kernel = torch.randn( + channels, + channels, + kernelsize, + kernelsize, + device="cuda", + dtype=torch.float32, + generator=gen, + ).contiguous() + + output_tensor = torch.empty( + batch, + channels, + size - kernelsize + 1, + size - kernelsize + 1, + device="cuda", + dtype=torch.float32, + ) + + return input_tensor, kernel, output_tensor + + +check_implementation = make_match_reference(ref_kernel, rtol=1e-3, atol=1e-3) diff --git a/problems/pmpp_v3/conv2d_py/solutions/correct/ref.py b/problems/pmpp_v3/conv2d_py/solutions/correct/ref.py new file mode 100644 index 000000000..b1b9daa90 --- /dev/null +++ b/problems/pmpp_v3/conv2d_py/solutions/correct/ref.py @@ -0,0 +1,10 @@ +from task import input_t, output_t +from utils import DeterministicContext +import torch.nn.functional as F + + +def custom_kernel(data: input_t) -> output_t: + input_tensor, kernel, output = data + with DeterministicContext(): + output[...] = F.conv2d(input_tensor, kernel, stride=1, padding=0) + return output diff --git a/problems/pmpp_v3/conv2d_py/solutions/wrong/empty.py b/problems/pmpp_v3/conv2d_py/solutions/wrong/empty.py new file mode 100644 index 000000000..7e6cef7cf --- /dev/null +++ b/problems/pmpp_v3/conv2d_py/solutions/wrong/empty.py @@ -0,0 +1,7 @@ +# the nop kernel +from task import input_t, output_t + + +def custom_kernel(data: input_t) -> output_t: + _, _, output = data + return output diff --git a/problems/pmpp_v3/conv2d_py/submission.py b/problems/pmpp_v3/conv2d_py/submission.py new file mode 100644 index 000000000..4f1efb4ce --- /dev/null +++ b/problems/pmpp_v3/conv2d_py/submission.py @@ -0,0 +1,17 @@ +from task import input_t, output_t +import torch +import torch.nn.functional as F + + +def custom_kernel(data: input_t) -> output_t: + """ + Implementation of 2D convolution using PyTorch with no padding and no striding. + Args: + data: Tuple of (input tensor, kernel tensor) + spec: Convolution specifications + Returns: + Output tensor after convolution + """ + input_tensor, kernel, output = data + output[...] = F.conv2d(input_tensor, kernel, stride=1, padding=0) + return output diff --git a/problems/pmpp_v3/conv2d_py/task.py b/problems/pmpp_v3/conv2d_py/task.py new file mode 100644 index 000000000..dc0b7710e --- /dev/null +++ b/problems/pmpp_v3/conv2d_py/task.py @@ -0,0 +1,13 @@ +from typing import TypedDict, TypeVar, Tuple +import torch + +input_t = TypeVar("input_t", bound=Tuple[torch.Tensor, torch.Tensor, torch.Tensor]) +output_t = TypeVar("output_t", bound=torch.Tensor) + + +class TestSpec(TypedDict): + size: int + kernelsize: int + channels: int + batch: int + seed: int diff --git a/problems/pmpp_v3/conv2d_py/task.yml b/problems/pmpp_v3/conv2d_py/task.yml new file mode 100644 index 000000000..26ba48233 --- /dev/null +++ b/problems/pmpp_v3/conv2d_py/task.yml @@ -0,0 +1,50 @@ +# name: conv2d-py + +files: + - {"name": "submission.py", "source": "@SUBMISSION@"} + - {"name": "task.py", "source": "task.py"} + - {"name": "utils.py", "source": "../utils.py"} + - {"name": "reference.py", "source": "reference.py"} + - {"name": "eval.py", "source": "../eval.py"} + +lang: "py" + +description: | + Return a plain, materialized torch.Tensor. Tensor subclasses and deferred + computation during checking are not allowed; compute the result inside custom_kernel. + + Implement a 2D convolution kernel that matches the reference implementation. + The kernel should perform 2D convolution with the given specifications + We will benchmark different sizes, kernel sizes, channels and batch sizes but they will all + be even numbers with the exception of batch size which can sometimes be 1 + We assume no padding and striding and instead vary the size of the input and kernel, + number of channels, and batch size. + + Input: Tuple of (input_tensor, kernel) + - input_tensor: 4D tensor of shape (batch, channels, height, width) with arbitrary values + - kernel: 4D tensor of shape (channels, channels, kernelsize, kernelsize) with arbitrary values + Output: 4D tensor of shape (batch, channels, height-kernelsize+1, width-kernelsize+1) with convolved values + +config: + main: "eval.py" + +templates: + Python: "../template.py" + +tests: + - {"size": 32, "kernelsize": 4, "channels": 16, "batch": 1, "seed": 4242} + - {"size": 32, "kernelsize": 4, "channels": 16, "batch": 2, "seed": 5236} + - {"size": 64, "kernelsize": 4, "channels": 32, "batch": 1, "seed": 1001} + - {"size": 64, "kernelsize": 8, "channels": 32, "batch": 2, "seed": 5531} + - {"size": 128, "kernelsize": 8, "channels": 64, "batch": 1, "seed": 9173} + +benchmarks: + - {"size": 128, "kernelsize": 8, "channels": 64, "batch": 4, "seed": 54352} + - {"size": 128, "kernelsize": 16, "channels": 64, "batch": 4, "seed": 93246} + - {"size": 256, "kernelsize": 16, "channels": 128, "batch": 2, "seed": 6256} + - {"size": 256, "kernelsize": 16, "channels": 128, "batch": 2, "seed": 8841} + - {"size": 256, "kernelsize": 32, "channels": 128, "batch": 1, "seed": 6252} + +test_timeout: 180 +benchmark_timeout: 180 +ranked_timeout: 420 diff --git a/problems/pmpp_v3/eval.py b/problems/pmpp_v3/eval.py new file mode 100644 index 000000000..981b93222 --- /dev/null +++ b/problems/pmpp_v3/eval.py @@ -0,0 +1,375 @@ +import base64 +import dataclasses +import multiprocessing +import re +import time +import os +import sys +import math +from pathlib import Path +from typing import Any, Optional + +import torch.cuda + +from utils import set_seed, clear_l2_cache +try: + from task import TestSpec +except ImportError: + TestSpec = dict + +from reference import check_implementation, generate_input + + +class PopcornOutput: + def __init__(self, fd: int): + self.file = os.fdopen(fd, 'w') + os.set_inheritable(fd, False) + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + self.file.close() + + def print(self, *args, **kwargs): + print(*args, **kwargs, file=self.file, flush=True) + + def log(self, key, value): + self.print(f"{key}: {value}") + + +@dataclasses.dataclass +class TestCase: + args: dict + spec: str + + +def _combine(a: int, b: int) -> int: + # combine two integers into one: + # we need this to generate a secret seed based on the test-level seed and + # the global secret seed. + # the test-level seeds are public knowledge, and typically relatively small numbers, + # so we need to make sure they don't provide any useful info for the full seed. + # This Cantor construction ensures that if the secret seed is a large number, + # then so is the overall seed. + return int(a + (a+b)*(a+b+1)//2) + + +def get_test_cases(file_name: str, seed: Optional[int]) -> list[TestCase]: + try: + content = Path(file_name).read_text() + except Exception as E: + print(f"Could not open test file`{file_name}`: {E}", file=sys.stderr) + exit(113) + + tests = [] + lines = content.splitlines() + match = r"\s*([a-zA-Z]+):\s*([a-zA-Z]+|[+-]?[0-9]+)\s*" + for line in lines: + parts = line.split(";") + case = {} + for part in parts: + matched = re.match(match, part) + if not re.fullmatch(match, part): + print(f"invalid test case: '{line}': '{part}'", file=sys.stderr) + exit(113) + key = matched[1] + val = matched[2] + try: + val = int(val) + except ValueError: + pass + + case[key] = val + tests.append(TestCase(spec=line, args=case)) + + if seed is not None: + for test in tests: + if "seed" in test.args: + test.args["seed"] = _combine(test.args["seed"], seed) + + return tests + + +@dataclasses.dataclass +class Stats: + runs: int + mean: float + std: float + err: float + best: float + worst: float + + +def calculate_stats(durations: list[int]): + """ + Calculate statistical data from a list of durations. + + @param durations: A list of durations in nanoseconds. + @return: A Stats object containing the number of runs, mean, standard deviation, error, best, and worst durations. + """ + runs = len(durations) + total = sum(durations) + best = min(durations) + worst = max(durations) + + avg = total / runs + variance = sum(map(lambda x: (x - avg)**2, durations)) + std = math.sqrt(variance / (runs - 1)) + err = std / math.sqrt(runs) + + return Stats(runs=runs, mean=avg, std=std, err=err, best=float(best), + worst=float(worst)) + + +def _clone_data(data): + """ + Recursively goes through data and clones all tensors. + """ + if isinstance(data, tuple): + return tuple(_clone_data(x) for x in data) + elif isinstance(data, list): + return [_clone_data(x) for x in data] + elif isinstance(data, dict): + return {k: _clone_data(v) for k, v in data.items()} + elif isinstance(data, torch.Tensor): + return data.clone() + else: + return data + + +def _run_single_test(test: TestCase): + """ + Runs a single test case. Do not call directly + """ + from submission import custom_kernel + data = generate_input(**test.args) + torch.cuda.synchronize() + submission_output = custom_kernel(_clone_data(data)) + torch.cuda.synchronize() + return check_implementation(data, submission_output) + + +def run_single_test(pool: multiprocessing.Pool, test: TestCase): + """ + Runs a single test in another process. + """ + return pool.apply(_run_single_test, (test,)) + + +def run_testing(logger: PopcornOutput, pool: multiprocessing.Pool, tests: list[TestCase]): + """ + Executes the actual test case code and checks for correctness. + + @param logger: A PopcornOutput object used for logging test results. + @param tests: A list of TestCase objects representing the test cases to be executed. + @return: An integer representing the exit status: 0 if all tests pass, otherwise 112. + """ + passed = True + logger.log("test-count", len(tests)) + for idx, test in enumerate(tests): + logger.log(f"test.{idx}.spec", test.spec) + good, message = run_single_test(pool, test) + if not good: + logger.log(f"test.{idx}.status", "fail") + logger.log(f"test.{idx}.error", message) + passed = False + else: + logger.log(f"test.{idx}.status", "pass") + if message: + logger.log(f"test.{idx}.message", message) + + if passed: + logger.log("check", "pass") + return 0 + else: + logger.log("check", "fail") + return 112 + + +def _run_single_benchmark(test: TestCase, recheck: bool, max_repeats: int, max_time_ns: float) -> Stats | Any: + """ + Runs one benchmark. Do not call directly. + """ + from submission import custom_kernel + + durations = [] + # generate input data once + data = generate_input(**test.args) + check_copy = _clone_data(data) + # first, one obligatory correctness check + output = custom_kernel(data) + good, message = check_implementation(check_copy, output) + if not good: + return message + + # now, do multiple timing runs without further correctness testing + # there is an upper bound of 100 runs, and a lower bound of 3 runs; + # otherwise, we repeat until we either measure at least 10 full seconds, + # or the relative error of the mean is below 1%. + + bm_start_time = time.perf_counter_ns() + for i in range(max_repeats): + if recheck: + # ensure we use a different seed for every benchmark + if "seed" in test.args: + test.args["seed"] += 13 + + data = generate_input(**test.args) + check_copy = _clone_data(data) + torch.cuda.synchronize() + start_event = torch.cuda.Event(enable_timing=True) + end_event = torch.cuda.Event(enable_timing=True) + clear_l2_cache() + + start_event.record() + output = custom_kernel(data) + end_event.record() + torch.cuda.synchronize() + duration = start_event.elapsed_time(end_event) * 1e6 # Convert ms to ns + + if recheck: + good, message = check_implementation(check_copy, output) + if not good: + return message + + del output + durations.append(duration) + + if i > 1: + total_bm_duration = time.perf_counter_ns() - bm_start_time + stats = calculate_stats(durations) + # stop if either + # a) relative error dips below 0.1% + # b) we exceed the total time limit for benchmarking the kernel + # c) we exceed 2 minutes of total wallclock time. + if stats.err / stats.mean < 0.001 or stats.mean * stats.runs > max_time_ns or total_bm_duration > 120e9: + break + + return calculate_stats(durations) + + +def run_single_benchmark(pool: multiprocessing.Pool, test: TestCase, recheck: bool, max_repeats: int, + max_time_ns: float): + """ + For a particular test case, check correctness (if applicable) and grab runtime results. + + @param pool: Process on which the benchmark will be launched. + @param test: TestCase object. + @param recheck: Flag for whether to explicitly check functional correctness. + @param max_repeats: Number of trials to repeat. + @param max_time_ns: Timeout time in nanoseconds. + @return: A Stats object for this particular benchmark case or an error if the test fails. + """ + return pool.apply(_run_single_benchmark, (test, recheck, max_repeats, max_time_ns)) + + +def run_benchmarking(logger: PopcornOutput, pool: multiprocessing.Pool, tests: list[TestCase]): + """ + Executes benchmarking code for a CUDA Kernel and logs runtimes. + + @param logger: A PopcornOutput object used for logging benchmark results. + @param pool: Process on which the benchmarks will be launched. + @param tests: A list of TestCase objects representing the test cases to be benchmarked. + @return: An integer representing the exit status: 0 if all benchmarks pass, otherwise 112. + """ + # warm up + run_single_benchmark(pool, tests[0], False, 100, 10e7) + + passed = True + logger.log("benchmark-count", len(tests)) + for idx, test in enumerate(tests): + logger.log(f"benchmark.{idx}.spec", test.spec) + result = run_single_benchmark(pool, test, False, 100, 10e9) + if isinstance(result, Stats): + for field in dataclasses.fields(Stats): + logger.log(f"benchmark.{idx}.{field.name}", getattr(result, field.name)) + else: + passed = False + logger.log(f"benchmark.{idx}.status", "fail") + logger.log(f"benchmark.{idx}.error", result) + + if passed: + logger.log("check", "pass") + return 0 + else: + logger.log("check", "fail") + return 112 + + +def run_single_profile(test: TestCase) -> str: + """ + Runs a single test case. Do not call directly + """ + from submission import custom_kernel + from torch.profiler import profile, record_function, ProfilerActivity + data = generate_input(**test.args) + torch.cuda.synchronize() + + with profile(activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA]) as prof: + submission_output = custom_kernel(_clone_data(data)) + torch.cuda.synchronize() + return prof.key_averages().table(sort_by="self_cuda_time_total", row_limit=20) + + +def run_profiling(logger: PopcornOutput, tests: list[TestCase]): + logger.log("benchmark-count", len(tests)) + for idx, test in enumerate(tests): + logger.log(f"benchmark.{idx}.spec", test.spec) + report = run_single_profile(test) + logger.log(f"benchmark.{idx}.report", base64.b64encode(report.encode("utf-8"), b"+*").decode("utf-8")) + logger.log("check", "pass") + return 0 + + +def main(): + fd = os.getenv("POPCORN_FD") + if not fd: + return 111 + + if len(sys.argv) < 3: + return 2 + + mode = sys.argv[1] + seed = os.getenv("POPCORN_SEED") + os.unsetenv("POPCORN_SEED") + seed = int(seed) if seed else None + set_seed(seed or 42) + tests = get_test_cases(sys.argv[2], seed) + + with PopcornOutput(int(fd)) as logger: + import multiprocessing + mp_context = multiprocessing.get_context('spawn') + with mp_context.Pool(1) as pool: + if mode == "test": + return run_testing(logger, pool, tests) + if mode == "benchmark": + return run_benchmarking(logger, pool, tests) + + if mode == "leaderboard": + # warmup + run_single_benchmark(pool, tests[0], False, 100, 1e7) + logger.log("benchmark-count", len(tests)) + passed = True + for i in range(len(tests)): + result = run_single_benchmark(pool, tests[i], True, 100, 30e9) + logger.log(f"benchmark.{i}.spec", tests[i].spec) + if isinstance(result, Stats): + for field in dataclasses.fields(Stats): + logger.log(f"benchmark.{i}.{field.name}", getattr(result, field.name)) + else: + passed = False + logger.log(f"benchmark.{i}.status", "fail") + logger.log(f"benchmark.{i}.error", str(result)) # TODO: Make sure result implements __str__? + break + + logger.log("check", "pass" if passed else "fail") + elif mode == "profile": + run_profiling(logger, tests) + else: + # TODO: Implement script mode + return 2 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/problems/pmpp_v3/grayscale_py/reference.py b/problems/pmpp_v3/grayscale_py/reference.py new file mode 100644 index 000000000..3190a0543 --- /dev/null +++ b/problems/pmpp_v3/grayscale_py/reference.py @@ -0,0 +1,44 @@ +from utils import make_match_reference, DeterministicContext +import torch +from task import input_t, output_t + + +def ref_kernel(data: input_t) -> output_t: + """ + Reference implementation of RGB to grayscale conversion using PyTorch. + Uses the standard coefficients: Y = 0.2989 R + 0.5870 G + 0.1140 B + + Args: + data: RGB tensor of shape (H, W, 3) with values in [0, 1] + Returns: + Grayscale tensor of shape (H, W) with values in [0, 1] + """ + with DeterministicContext(): + data, output = data + # Standard RGB to Grayscale coefficients + weights = torch.tensor( + [0.2989, 0.5870, 0.1140], device=data.device, dtype=data.dtype + ) + output[...] = torch.sum(data * weights, dim=-1) + return output + + +def generate_input(size: int, seed: int) -> input_t: + """ + Generates random RGB image tensor of specified size. + Returns: + Tensor of shape (size, size, 3) with values in [0, 1] + """ + gen = torch.Generator(device="cuda") + gen.manual_seed(seed) + + x = torch.rand( + size, size, 3, device="cuda", dtype=torch.float32, generator=gen + ).contiguous() + + y = torch.empty(size, size, device="cuda", dtype=torch.float32).contiguous() + + return x, y + + +check_implementation = make_match_reference(ref_kernel, rtol=1e-4, atol=1e-4) diff --git a/problems/pmpp_v3/grayscale_py/solutions/correct/ref.py b/problems/pmpp_v3/grayscale_py/solutions/correct/ref.py new file mode 100644 index 000000000..6a9d1b787 --- /dev/null +++ b/problems/pmpp_v3/grayscale_py/solutions/correct/ref.py @@ -0,0 +1,11 @@ +from task import input_t, output_t +import torch + + +def custom_kernel(data: input_t) -> output_t: + data, output = data + weights = torch.tensor( + [0.2989, 0.5870, 0.1140], device=data.device, dtype=data.dtype + ) + output[...] = torch.sum(data * weights, dim=-1) + return output diff --git a/problems/pmpp_v3/grayscale_py/solutions/wrong/empty.py b/problems/pmpp_v3/grayscale_py/solutions/wrong/empty.py new file mode 100644 index 000000000..129b89668 --- /dev/null +++ b/problems/pmpp_v3/grayscale_py/solutions/wrong/empty.py @@ -0,0 +1,8 @@ +# the nop kernel +from task import input_t, output_t +import torch + + +def custom_kernel(data: input_t) -> output_t: + _, output = data + return output diff --git a/problems/pmpp_v3/grayscale_py/submission.py b/problems/pmpp_v3/grayscale_py/submission.py new file mode 100644 index 000000000..9e55306c9 --- /dev/null +++ b/problems/pmpp_v3/grayscale_py/submission.py @@ -0,0 +1,10 @@ +from task import input_t, output_t +import torch + +def custom_kernel(data: input_t) -> output_t: + data, output = data + weights = torch.tensor([0.2989, 0.5870, 0.1140], + device=data.device, + dtype=data.dtype) + output[...] = torch.sum(data * weights, dim=-1) + return output diff --git a/problems/pmpp_v3/grayscale_py/task.py b/problems/pmpp_v3/grayscale_py/task.py new file mode 100644 index 000000000..26a2f524a --- /dev/null +++ b/problems/pmpp_v3/grayscale_py/task.py @@ -0,0 +1,14 @@ +from typing import TypedDict, TypeVar +import torch + +input_t = TypeVar( + "input_t", bound=tuple[torch.Tensor, torch.Tensor] +) # Input is a pair of tensors (input, output) where input is (H, W, 3) RGB tensor and output is (H, W) grayscale tensor +output_t = TypeVar( + "output_t", bound=torch.Tensor +) # Output will be (H, W) grayscale tensor + + +class TestSpec(TypedDict): + size: int # Size of the square image (H=W) + seed: int diff --git a/problems/pmpp_v3/grayscale_py/task.yml b/problems/pmpp_v3/grayscale_py/task.yml new file mode 100644 index 000000000..842e42ba7 --- /dev/null +++ b/problems/pmpp_v3/grayscale_py/task.yml @@ -0,0 +1,44 @@ +files: + - {"name": "submission.py", "source": "@SUBMISSION@"} + - {"name": "task.py", "source": "task.py"} + - {"name": "utils.py", "source": "../utils.py"} + - {"name": "reference.py", "source": "reference.py"} + - {"name": "eval.py", "source": "../eval.py"} + +lang: "py" + +description: | + Return a plain, materialized torch.Tensor. Tensor subclasses and deferred + computation during checking are not allowed; compute the result inside custom_kernel. + + Implement an RGB to grayscale conversion kernel that matches the reference implementation. + The kernel should convert square RGB images with even sizes to grayscale using the standard coefficients: + Y = 0.2989 R + 0.5870 G + 0.1140 B + + Input: RGB tensor of shape (H, W, 3) with values in [0, 1] + Output: Grayscale tensor of shape (H, W) with values in [0, 1] + +config: + main: "eval.py" + +templates: + Python: "../template.py" + +tests: + + - {"size": 128, "seed": 1001} + - {"size": 256, "seed": 5531} + - {"size": 512, "seed": 9173} + +benchmarks: + + - {"size": 512, "seed": 54352} + - {"size": 1024, "seed": 93246} + - {"size": 2048, "seed": 6256} + - {"size": 4096, "seed": 8841} + - {"size": 8192, "seed": 6252} + - {"size": 16384, "seed": 54352} + +test_timeout: 180 +benchmark_timeout: 180 +ranked_timeout: 420 diff --git a/problems/pmpp_v3/histogram_py/reference.py b/problems/pmpp_v3/histogram_py/reference.py new file mode 100644 index 000000000..4268cec79 --- /dev/null +++ b/problems/pmpp_v3/histogram_py/reference.py @@ -0,0 +1,56 @@ +from utils import verbose_allequal, DeterministicContext +import torch +from task import input_t, output_t + + +def ref_kernel(data: input_t) -> output_t: + """ + Reference implementation of histogram using PyTorch. + Args: + data: tensor of shape (size,) + Returns: + Tensor containing bin counts + """ + with DeterministicContext(): + data, output = data + # Count values in each bin + output[...] = torch.bincount(data, minlength=256) + return output + + +def generate_input(size: int, contention: float, seed: int) -> input_t: + """ + Generates random input tensor for histogram. + + Args: + size: Size of the input tensor (must be multiple of 16) + contention: float in [0, 100], specifying the percentage of identical values + seed: Random seed + Returns: + The input tensor with values in [0, 255] + """ + gen = torch.Generator(device='cuda') + gen.manual_seed(seed) + + # Generate integer values between 0 and 256 + data = torch.randint(0, 256, (size,), device='cuda', dtype=torch.uint8, generator=gen) + + # make one value appear quite often, increasing the chance for atomic contention + evil_value = torch.randint(0, 256, (), device='cuda', dtype=torch.uint8, generator=gen) + evil_loc = torch.rand((size,), device='cuda', dtype=torch.float32, generator=gen) < (contention / 100.0) + data[evil_loc] = evil_value + + output = torch.empty(256, device='cuda', dtype=torch.int64).contiguous() + + return data.contiguous(), output + + +def check_implementation(data, output): + expected = ref_kernel(data) + reasons = verbose_allequal(output, expected) + + if len(reasons) > 0: + return False, "mismatch found! custom implementation doesn't match reference: " + " ".join(reasons) + + return True, '' + diff --git a/problems/pmpp_v3/histogram_py/solutions/correct/ref.py b/problems/pmpp_v3/histogram_py/solutions/correct/ref.py new file mode 100644 index 000000000..d96e1a21b --- /dev/null +++ b/problems/pmpp_v3/histogram_py/solutions/correct/ref.py @@ -0,0 +1,8 @@ +import torch +from task import input_t, output_t + + +def custom_kernel(data: input_t) -> output_t: + data, output = data + output[...] = torch.bincount(data, minlength=256) + return output diff --git a/problems/pmpp_v3/histogram_py/solutions/wrong/empty.py b/problems/pmpp_v3/histogram_py/solutions/wrong/empty.py new file mode 100644 index 000000000..af7bfcc02 --- /dev/null +++ b/problems/pmpp_v3/histogram_py/solutions/wrong/empty.py @@ -0,0 +1,7 @@ +# the nop kernel +from task import input_t, output_t + + +def custom_kernel(data: input_t) -> output_t: + _, output = data + return output diff --git a/problems/pmpp_v3/histogram_py/submission.py b/problems/pmpp_v3/histogram_py/submission.py new file mode 100644 index 000000000..590fd03ad --- /dev/null +++ b/problems/pmpp_v3/histogram_py/submission.py @@ -0,0 +1,16 @@ +import torch +from task import input_t, output_t + + +def custom_kernel(data: input_t) -> output_t: + """ + Reference implementation of histogram using PyTorch. + Args: + data: tensor of shape (size,) + Returns: + Tensor containing bin counts + """ + data, output = data + # Compute histogram with 256 bins + output[...] = torch.bincount(data, minlength=256) + return output diff --git a/problems/pmpp_v3/histogram_py/task.py b/problems/pmpp_v3/histogram_py/task.py new file mode 100644 index 000000000..632ed7f28 --- /dev/null +++ b/problems/pmpp_v3/histogram_py/task.py @@ -0,0 +1,11 @@ +from typing import TypedDict, TypeVar +import torch + +input_t = TypeVar("input_t", bound=tuple[torch.Tensor, torch.Tensor]) +output_t = TypeVar("output_t", bound=torch.Tensor) + + +class TestSpec(TypedDict): + size: int + seed: int + contention: int diff --git a/problems/pmpp_v3/histogram_py/task.yml b/problems/pmpp_v3/histogram_py/task.yml new file mode 100644 index 000000000..192509ab5 --- /dev/null +++ b/problems/pmpp_v3/histogram_py/task.yml @@ -0,0 +1,49 @@ +# name: histogram-cuda-inline + +files: + - {"name": "submission.py", "source": "@SUBMISSION@"} + - {"name": "task.py", "source": "task.py"} + - {"name": "utils.py", "source": "../utils.py"} + - {"name": "reference.py", "source": "reference.py"} + - {"name": "eval.py", "source": "../eval.py"} + +lang: "py" + +description: | + Return a plain, materialized torch.Tensor. Tensor subclasses and deferred + computation during checking are not allowed; compute the result inside custom_kernel. + + Implement a histogram kernel that counts the number of elements falling into each bin across the specified range. + Input values are uint8 integers in [0, 255]. All sizes are multiples of 16. + The output must be a CUDA int64 tensor of shape (256,), containing the exact count + for every bin. Broadcasting a scalar or returning floating-point counts is invalid. + + Input: + - data: a tensor of shape (size,) + +config: + main: "eval.py" + +templates: + Python: "../template.py" + +tests: + - {"size": 5120, "seed": 9991, "contention": 10} + - {"size": 7840, "seed": 2105, "contention": 10} + - {"size": 30080, "seed": 9999, "contention": 10} + - {"size": 30080, "seed": 4254, "contention": 90} + - {"size": 100000, "seed": 1212, "contention": 10} + - {"size": 5120, "seed": 3917, "contention": 0} + - {"size": 5120, "seed": 3918, "contention": 100} + +benchmarks: + - {"size": 1310720, "seed": 6252, "contention": 10} + - {"size": 2621440, "seed": 8841, "contention": 10} + - {"size": 2621440, "seed": 3411, "contention": 40} + - {"size": 2621440, "seed": 8753, "contention": 90} + - {"size": 5242880, "seed": 6252, "contention": 10} + - {"size": 10485760, "seed": 8841, "contention": 10} + +test_timeout: 180 +benchmark_timeout: 180 +ranked_timeout: 420 diff --git a/problems/pmpp_v3/matmul_py/reference.py b/problems/pmpp_v3/matmul_py/reference.py new file mode 100644 index 000000000..dc34cd32c --- /dev/null +++ b/problems/pmpp_v3/matmul_py/reference.py @@ -0,0 +1,23 @@ +import torch +from task import input_t, output_t +from utils import make_match_reference, DeterministicContext + + +def generate_input(m: int, n: int, k: int, seed: int) -> input_t: + gen = torch.Generator(device='cuda') + gen.manual_seed(seed) + a = torch.empty(m, k, device='cuda', dtype=torch.float16) + a.uniform_(0, 1, generator=gen) + b = torch.empty(k, n, device='cuda', dtype=torch.float16) + b.uniform_(0, 1, generator=gen) + c = torch.empty(m, n, device='cuda', dtype=torch.float16) + return a, b, c + + +def ref_kernel(data: input_t) -> output_t: + with DeterministicContext(): + a, b, c = data + return a @ b + + +check_implementation = make_match_reference(ref_kernel) diff --git a/problems/pmpp_v3/matmul_py/solutions/correct/ref.py b/problems/pmpp_v3/matmul_py/solutions/correct/ref.py new file mode 100644 index 000000000..15898593e --- /dev/null +++ b/problems/pmpp_v3/matmul_py/solutions/correct/ref.py @@ -0,0 +1,8 @@ +import torch +from task import input_t, output_t + + +def custom_kernel(data: input_t) -> output_t: + a, b, c = data + c[...] = a @ b + return c diff --git a/problems/pmpp_v3/matmul_py/solutions/wrong/low-precision.py b/problems/pmpp_v3/matmul_py/solutions/wrong/low-precision.py new file mode 100644 index 000000000..b9af5586d --- /dev/null +++ b/problems/pmpp_v3/matmul_py/solutions/wrong/low-precision.py @@ -0,0 +1,8 @@ +import torch +from task import input_t, output_t + + +def custom_kernel(data: input_t) -> output_t: + a, b, c = data + c[...] = (a.to(torch.bfloat16) @ b.to(torch.bfloat16)).to(c.dtype) + return c diff --git a/problems/pmpp_v3/matmul_py/submission.py b/problems/pmpp_v3/matmul_py/submission.py new file mode 100644 index 000000000..ecb0408d2 --- /dev/null +++ b/problems/pmpp_v3/matmul_py/submission.py @@ -0,0 +1,6 @@ +from task import input_t, output_t + +def custom_kernel(data: input_t) -> output_t: + a, b, c = data + c[...] = a @ b + return c diff --git a/problems/pmpp_v3/matmul_py/task.py b/problems/pmpp_v3/matmul_py/task.py new file mode 100644 index 000000000..65a72b3f4 --- /dev/null +++ b/problems/pmpp_v3/matmul_py/task.py @@ -0,0 +1,11 @@ +import torch +from typing import TypeVar, TypedDict + +input_t = TypeVar("input_t", bound=tuple[torch.Tensor, torch.Tensor, torch.Tensor]) +output_t = TypeVar("output_t", bound=torch.Tensor) + +class TestSpec(TypedDict): + m: int + n: int + k: int + seed: int diff --git a/problems/pmpp_v3/matmul_py/task.yml b/problems/pmpp_v3/matmul_py/task.yml new file mode 100644 index 000000000..8fa1837c6 --- /dev/null +++ b/problems/pmpp_v3/matmul_py/task.yml @@ -0,0 +1,47 @@ +# name: matmul-py + +files: + - {"name": "submission.py", "source": "@SUBMISSION@"} + - {"name": "task.py", "source": "task.py"} + - {"name": "utils.py", "source": "../utils.py"} + - {"name": "reference.py", "source": "reference.py"} + - {"name": "eval.py", "source": "../eval.py"} + +lang: "py" + +description: | + Return a plain, materialized torch.Tensor. Tensor subclasses and deferred + computation during checking are not allowed; compute the result inside custom_kernel. + + Implement a custom matmul function that matches the reference implementation. + The function should handle a tuple of input tensors and apply matmul + The shapes of all outer and inner dimensions of tensors are multiples of 16 + +config: + main: "eval.py" + +templates: + Python: "../template.py" + +tests: + - {"m": 64, "n": 64, "k": 64, "seed": 53124} + - {"m": 128, "n": 128, "k": 128, "seed": 3321} + - {"m": 256, "n": 256, "k": 256, "seed": 1200} + + - {"m": 32, "n": 512, "k": 32, "seed": 32523} + - {"m": 64, "n": 1024, "k": 64, "seed": 4327} + +benchmarks: + - {"m": 128, "n": 128, "k": 128, "seed": 43214} + - {"m": 256, "n": 256, "k": 256, "seed": 423011} + - {"m": 512, "n": 512, "k": 512, "seed": 123456} + - {"m": 1024, "n": 1024, "k": 1024, "seed": 1029} + - {"m": 2048, "n": 2048, "k": 2048, "seed": 75342} + + - {"m": 1024, "n": 1536, "k": 1024, "seed": 321} + - {"m": 2048, "n": 3072, "k": 2048, "seed": 32412} + - {"m": 4096, "n": 5120, "k": 4096, "seed": 123456} + +test_timeout: 180 +benchmark_timeout: 180 +ranked_timeout: 420 diff --git a/problems/pmpp_v3/prefixsum_py/reference.py b/problems/pmpp_v3/prefixsum_py/reference.py new file mode 100644 index 000000000..8069dac69 --- /dev/null +++ b/problems/pmpp_v3/prefixsum_py/reference.py @@ -0,0 +1,58 @@ +import torch +from task import input_t, output_t +from utils import DeterministicContext, match_reference + + +def ref_kernel(data: input_t) -> output_t: + """ + Reference implementation of inclusive prefix sum using PyTorch. + Args: + data: Input tensor to compute prefix sum on + Returns: + Tensor containing the inclusive prefix sum + """ + with DeterministicContext(): + data, output = data + output = torch.cumsum(data.to(torch.float64), dim=0).to(torch.float32) + return output + + +def generate_input( + size: int, seed: int, distribution: str = "normal", *, device="cuda" +) -> input_t: + """ + Generates random input tensor. + Returns: + Tensor to compute prefix sum on + """ + gen = torch.Generator(device=device) + gen.manual_seed(seed) + x = torch.randn( + size, device=device, dtype=torch.float32, generator=gen + ).contiguous() + if distribution == "positive": + x = x.abs() + 0.25 + elif distribution == "negative": + x = -x.abs() - 0.25 + elif distribution == "alternating": + x[1::2] = -x[::2][: x[1::2].numel()] + elif distribution == "sparse": + x.zero_() + if size: + indices = torch.randperm(size, device=device, generator=gen)[ + : min(size, 16) + ] + x[indices] = torch.randn(indices.numel(), device=device, generator=gen) + elif distribution != "normal": + raise ValueError(f"Unknown prefix sum distribution: {distribution}") + y = torch.empty(size, device=device, dtype=torch.float32).contiguous() + return x, y + + +def check_implementation(data: input_t, output: output_t) -> tuple[bool, str]: + # Parallel reduction orders need an absolute roundoff allowance. Scale it + # with input energy, not answer magnitude: sqrt(n)-scaled rtol allowed a + # 16% error on the largest benchmark. + input_norm = torch.linalg.vector_norm(data[0].to(torch.float64)).item() + atol = 1e-5 * (1 + input_norm) + return match_reference(data, output, reference=ref_kernel, rtol=1e-5, atol=atol) diff --git a/problems/pmpp_v3/prefixsum_py/solutions/correct/ref.py b/problems/pmpp_v3/prefixsum_py/solutions/correct/ref.py new file mode 100644 index 000000000..1bfe53c07 --- /dev/null +++ b/problems/pmpp_v3/prefixsum_py/solutions/correct/ref.py @@ -0,0 +1,8 @@ +import torch +from task import input_t, output_t + + +def custom_kernel(data: input_t) -> output_t: + data, output = data + output[...] = torch.cumsum(data, dim=0) + return output diff --git a/problems/pmpp_v3/prefixsum_py/solutions/wrong/empty.py b/problems/pmpp_v3/prefixsum_py/solutions/wrong/empty.py new file mode 100644 index 000000000..af7bfcc02 --- /dev/null +++ b/problems/pmpp_v3/prefixsum_py/solutions/wrong/empty.py @@ -0,0 +1,7 @@ +# the nop kernel +from task import input_t, output_t + + +def custom_kernel(data: input_t) -> output_t: + _, output = data + return output diff --git a/problems/pmpp_v3/prefixsum_py/submission.py b/problems/pmpp_v3/prefixsum_py/submission.py new file mode 100644 index 000000000..aa8c90a96 --- /dev/null +++ b/problems/pmpp_v3/prefixsum_py/submission.py @@ -0,0 +1,15 @@ +import torch +from task import input_t, output_t + + +def custom_kernel(data: input_t) -> output_t: + """ + Reference implementation of inclusive prefix sum using PyTorch. + Args: + data: Input tensor to compute prefix sum on + Returns: + Tensor containing the inclusive prefix sum + """ + data, output = data + output[...] = torch.cumsum(data, dim=0) + return output diff --git a/problems/pmpp_v3/prefixsum_py/task.py b/problems/pmpp_v3/prefixsum_py/task.py new file mode 100644 index 000000000..af911c6da --- /dev/null +++ b/problems/pmpp_v3/prefixsum_py/task.py @@ -0,0 +1,12 @@ +from typing import NotRequired, TypedDict, TypeVar + +import torch + +input_t = TypeVar("input_t", bound=tuple[torch.Tensor, torch.Tensor]) +output_t = TypeVar("output_t", bound=torch.Tensor) + + +class TestSpec(TypedDict): + size: int + seed: int + distribution: NotRequired[str] diff --git a/problems/pmpp_v3/prefixsum_py/task.yml b/problems/pmpp_v3/prefixsum_py/task.yml new file mode 100644 index 000000000..1c086ce02 --- /dev/null +++ b/problems/pmpp_v3/prefixsum_py/task.yml @@ -0,0 +1,66 @@ +# name: prefixsum-cuda-inline + +files: + - {"name": "submission.py", "source": "@SUBMISSION@"} + - {"name": "task.py", "source": "task.py"} + - {"name": "utils.py", "source": "../utils.py"} + - {"name": "reference.py", "source": "reference.py"} + - {"name": "eval.py", "source": "../eval.py"} + +lang: "py" + +description: | + Return a plain, materialized torch.Tensor. Tensor subclasses and deferred + computation during checking are not allowed; compute the result inside custom_kernel. + + Implement an inclusive prefix sum (scan) kernel that matches the reference implementation. + The kernel should compute the cumulative sum of all elements up to each position. + Input and output use float32. Correctness is checked against float64 accumulation + rounded to float32, with fixed relative tolerance 1e-5 and an absolute roundoff + allowance of 1e-5 * (1 + L2 norm of the input). Relative error does not grow with size. + + Input: + - `data`: A 1D tensor of size `n` + Output: + - `output`: A 1D tensor of size `n` + +config: + main: "eval.py" + +templates: + Python: "../template.py" + +tests: + - {"size": 1023, "seed": 4242} + - {"size": 1024, "seed": 5236} + - {"size": 1025, "seed": 1001} + - {"size": 2048, "seed": 5531} + - {"size": 4096, "seed": 9173} + - {"size": 4097, "seed": 4001, "distribution": "positive"} + - {"size": 4097, "seed": 4002, "distribution": "negative"} + - {"size": 4097, "seed": 4003, "distribution": "alternating"} + - {"size": 4097, "seed": 4004, "distribution": "sparse"} + +benchmarks: + # - {"size": 8192, "seed": 54352} + # - {"size": 16384, "seed": 93246} + # - {"size": 32768, "seed": 6256} + # - {"size": 65536, "seed": 8841} + # - {"size": 131072, "seed": 6252} + - {"size": 262144, "seed": 12345} + - {"size": 524288, "seed": 67890} + - {"size": 1048576, "seed": 13579} + - {"size": 2097152, "seed": 24680} + - {"size": 4194304, "seed": 35791} + - {"size": 8388608, "seed": 46802} + - {"size": 16777216, "seed": 57913} + - {"size": 33554432, "seed": 68024} + - {"size": 67108864, "seed": 79135} + - {"size": 134217728, "seed": 80246} # fits on T4 + - {"size": 268435456, "seed": 91357} + # - {"size": 536870912, "seed": 102468} + # - {"size": 1073741824, "seed": 113579} + +test_timeout: 180 +benchmark_timeout: 180 +ranked_timeout: 420 diff --git a/problems/pmpp_v3/sort_py/reference.py b/problems/pmpp_v3/sort_py/reference.py new file mode 100644 index 000000000..2d6e39ab9 --- /dev/null +++ b/problems/pmpp_v3/sort_py/reference.py @@ -0,0 +1,61 @@ +import torch +from task import input_t, output_t +from utils import DeterministicContext, make_match_reference_exact + + +def ref_kernel(data: input_t) -> output_t: + """ + Reference implementation of sort using PyTorch. + Args: + data: Input tensor to be sorted + Returns: + Sorted tensor + """ + with DeterministicContext(): + data, output = data + output[...] = torch.sort(data)[0] + return output + + +def generate_input( + size: int, seed: int, distribution: str = "normal", *, device="cuda" +) -> input_t: + """Seeds select random values, never their magnitude or location. + + Private seeds can be very large. Adding them to float32 data erases the + random values and makes approximate, input-independent outputs pass. + """ + if size < 0: + raise ValueError("size must be non-negative") + gen = torch.Generator(device=device).manual_seed(seed) + if distribution in ("normal", "sorted", "reverse", "outliers"): + values = torch.randn(size, device=device, dtype=torch.float32, generator=gen) + if distribution == "sorted": + values = values.sort().values + elif distribution == "reverse": + values = values.sort(descending=True).values + elif distribution == "outliers" and size: + indices = torch.randperm(size, device=device, generator=gen)[ + : max(1, size // 32) + ] + values[indices] *= 1024 + elif distribution == "uniform": + values = ( + torch.rand(size, device=device, dtype=torch.float32, generator=gen) * 16 - 8 + ) + elif distribution == "duplicates": + values = torch.randint(-8, 9, (size,), device=device, generator=gen).to( + torch.float32 + ) + elif distribution == "constant": + value = torch.randint(-8, 9, (), device=device, generator=gen).item() + values = torch.full((size,), value, device=device, dtype=torch.float32) + else: + raise ValueError(f"Unknown sort distribution: {distribution}") + values = values.contiguous() + return values, torch.empty_like(values) + + +# Sorting preserves values exactly. Tolerance accepts fabricated values and +# lost duplicates even when the output is increasing and looks plausible. +check_implementation = make_match_reference_exact(ref_kernel) diff --git a/problems/pmpp_v3/sort_py/solutions/correct/ref.py b/problems/pmpp_v3/sort_py/solutions/correct/ref.py new file mode 100644 index 000000000..20be517eb --- /dev/null +++ b/problems/pmpp_v3/sort_py/solutions/correct/ref.py @@ -0,0 +1,11 @@ +import torch +from task import input_t, output_t + + +def _custom_kernel(data: input_t) -> output_t: + data, output = data + output[...] = torch.sort(data)[0] + return output + + +custom_kernel = torch.compile(_custom_kernel, mode="reduce-overhead") diff --git a/problems/pmpp_v3/sort_py/solutions/wrong/empty.py b/problems/pmpp_v3/sort_py/solutions/wrong/empty.py new file mode 100644 index 000000000..af7bfcc02 --- /dev/null +++ b/problems/pmpp_v3/sort_py/solutions/wrong/empty.py @@ -0,0 +1,7 @@ +# the nop kernel +from task import input_t, output_t + + +def custom_kernel(data: input_t) -> output_t: + _, output = data + return output diff --git a/problems/pmpp_v3/sort_py/submission.py b/problems/pmpp_v3/sort_py/submission.py new file mode 100644 index 000000000..43175250c --- /dev/null +++ b/problems/pmpp_v3/sort_py/submission.py @@ -0,0 +1,18 @@ +import torch +from task import input_t, output_t + + +def _custom_kernel(data: input_t) -> output_t: + """ + Implements sort using PyTorch. + Args: + data: Input tensor to be sorted + Returns: + Sorted tensor + """ + data, output = data + output[...] = torch.sort(data)[0] + return output + + +custom_kernel = torch.compile(_custom_kernel, mode="reduce-overhead") diff --git a/problems/pmpp_v3/sort_py/task.py b/problems/pmpp_v3/sort_py/task.py new file mode 100644 index 000000000..43b8a8942 --- /dev/null +++ b/problems/pmpp_v3/sort_py/task.py @@ -0,0 +1,12 @@ +from typing import NotRequired, TypedDict, TypeVar + +import torch + +input_t = TypeVar("input_t", bound=[torch.Tensor, torch.Tensor]) +output_t = TypeVar("output_t", bound=torch.Tensor) + + +class TestSpec(TypedDict): + size: int + seed: int + distribution: NotRequired[str] diff --git a/problems/pmpp_v3/sort_py/task.yml b/problems/pmpp_v3/sort_py/task.yml new file mode 100644 index 000000000..029fb86ea --- /dev/null +++ b/problems/pmpp_v3/sort_py/task.yml @@ -0,0 +1,55 @@ +# name: mergesort-cuda-inline + +files: + - {"name": "submission.py", "source": "@SUBMISSION@"} + - {"name": "task.py", "source": "task.py"} + - {"name": "utils.py", "source": "../utils.py"} + - {"name": "reference.py", "source": "reference.py"} + - {"name": "eval.py", "source": "../eval.py"} + +lang: "py" + +description: | + Return a plain, materialized torch.Tensor. Tensor subclasses and deferred + computation during checking are not allowed; compute the result inside custom_kernel. + + Implement a sort kernel that matches the reference implementation. + The kernel should sort the input array in ascending order using a sort algorithm of your choice. + + Input and output are contiguous 1D CUDA float32 tensors of the same length. + Inputs contain finite values from normal, uniform, duplicate-heavy, constant, + already sorted, reverse-sorted, and outlier distributions. Seeds control randomness + only; their numeric values are never added to the data. + The output must equal the sorted input exactly, including duplicate counts. + Generating a similar distribution or approximating sorted values is incorrect. + +config: + main: "eval.py" + +templates: + Python: "../template.py" +tests: + - {"size": 1, "seed": 7123} + - {"size": 17, "seed": 9173, "distribution": "duplicates"} + - {"size": 1023, "seed": 4242} + - {"size": 1024, "seed": 5236} + - {"size": 1025, "seed": 1001} + - {"size": 2048, "seed": 5531} + - {"size": 4096, "seed": 9173} + - {"size": 4097, "seed": 4001, "distribution": "uniform"} + - {"size": 4097, "seed": 4002, "distribution": "duplicates"} + - {"size": 4097, "seed": 4003, "distribution": "constant"} + - {"size": 4097, "seed": 4004, "distribution": "sorted"} + - {"size": 4097, "seed": 4005, "distribution": "reverse"} + - {"size": 4097, "seed": 4006, "distribution": "outliers"} + +benchmarks: + - {"size": 100000, "seed": 54352} + - {"size": 500000, "seed": 93246} + - {"size": 1000000, "seed": 6256} + - {"size": 10000000, "seed": 8841} + - {"size": 100000000, "seed": 6252} + +test_timeout: 180 +benchmark_timeout: 180 +ranked_timeout: 420 diff --git a/problems/pmpp_v3/template.py b/problems/pmpp_v3/template.py new file mode 100644 index 000000000..4aec6a6cb --- /dev/null +++ b/problems/pmpp_v3/template.py @@ -0,0 +1,5 @@ +from task import input_t, output_t + + +def custom_kernel(data: input_t) -> output_t: + pass diff --git a/problems/pmpp_v3/utils.py b/problems/pmpp_v3/utils.py new file mode 100644 index 000000000..3f4eb70ef --- /dev/null +++ b/problems/pmpp_v3/utils.py @@ -0,0 +1,212 @@ +import os +import random + +import numpy as np +import torch + + +def set_seed(seed=42): + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + if torch.cuda.is_available(): + torch.cuda.manual_seed(seed) + torch.cuda.manual_seed_all(seed) + + +def get_device(use_cuda: bool = True) -> torch.device: + """Get the appropriate device (GPU or CPU).""" + if use_cuda: + if torch.cuda.is_available(): + return torch.device("cuda") + elif torch.backends.mps.is_available(): + return torch.device("mps") + else: + print("No compatible GPU found. Falling back to CPU.") + return torch.device("cpu") + + +def _check_tensor_contract(received, expected) -> list[str]: + """Reject malformed results before comparisons can broadcast or promote them.""" + # Subclass hooks can fabricate comparisons or defer the kernel until the + # checker touches its result, moving computation outside the timed region. + if type(received) is not torch.Tensor: + return ["TYPE MISMATCH: output must be a plain, materialized torch.Tensor"] + if received.shape != expected.shape: + return [ + f"SIZE MISMATCH: got {tuple(received.shape)}, expected {tuple(expected.shape)}" + ] + if received.dtype != expected.dtype: + return [f"DTYPE MISMATCH: got {received.dtype}, expected {expected.dtype}"] + if received.device != expected.device: + return [f"DEVICE MISMATCH: got {received.device}, expected {expected.device}"] + if expected.is_floating_point(): + if not torch.isfinite(expected).all().item(): + return ["NON-FINITE REFERENCE: PMPP v3 requires finite results"] + if not torch.isfinite(received).all().item(): + return ["NON-FINITE OUTPUT"] + return [] + + +def _mismatch_details(received, expected, mismatched, max_print): + num_mismatched = mismatched.count_nonzero().item() + if not num_mismatched: + return [] + details = [f"Number of mismatched elements: {num_mismatched}"] + # A fabricated large result can mismatch everywhere. Never allocate an + # index tensor proportional to all failures just to report five examples. + flat = mismatched.reshape(-1) + printed = 0 + for start in range(0, flat.numel(), 65536): + indices = flat[start : start + 65536].nonzero().flatten()[: max_print - printed] + for offset in indices.tolist(): + position = start + offset + index = [] + for size in reversed(expected.shape): + index.append(position % size) + position //= size + index = tuple(reversed(index)) + details.append(f"ERROR AT {index}: {received[index]} {expected[index]}") + printed += 1 + if printed >= max_print: + break + if num_mismatched > printed: + details.append(f"... and {num_mismatched - printed} more mismatched elements.") + return details + + +# Adapted from https://github.com/linkedin/Liger-Kernel/blob/main/test/utils.py +@torch.no_grad() +def verbose_allclose( + received: torch.Tensor, expected: torch.Tensor, rtol=1e-05, atol=1e-08, max_print=5 +) -> list[str]: + """ + Assert that two tensors are element-wise equal within a tolerance, providing detailed information about mismatches. + + Parameters: + received (torch.Tensor): Tensor we actually got. + expected (torch.Tensor): Tensor we expected to receive. + rtol (float): Relative tolerance; relative to expected + atol (float): Absolute tolerance. + max_print (int): Maximum number of mismatched elements to print. + + Raises: + AssertionError: If the tensors are not all close within the given tolerance. + """ + reasons = _check_tensor_contract(received, expected) + if reasons: + return reasons + + # Calculate the difference between the tensors + diff = torch.abs(received - expected) + + # Determine the tolerance + tolerance = atol + rtol * torch.abs(expected) + + # Non-finite values were rejected above. Keep only one mismatch mask for + # benchmark-sized scans instead of several full-size NaN/Inf masks. + mismatched = diff > tolerance + + return _mismatch_details(received, expected, mismatched, max_print) + + +@torch.no_grad() +def verbose_allequal( + received: torch.Tensor, expected: torch.Tensor, max_print: int = 5 +): + """ + Assert that two tensors are element-wise perfectly equal, providing detailed information about mismatches. + + Parameters: + received (torch.Tensor): Tensor we actually got. + expected (torch.Tensor): Tensor we expected to receive. + max_print (int): Maximum number of mismatched elements to print. + + Returns: + Empty string if tensors are equal, otherwise detailed error information + """ + reasons = _check_tensor_contract(received, expected) + if reasons: + return reasons + mismatched = torch.not_equal(received, expected) + return _mismatch_details(received, expected, mismatched, max_print) + + +def match_reference( + data, output, reference: callable, rtol=1e-05, atol=1e-08 +) -> tuple[bool, str]: + """ + Convenient "default" implementation for tasks' `check_implementation` function. + """ + expected = reference(data) + reasons = verbose_allclose(output, expected, rtol=rtol, atol=atol) + + if len(reasons) > 0: + return ( + False, + "mismatch found! custom implementation doesn't match reference: " + + " ".join(reasons), + ) + + return True, "" + + +def make_match_reference(reference: callable, **kwargs): + def wrapped(data, output): + return match_reference(data, output, reference=reference, **kwargs) + + return wrapped + + +def make_match_reference_exact(reference: callable): + """Use for operations such as sorting that must preserve exact values.""" + + @torch.no_grad() + def wrapped(data, output): + expected = reference(data) + reasons = verbose_allequal(output, expected) + if reasons: + return False, "exact reference mismatch: " + " ".join(reasons) + return True, "" + + return wrapped + + +class DeterministicContext: + def __init__(self): + self.allow_tf32 = None + self.deterministic = None + self.cublas = None + self.algorithms = None + self.warn_only = None + self.matmul_tf32 = None + + def __enter__(self): + self.cublas = os.environ.get("CUBLAS_WORKSPACE_CONFIG", "") + self.allow_tf32 = torch.backends.cudnn.allow_tf32 + self.deterministic = torch.backends.cudnn.deterministic + self.algorithms = torch.are_deterministic_algorithms_enabled() + self.warn_only = torch.is_deterministic_algorithms_warn_only_enabled() + self.matmul_tf32 = torch.backends.cuda.matmul.allow_tf32 + torch.backends.cudnn.allow_tf32 = False + torch.backends.cudnn.deterministic = True + torch.backends.cuda.matmul.allow_tf32 = False + torch.use_deterministic_algorithms(True) + return self + + def __exit__(self, exc_type, exc_value, traceback): + torch.backends.cudnn.allow_tf32 = self.allow_tf32 + torch.backends.cudnn.deterministic = self.deterministic + torch.backends.cuda.matmul.allow_tf32 = self.matmul_tf32 + torch.use_deterministic_algorithms(self.algorithms, warn_only=self.warn_only) + os.environ["CUBLAS_WORKSPACE_CONFIG"] = self.cublas + + +def clear_l2_cache(): + # import cupy as cp + # cp.cuda.runtime.deviceSetLimit(cp.cuda.runtime.cudaLimitPersistingL2CacheSize, 0) + # create a large dummy tensor + dummy = torch.empty((32, 1024, 1024), dtype=torch.int64, device="cuda") + # write stuff to + dummy.fill_(42) + del dummy diff --git a/problems/pmpp_v3/vectoradd_py/reference.py b/problems/pmpp_v3/vectoradd_py/reference.py new file mode 100644 index 000000000..3f200545c --- /dev/null +++ b/problems/pmpp_v3/vectoradd_py/reference.py @@ -0,0 +1,38 @@ +import torch +from task import input_t, output_t +from utils import DeterministicContext, make_match_reference_exact + + +def ref_kernel(data: input_t) -> output_t: + """ + Reference implementation of vector addition using PyTorch. + Args: + data: Tuple of tensors [A, B] to be added. + Returns: + Tensor containing element-wise sums. + """ + with DeterministicContext(): + A, B, output = data + output[...] = A + B + return output + + +def generate_input(size: int, seed: int) -> input_t: + """ + Generates random input tensors of specified shapes. + Returns: + Tuple of tensors [A, B] to be added. + """ + gen = torch.Generator(device="cuda") + gen.manual_seed(seed) + A = torch.randn( + size, size, device="cuda", dtype=torch.float16, generator=gen + ).contiguous() + B = torch.randn( + size, size, device="cuda", dtype=torch.float16, generator=gen + ).contiguous() + C = torch.empty(size, size, device="cuda", dtype=torch.float16).contiguous() + return A, B, C + + +check_implementation = make_match_reference_exact(ref_kernel) diff --git a/problems/pmpp_v3/vectoradd_py/solutions/correct/submission_cuda_inline.py b/problems/pmpp_v3/vectoradd_py/solutions/correct/submission_cuda_inline.py new file mode 100644 index 000000000..ecd070b49 --- /dev/null +++ b/problems/pmpp_v3/vectoradd_py/solutions/correct/submission_cuda_inline.py @@ -0,0 +1,84 @@ +import torch +from torch.utils.cpp_extension import load_inline +from typing import List +from task import input_t, output_t + +add_cuda_source = """ +template +__global__ void add_kernel(const scalar_t* __restrict__ A, + const scalar_t* __restrict__ B, + scalar_t* __restrict__ C, + int N) { + int idx = blockIdx.x * blockDim.x + threadIdx.x; + + if (idx < N) { + C[idx] = A[idx] + B[idx]; + } +} + +torch::Tensor add_cuda(torch::Tensor A, torch::Tensor B, torch::Tensor C) { + TORCH_CHECK(A.device().is_cuda(), "Tensor A must be a CUDA tensor"); + TORCH_CHECK(B.device().is_cuda(), "Tensor B must be a CUDA tensor"); + TORCH_CHECK(C.device().is_cuda(), "Tensor C must be a CUDA tensor"); + TORCH_CHECK(A.sizes() == B.sizes(), "Input tensors must have the same size"); + + int N = A.numel(); + + const int threads = 256; + const int blocks = (N + threads - 1) / threads; + + AT_DISPATCH_FLOATING_TYPES_AND_HALF(A.scalar_type(), "add_kernel", ([&] { + add_kernel<<>>( + A.data_ptr(), + B.data_ptr(), + C.data_ptr(), + N + ); + })); + + cudaError_t err = cudaGetLastError(); + if (err != cudaSuccess) { + throw std::runtime_error(cudaGetErrorString(err)); + } + + return C; +} +""" + +add_cpp_source = """ +#include + +torch::Tensor add_cuda(torch::Tensor A, torch::Tensor B, torch::Tensor C); +""" + +add_module = load_inline( + name='add_cuda', + cpp_sources=add_cpp_source, + cuda_sources=add_cuda_source, + functions=['add_cuda'], + verbose=True, +) + +def add(A, B, C): + if not A.is_cuda or not B.is_cuda or not C.is_cuda: + raise RuntimeError("All tensors must be on GPU") + return add_module.add_cuda(A, B, C) + +def custom_kernel(data: input_t) -> output_t: + """ + Custom implementation of vector addition using CUDA. + Args: + inputs: List of pairs of tensors [A, B] to be added. + Returns: + Tensor containing element-wise sum. + """ + A, B, C = data + + assert A.is_cuda and B.is_cuda and C.is_cuda, "Input/output tensors must be on GPU" + assert A.shape == B.shape, "Input tensors must have the same shape" + assert C.shape == A.shape, "Output tensor and input tensors must have the same shape" + assert A.dtype == torch.float16 and B.dtype == torch.float16 and C.dtype == torch.float16, "Input/output tensors must be float16" + + # Simply reuse the existing add function we already defined + # This avoids the compilation issues with the inline kernel + return add(A, B, C) diff --git a/problems/pmpp_v3/vectoradd_py/solutions/correct/submission_mojo.py b/problems/pmpp_v3/vectoradd_py/solutions/correct/submission_mojo.py new file mode 100644 index 000000000..526c4ac70 --- /dev/null +++ b/problems/pmpp_v3/vectoradd_py/solutions/correct/submission_mojo.py @@ -0,0 +1,109 @@ +#!POPCORN leaderboard vectoradd_v3 +from pathlib import Path + +import mojo.importer # noqa: F401 +import torch +from task import input_t, output_t + +MOJO_SOURCE = """ +from std.math import ceildiv +from std.memory import Pointer +from std.os import abort +from std.python import PythonObject +from std.python.bindings import PythonModuleBuilder +from max.gpu import global_idx +from max.gpu.host import DeviceContext +from layout import RowMajorLayout, TileTensor, row_major + +comptime BLOCK = 256 +comptime Layout1D = RowMajorLayout[Int] + + +def add_kernel( + a: TileTensor[.float16, Layout1D, ImmUntrackedOrigin], + b: TileTensor[.float16, Layout1D, ImmUntrackedOrigin], + c: TileTensor[.float16, Layout1D, MutUntrackedOrigin], + n: Int32, +): + var idx = Int32(global_idx.x) + if idx < n: + c[idx] = a[idx] + b[idx] + + +@fieldwise_init +struct Runner(Movable, Writable): + var ctx: DeviceContext + var func: type_of(DeviceContext().compile_function[add_kernel]()) + + def write_repr_to(self, mut writer: Some[Writer]): + writer.write("Runner()") + + @staticmethod + def py_init(out self: Self, args: PythonObject, kwargs: PythonObject) raises: + var ctx = DeviceContext() + var func = ctx.compile_function[add_kernel]() + self = Self(ctx^, func^) + + @staticmethod + def launch( + self_ptr: Pointer[Self, MutAnyOrigin], + a_py: PythonObject, + b_py: PythonObject, + c_py: PythonObject, + n_py: PythonObject, + ) raises: + var n = Int(py=n_py) + var a = TileTensor( + Pointer[Float16, ImmUntrackedOrigin](unsafe_from_address=Int(py=a_py)), + row_major(n), + ) + var b = TileTensor( + Pointer[Float16, ImmUntrackedOrigin](unsafe_from_address=Int(py=b_py)), + row_major(n), + ) + var c = TileTensor( + Pointer[Float16, MutUntrackedOrigin](unsafe_from_address=Int(py=c_py)), + row_major(n), + ) + self_ptr[].ctx.enqueue_function( + self_ptr[].func, + a, + b, + c, + Int32(n), + grid_dim=ceildiv(n, BLOCK), + block_dim=BLOCK, + ) + + +@export +def PyInit_mojo_vecadd() abi("C") -> PythonObject: + try: + var mb = PythonModuleBuilder("mojo_vecadd") + _ = ( + mb.add_type[Runner]("Runner") + .def_py_init[Runner.py_init]() + .def_method[Runner.launch]("launch") + ) + return mb.finalize() + except e: + abort(t"Failed to initialize mojo_vecadd: {e}") +""" + +# Compiled by mojo.importer on first import and cached in __mojocache__ next to +# the source, so the evaluator's worker processes reuse one build. +(Path(__file__).resolve().parent / "mojo_vecadd.mojo").write_text(MOJO_SOURCE) +import mojo_vecadd # noqa: E402 + +_RUNNER = mojo_vecadd.Runner() + + +def custom_kernel(data: input_t) -> output_t: + A, B, C = data + _RUNNER.launch( + A.data_ptr(), + B.data_ptr(), + C.data_ptr(), + A.numel(), + ) + return C diff --git a/problems/pmpp_v3/vectoradd_py/solutions/correct/submission_triton.py b/problems/pmpp_v3/vectoradd_py/solutions/correct/submission_triton.py new file mode 100644 index 000000000..7ae0a250d --- /dev/null +++ b/problems/pmpp_v3/vectoradd_py/solutions/correct/submission_triton.py @@ -0,0 +1,38 @@ +#!POPCORN leaderboard vectoradd_v3 + +import torch +import triton +import triton.language as tl +from task import input_t, output_t + + +@triton.jit +def add_kernel( + A_ptr, B_ptr, C_ptr, M, N, + BLOCK_SIZE: tl.constexpr, +): + row_idx = tl.program_id(0) * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE) + col_idx = tl.program_id(1) * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE) + + mask_row = row_idx < M + mask_col = col_idx < N + + A = tl.load(A_ptr + row_idx[:, None] * N + col_idx[None, :], mask=mask_row[:, None] & mask_col[None, :], other=0.0) + B = tl.load(B_ptr + row_idx[:, None] * N + col_idx[None, :], mask=mask_row[:, None] & mask_col[None, :], other=0.0) + + C = A + B + tl.store(C_ptr + row_idx[:, None] * N + col_idx[None, :], C, mask=mask_row[:, None] & mask_col[None, :]) + +def custom_kernel(data: input_t) -> output_t: + A, B, C = data + M, N = A.shape + + BLOCK_SIZE = 32 + grid = (triton.cdiv(M, BLOCK_SIZE), triton.cdiv(N, BLOCK_SIZE)) + + add_kernel[grid]( + A, B, C, M, N, + BLOCK_SIZE=BLOCK_SIZE, + ) + + return C diff --git a/problems/pmpp_v3/vectoradd_py/submission.py b/problems/pmpp_v3/vectoradd_py/submission.py new file mode 100644 index 000000000..918a1eb89 --- /dev/null +++ b/problems/pmpp_v3/vectoradd_py/submission.py @@ -0,0 +1,7 @@ +from task import input_t, output_t + + +def custom_kernel(data: input_t) -> output_t: + A, B, output = data + output[...] = A + B + return output diff --git a/problems/pmpp_v3/vectoradd_py/task.py b/problems/pmpp_v3/vectoradd_py/task.py new file mode 100644 index 000000000..a630cff73 --- /dev/null +++ b/problems/pmpp_v3/vectoradd_py/task.py @@ -0,0 +1,11 @@ +from typing import TypedDict, TypeVar +import torch + + +input_t = TypeVar("input_t", bound=tuple[torch.Tensor, torch.Tensor]) +output_t = TypeVar("output_t", bound=torch.Tensor) + + +class TestSpec(TypedDict): + size: int + seed: int diff --git a/problems/pmpp_v3/vectoradd_py/task.yml b/problems/pmpp_v3/vectoradd_py/task.yml new file mode 100644 index 000000000..6d3f0ff6b --- /dev/null +++ b/problems/pmpp_v3/vectoradd_py/task.yml @@ -0,0 +1,44 @@ +# name: vectoradd-cuda-inline + +files: + - {"name": "submission.py", "source": "@SUBMISSION@"} + - {"name": "task.py", "source": "task.py"} + - {"name": "utils.py", "source": "../utils.py"} + - {"name": "reference.py", "source": "reference.py"} + - {"name": "eval.py", "source": "../eval.py"} + +lang: "py" + +description: | + Return a plain, materialized torch.Tensor. Tensor subclasses and deferred + computation during checking are not allowed; compute the result inside custom_kernel. + + Implement a float16 vector addition kernel. + + Input: tuple(torch.Tensor, torch.Tensor) with tensors of shape (N, N) and type torch.float16. These tensors are from + a normal distribution with mean 0 and variance 1. + Output: torch.Tensor of shape (N, N) and type torch.float16 + +config: + main: "eval.py" + +templates: + Python: "../template.py" + +tests: + - {"size": 127, "seed": 4242} + - {"size": 128, "seed": 5236} + - {"size": 129, "seed": 1001} + - {"size": 256, "seed": 5531} + - {"size": 512, "seed": 9173} + +benchmarks: + - {"size": 1024, "seed": 31232} + - {"size": 2048, "seed": 4052} + - {"size": 4096, "seed": 2146} + - {"size": 8192, "seed": 3129} + - {"size": 16384, "seed": 54352} + +test_timeout: 180 +benchmark_timeout: 180 +ranked_timeout: 420 diff --git a/problems/pmpp_v3/vectorsum_py/reference.py b/problems/pmpp_v3/vectorsum_py/reference.py new file mode 100644 index 000000000..313749e15 --- /dev/null +++ b/problems/pmpp_v3/vectorsum_py/reference.py @@ -0,0 +1,55 @@ +from utils import make_match_reference, DeterministicContext +import torch +from task import input_t, output_t + + +def ref_kernel(data: input_t) -> output_t: + """ + Reference implementation of vector sum reduction using PyTorch. + Args: + data: Input tensor to be reduced + Returns: + Tensor containing the sum of all elements + """ + with DeterministicContext(): + data, output = data + # Let's be on the safe side here, and do the reduction in 64 bit + output = data.to(torch.float64).sum().to(torch.float32) + return output + + +def generate_input(size: int, seed: int) -> input_t: + """ + Generates random input tensor of specified shape with random offset and scale. + The data is first generated as standard normal, then scaled and offset + to prevent trivial solutions. + + Returns: + Tensor to be reduced + """ + gen = torch.Generator(device="cuda") + gen.manual_seed(seed) + + # Generate base random data + data = torch.randn( + size, device="cuda", dtype=torch.float32, generator=gen + ).contiguous() + + # Generate random offset and scale (using different seeds to avoid correlation) + offset_gen = torch.Generator(device="cuda") + offset_gen.manual_seed(seed + 1) + scale_gen = torch.Generator(device="cuda") + scale_gen.manual_seed(seed + 2) + + # Generate random offset between -100 and 100 + offset = (torch.rand(1, device="cuda", generator=offset_gen) * 200 - 100).item() + # Generate random scale between 0.1 and 10 + scale = (torch.rand(1, device="cuda", generator=scale_gen) * 9.9 + 0.1).item() + + # Apply scale and offset + input_tensor = (data * scale + offset).contiguous() + output_tensor = torch.empty(1, device="cuda", dtype=torch.float32) + return input_tensor, output_tensor + + +check_implementation = make_match_reference(ref_kernel) diff --git a/problems/pmpp_v3/vectorsum_py/solutions/correct/pytorch.py b/problems/pmpp_v3/vectorsum_py/solutions/correct/pytorch.py new file mode 100644 index 000000000..89400913e --- /dev/null +++ b/problems/pmpp_v3/vectorsum_py/solutions/correct/pytorch.py @@ -0,0 +1,12 @@ +import torch +from task import input_t, output_t + + +def _custom_kernel(data: input_t) -> output_t: + data, output = data + output[...] = data.sum() + return output + + +# Compile the kernel for better performance +custom_kernel = torch.compile(_custom_kernel, mode="reduce-overhead") diff --git a/problems/pmpp_v3/vectorsum_py/solutions/wrong/cheat.py b/problems/pmpp_v3/vectorsum_py/solutions/wrong/cheat.py new file mode 100644 index 000000000..83e4f6c78 --- /dev/null +++ b/problems/pmpp_v3/vectorsum_py/solutions/wrong/cheat.py @@ -0,0 +1,16 @@ +import torch +from task import input_t, output_t + + +def _custom_kernel(data: input_t) -> output_t: + data, output = data + n_in = data.numel() + if n_in > 1_000_000: + cheat = n_in // 99 * 100 + else: + cheat = n_in + return data[:cheat].sum() * n_in / cheat + + +# Compile the kernel for better performance +custom_kernel = torch.compile(_custom_kernel, mode="reduce-overhead") diff --git a/problems/pmpp_v3/vectorsum_py/submission.py b/problems/pmpp_v3/vectorsum_py/submission.py new file mode 100644 index 000000000..165a623cb --- /dev/null +++ b/problems/pmpp_v3/vectorsum_py/submission.py @@ -0,0 +1,62 @@ +#!POPCORN leaderboard vectorsum_v3 + +import torch +import triton +import triton.language as tl +from task import input_t, output_t + + +@triton.jit +def sum_kernel( + x_ptr, + output_ptr, + n_elements, + BLOCK_SIZE: tl.constexpr, +): + """ + Parallel reduction kernel that sums elements in chunks. + Each thread block reduces BLOCK_SIZE elements. + """ + pid = tl.program_id(0) + block_start = pid * BLOCK_SIZE + offsets = block_start + tl.arange(0, BLOCK_SIZE) + mask = offsets < n_elements + + # Load data + x = tl.load(x_ptr + offsets, mask=mask, other=0.0) + + # Compute local reduction + block_sum = tl.sum(x, axis=0) + + # Store the partial sum + tl.atomic_add(output_ptr, block_sum) + + +def _custom_kernel(data: input_t) -> output_t: + """ + Performs parallel reduction to compute sum of all elements. + Args: + data: Input tensor to be reduced + Returns: + Tensor containing the sum of all elements + """ + data, output = data + n_elements = data.numel() + + # Configure kernel + BLOCK_SIZE = 1024 + grid = (triton.cdiv(n_elements, BLOCK_SIZE),) + + # Launch kernel + sum_kernel[grid]( + data, + output, + n_elements, + BLOCK_SIZE=BLOCK_SIZE, + ) + + return output[0] + + +# Compile the kernel for better performance +custom_kernel = torch.compile(_custom_kernel, mode="reduce-overhead") diff --git a/problems/pmpp_v3/vectorsum_py/task.py b/problems/pmpp_v3/vectorsum_py/task.py new file mode 100644 index 000000000..2d48268bf --- /dev/null +++ b/problems/pmpp_v3/vectorsum_py/task.py @@ -0,0 +1,9 @@ +from typing import TypedDict, TypeVar +import torch + +input_t = TypeVar("input_t", bound=tuple[torch.Tensor, torch.Tensor]) +output_t = TypeVar("output_t", bound=torch.Tensor) + +class TestSpec(TypedDict): + size: int + seed: int diff --git a/problems/pmpp_v3/vectorsum_py/task.yml b/problems/pmpp_v3/vectorsum_py/task.yml new file mode 100644 index 000000000..107828f7b --- /dev/null +++ b/problems/pmpp_v3/vectorsum_py/task.yml @@ -0,0 +1,44 @@ +# name: vectorsum-cuda-inline + +files: + - {"name": "submission.py", "source": "@SUBMISSION@"} + - {"name": "task.py", "source": "task.py"} + - {"name": "utils.py", "source": "../utils.py"} + - {"name": "reference.py", "source": "reference.py"} + - {"name": "eval.py", "source": "../eval.py"} + +lang: "py" + +description: | + Return a plain, materialized torch.Tensor. Tensor subclasses and deferred + computation during checking are not allowed; compute the result inside custom_kernel. + + Implement a vector sum reduction kernel. This kernel computes the sum of all elements in the input tensor. + + Input: A tensor of shape `(N,)` with values from a normal distribution with mean 0 and variance 1. + Output: A scalar value equal to the sum of all elements in the input tensor. + +config: + main: "eval.py" + +templates: + Python: "../template.py" + +tests: + - {"size": 1023, "seed": 4242} + - {"size": 1024, "seed": 5236} + - {"size": 1025, "seed": 1001} + - {"size": 2048, "seed": 5531} + - {"size": 4096, "seed": 9173} + +benchmarks: + - {"size": 1638400, "seed": 93246} + - {"size": 3276800, "seed": 6256} + - {"size": 6553600, "seed": 8841} + - {"size": 13107200, "seed": 6252} + - {"size": 26214400, "seed": 82135} + - {"size": 52428800, "seed": 12345} + +test_timeout: 180 +benchmark_timeout: 180 +ranked_timeout: 420 diff --git a/tests/pmpp_v2/conftest.py b/tests/pmpp_v2/conftest.py index d4b90aa50..8f416f722 100644 --- a/tests/pmpp_v2/conftest.py +++ b/tests/pmpp_v2/conftest.py @@ -6,7 +6,7 @@ import pytest import torch -ROOT = Path(__file__).resolve().parents[2] / "problems" / "pmpp_v2" +PROBLEM_SETS = ("pmpp_v2", "pmpp_v3") PROBLEMS = ( "sort", "prefixsum", @@ -28,11 +28,11 @@ def load_module(name, path): @pytest.fixture -def load_problem(): - utils = load_module("pmpp_test_utils", ROOT / "utils.py") +def load_problem(problem_root): + utils = load_module("pmpp_test_utils", problem_root / "utils.py") def load(name): - folder = ROOT / f"{name}_py" + folder = problem_root / f"{name}_py" task = load_module(f"pmpp_test_{name}_task", folder / "task.py") with patch.dict(sys.modules, {"task": task, "utils": utils}): return load_module(f"pmpp_test_{name}_reference", folder / "reference.py") @@ -40,6 +40,11 @@ def load(name): return load +@pytest.fixture(params=PROBLEM_SETS) +def problem_root(request): + return Path(__file__).resolve().parents[2] / "problems" / request.param + + @pytest.fixture def examples(): gen = torch.Generator().manual_seed(72) diff --git a/tests/pmpp_v2/test_checkers.py b/tests/pmpp_v2/test_checkers.py index ca6cf484c..98f300993 100644 --- a/tests/pmpp_v2/test_checkers.py +++ b/tests/pmpp_v2/test_checkers.py @@ -3,7 +3,7 @@ import pytest import torch import yaml -from conftest import PROBLEMS, ROOT +from conftest import PROBLEMS @pytest.mark.parametrize("problem", PROBLEMS) @@ -148,9 +148,11 @@ def test_prefix_sum_tolerance_tracks_input_energy(load_problem): @pytest.mark.parametrize("problem", ("sort", "prefixsum")) -def test_all_configured_cases_generate_and_reference_passes(problem, load_problem): +def test_all_configured_cases_generate_and_reference_passes( + problem, load_problem, problem_root +): ref = load_problem(problem) - task = yaml.safe_load((ROOT / f"{problem}_py" / "task.yml").read_text()) + task = yaml.safe_load((problem_root / f"{problem}_py" / "task.yml").read_text()) for case in task["tests"]: data = ref.generate_input(**case, device="cpu") expected = ref.ref_kernel(data).clone() From 6ef360de4aebf7f990cec8631c5b709b95bff2bc Mon Sep 17 00:00:00 2001 From: Mark Saroufim Date: Mon, 30 Nov 2026 20:28:02 -0800 Subject: [PATCH 2/2] Return a scalar from the v3 vector sum example --- problems/pmpp_v3/vectorsum_py/solutions/correct/pytorch.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/pmpp_v3/vectorsum_py/solutions/correct/pytorch.py b/problems/pmpp_v3/vectorsum_py/solutions/correct/pytorch.py index 89400913e..82a6c7537 100644 --- a/problems/pmpp_v3/vectorsum_py/solutions/correct/pytorch.py +++ b/problems/pmpp_v3/vectorsum_py/solutions/correct/pytorch.py @@ -5,7 +5,7 @@ def _custom_kernel(data: input_t) -> output_t: data, output = data output[...] = data.sum() - return output + return output.squeeze(0) # Compile the kernel for better performance