Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
110 changes: 110 additions & 0 deletions examples/vectoradd_py/submission_mojo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
#!POPCORN leaderboard vectoradd_py-dev
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 = data
C = torch.empty_like(A)
_RUNNER.launch(
A.data_ptr(),
B.data_ptr(),
C.data_ptr(),
A.numel(),
)
return C
18 changes: 16 additions & 2 deletions src/kernelbot/cogs/leaderboard_cog.py
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,14 @@ async def lang_autocomplete(


def add_header_to_template(lang: str, code: str, lb: LeaderboardItem):
comment_char = {"CUDA": "//", "Python": "#", "Triton": "#", "HIP": "#", "CuteDSL": "#"}[lang]
comment_char = {
"CUDA": "//",
"Python": "#",
"Triton": "#",
"HIP": "#",
"CuteDSL": "#",
"Mojo": "#",
}[lang]

description_comment = [f"{comment_char} > {line}" for line in lb["description"].splitlines()]
header = f"""
Expand Down Expand Up @@ -548,7 +555,14 @@ async def get_task_template(
return

template = add_header_to_template(lang, templates[lang], leaderboard_item)
ext = {"CUDA": "cu", "Python": "py", "Triton": "py", "HIP": "py", "CuteDSL": "py"}
ext = {
"CUDA": "cu",
"Python": "py",
"Triton": "py",
"HIP": "py",
"CuteDSL": "py",
"Mojo": "py",
}
file_name = f"{leaderboard_name}.{ext[lang]}"
file = discord.File(fp=StringIO(template), filename=file_name)
message = f"**Starter code for leaderboard `{leaderboard_name}`**\n"
Expand Down
20 changes: 12 additions & 8 deletions src/libkernelbot/run_eval.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import base64
import contextlib
import copy
import dataclasses
import datetime
Expand Down Expand Up @@ -742,10 +743,17 @@ def run_pytorch_script( # noqa: C901
RunResult
"""
start = datetime.datetime.now()
try:
assert main in sources.keys()

# Write submission files to directory
assert main in sources.keys()
# Submissions may write next to themselves (e.g. Mojo sources and their
# __mojocache__). Modal reuses warm containers across users, so each run
# gets a private working directory that is deleted afterwards. CPU-artifact
# replay already provides one, and checks header dependencies against it.
inline_workdir = os.environ.get("KERNELBOT_INLINE_WORKDIR")
with (
contextlib.nullcontext(inline_workdir)
if inline_workdir
else tempfile.TemporaryDirectory(prefix="kernelbot-run-", ignore_cleanup_errors=True)
) as workdir, contextlib.chdir(workdir):
_create_files(sources)

# "compile" step: execute the script once. Will populate
Expand Down Expand Up @@ -786,10 +794,6 @@ def run_pytorch_script( # noqa: C901
run=run,
profile=profile,
)
finally:
for f in sources.keys():
if os.path.exists(f):
os.remove(f)


class _EvalRunner(Protocol):
Expand Down
2 changes: 1 addition & 1 deletion src/libkernelbot/task.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ def make_task_definition(yaml_file: str | Path) -> LeaderboardDefinition: # noq
# load template files
templates = {}
for lang, source in raw.get("templates", {}).items():
assert lang in ["CUDA", "Python", "Triton", "HIP", "CuteDSL"]
assert lang in ["CUDA", "Python", "Triton", "HIP", "CuteDSL", "Mojo"]
templates[lang] = (root / source).read_text()

if templates:
Expand Down
6 changes: 5 additions & 1 deletion src/runners/modal_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,9 @@
.uv_pip_install(
"tinygrad~=0.10",
"helion",
# Mojo compiler, `mojo.importer`, and the MAX GPU libraries. Pinned because
# Mojo syntax still changes between releases and would break submissions.
"max==26.7.0",
)
# nvidia cuda packages
.uv_pip_install(
Expand Down Expand Up @@ -115,8 +118,9 @@
)
.run_commands(
"python -m pip check",
'python -c "import cuda.tile, nvmath"',
'python -c "import cuda.tile, nvmath, mojo.importer"',
"tileiras --version",
"mojo --version",
(
"printf '#include <cublasdx.hpp>\\n' | "
"nvcc -std=c++17 -x cu -c - -o /tmp/cublasdx-smoke.o && "
Expand Down
36 changes: 36 additions & 0 deletions tests/test_api_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import io
from unittest.mock import MagicMock

import pytest
from fastapi import HTTPException, UploadFile


async def submit(project_root, code: bytes):
# Importing at collection time would load kernelbot.env before test_admin_api patches it.
from kernelbot.api.api_utils import to_submit_info

db = MagicMock()
db.__enter__.return_value.get_leaderboard.return_value = {"gpu_types": ["H100"]}
return await to_submit_info(
{"user_name": "user", "user_id": "1", "id_type": "cli"},
"leaderboard",
UploadFile(io.BytesIO(code), filename="submission_mojo.py"),
"vectoradd_py-dev",
"H100",
db,
)


@pytest.mark.asyncio
async def test_mojo_example_passes_submission_filters(project_root):
code = (project_root / "examples" / "vectoradd_py" / "submission_mojo.py").read_bytes()

request, _ = await submit(project_root, code)

assert request.code == code.decode()


@pytest.mark.asyncio
async def test_submissions_mentioning_streams_are_rejected(project_root):
with pytest.raises(HTTPException, match="another stream"):
await submit(project_root, b"s = torch.cuda.current_stream()\n")
78 changes: 78 additions & 0 deletions tests/test_modal.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,7 @@ def modal_deployment(project_root: Path):
[
("vectoradd_py", "submission_cuda_inline.py"),
("vectoradd_py", "submission_triton.py"),
("vectoradd_py", "submission_mojo.py"),
],
)
async def test_modal_launcher_python_script(
Expand Down Expand Up @@ -414,3 +415,80 @@ async def test_modal_launcher_failing_script(modal_deployment, project_root: Pat
assert result.success, f"Expected successful run, got: {result.error}"
assert result.error == ""
assert result.runs["test"].run.passed is False or result.runs["benchmark"].run.passed is False


@pytest.mark.integration
@pytest.mark.asyncio
async def test_modal_mojo_leaderboard(modal_deployment, project_root: Path):
"""A Mojo submission goes through test, benchmark and ranked runs with honest timings."""
launcher = ModalLauncher(add_include_dirs=[])
gpu_type = ModalGPU.H100
task_path = project_root / "examples" / "vectoradd_py"
task_definition = make_task_definition(task_path)
config = build_task_config(
task=task_definition.task,
submission_content=(task_path / "submission_mojo.py").read_text(),
arch=GPU_TO_SM[gpu_type.name],
mode=SubmissionMode.LEADERBOARD,
)

result = await launcher.run_submission(config, gpu_type, MockProgressReporter())

assert result.success, result.error
for name in ("test", "benchmark", "leaderboard"):
run = result.runs[name].run
assert run.passed, f"{name}: {run.stderr}"
# Ranked runs time only the largest case: 16384^2 fp16 values, read twice and written
# once. Events that missed the Mojo kernel would report far less than H100's
# bandwidth allows.
moved_bytes = 3 * 16384 * 16384 * 2
mean_ns = float(result.runs["leaderboard"].run.result["benchmark.0.mean"])
assert mean_ns > moved_bytes / 4e12 * 1e9


MOJO_ORDERING_CHECK = """
import os

import torch
from submission import custom_kernel

n = 4096
A = torch.empty(n, n, device="cuda", dtype=torch.float16)
B = torch.empty_like(A)
# Delay PyTorch's queue so a kernel that does not wait for it reads stale inputs.
torch.cuda._sleep(200_000_000)
A.fill_(1)
B.fill_(2)
C = custom_kernel((A, B))
ok = bool((C == 3).all())

with os.fdopen(int(os.environ["POPCORN_FD"]), "w") as out:
out.write("check: " + ("pass" if ok else "fail") + "\\n")
"""


@pytest.mark.integration
@pytest.mark.asyncio
async def test_modal_mojo_is_ordered_with_torch(modal_deployment, project_root: Path):
"""Submissions may not name streams, so Mojo launches on its own queue. It must still
wait for, and be waited on by, work on PyTorch's default stream."""
launcher = ModalLauncher(add_include_dirs=[])
task_path = project_root / "examples" / "vectoradd_py"
config = {
"lang": "py",
"main": "eval.py",
"mode": SubmissionMode.TEST.value,
"arch": GPU_TO_SM[ModalGPU.H100.name],
"tests": [{"size": 1}],
"sources": {
"eval.py": MOJO_ORDERING_CHECK,
"submission.py": (task_path / "submission_mojo.py").read_text(),
"task.py": (task_path / "task.py").read_text(),
},
}

result = await launcher.run_submission(config, ModalGPU.H100, MockProgressReporter())

assert result.success, result.error
run = result.runs["test"].run
assert run.passed, run.stderr
51 changes: 51 additions & 0 deletions tests/test_run_eval.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
from pathlib import Path

from libkernelbot.run_eval import SystemInfo, run_pytorch_script

EVAL_WRITES_NEXT_TO_ITSELF = """
import os
from pathlib import Path

Path("kernel.mojo").write_text("previous user's kernel")
Path("__mojocache__").mkdir()
with os.fdopen(int(os.environ["POPCORN_FD"]), "w") as out:
out.write(f"check: pass\\ncwd: {os.getcwd()}\\n")
"""


def test_python_submission_runs_in_private_directory(tmp_path, monkeypatch):
monkeypatch.chdir(tmp_path)

result = run_pytorch_script(
sources={"eval.py": EVAL_WRITES_NEXT_TO_ITSELF, "submission.py": ""},
main="eval.py",
mode="test",
system=SystemInfo(),
tests="size: 1\n",
)

assert result.run.passed, result.run.stderr
run_dir = Path(result.run.result["cwd"])
assert run_dir.resolve() != tmp_path.resolve()
assert not run_dir.exists()
assert list(tmp_path.iterdir()) == []
assert Path.cwd() == tmp_path


def test_python_submission_reuses_cpu_artifact_directory(tmp_path, monkeypatch):
work = tmp_path / "work"
work.mkdir()
monkeypatch.chdir(tmp_path)
monkeypatch.setenv("KERNELBOT_INLINE_WORKDIR", str(work))

result = run_pytorch_script(
sources={"eval.py": EVAL_WRITES_NEXT_TO_ITSELF, "submission.py": ""},
main="eval.py",
mode="test",
system=SystemInfo(),
tests="size: 1\n",
)

assert result.run.passed, result.run.stderr
assert Path(result.run.result["cwd"]).resolve() == work.resolve()
assert Path.cwd() == tmp_path
Loading
Loading