{"items":[{"created_at":"2026-10-25T03:52:20.732000+00:00","type":"general","test_cases":[{"test":"A = chr(10) + ''.join(chr(c) for c in range(32, 127))\nm = train('hello world. ' * 60, A, 8.0)\ns = init_state(m, 3)\nprint(len(tuple(s.shape)) == 2 and tuple(s.shape)[0] == 3)","expected_output":"True"},{"test":"import numpy as np\nA = chr(10) + ''.join(chr(c) for c in range(32, 127))\nm = train('hello world. ' * 60, A, 8.0)\nlp, s = step(m, init_state(m, 2), [-1, -1])\na = lp.detach().cpu().numpy() if hasattr(lp, 'detach') else np.asarray(lp)\nprint(a.shape == (2, 96) and float(np.abs(np.log(np.exp(a.astype('float64')).sum(1))).max()) < 1e-3)","expected_output":"True"},{"test":"import numpy as np\nA = chr(10) + ''.join(chr(c) for c in range(32, 127))\nm = train('hello world. ' * 60, A, 8.0)\ns0 = init_state(m, 1)\n_, s1 = step(m, s0, [A.index('h')])\n_, s2 = step(m, s1, [A.index('e')])\nf = lambda x: x.detach().cpu().numpy() if hasattr(x, 'detach') else np.asarray(x)\nprint(not np.allclose(f(s1).astype('float64'), f(s2).astype('float64')))","expected_output":"True"},{"test":"import numpy as np\nA = chr(10) + ''.join(chr(c) for c in range(32, 127))\nm = train('hello world. ' * 60, A, 8.0)\nf = lambda x: x.detach().cpu().numpy() if hasattr(x, 'detach') else np.asarray(x)\na, _ = step(m, init_state(m, 1), [A.index('h')])\nb, _ = step(m, init_state(m, 1), [A.index('w')])\nprint(float(np.abs(f(a) - f(b)).max()) > 1e-4)","expected_output":"True"}],"lower_is_better":true,"approved_user_libraries":["numpy","torch","triton","math","collections","itertools","functools","random","time"],"data_info":"TinyStories validation text with planted recall: every story's character names are replaced by fresh made-up names and each ~3,000-character document opens with a random six-letter code and repeats it at the end. Submit: train on characters 6,000,000-16,000,000 (about 10 million characters after the transform, 240 s on a T4), score 48 documents built from characters 17,000,000-17,800,000. Run: train on 0-1,500,000 for 90 s, score 32 documents of about 1,500 characters from 2,000,000-2,200,000. The report shows the score, text_bpc, recall_bpc, overall bits per character, the state size and the time used.","time_limits":{"test":600,"dev":360},"example":{"input":"model = train(text, alphabet, 240.0); state = init_state(model, 48); logprobs, state = step(model, state, prev)","output":"logprobs: (48, 96) normalised log-probabilities for the next character of each document; state: (48, S) with S * itemsize <= 131072 bytes"},"gpu":true,"description":"Mamba asked one question: can a model that carries a **fixed-size memory** from token to token, so it runs in linear time with constant memory per sequence, match attention on language, including the part attention is best at, recalling something seen far back? Build the best character-level language model you can under that constraint. Any design counts: a selective state space model, a gated RNN, linear attention, a sliding window that fits the cap, an n-gram mixed with a learned memory, or something new. The leaderboard ranks by **score**, lower is better.\n\n**Data.** TinyStories, with recall planted in it. Every character in every story gets a fresh made-up name (so a name can only be predicted by remembering it), and every document starts with a random six-letter code (`Code: qzvmxa.`) and ends by repeating it (`The code was qzvmxa.`) about 3,000 characters later. `train` receives about 10 million characters built the same way from a different part of the corpus. The alphabet is fixed: newline plus the 95 printable ASCII characters (anything else is mapped to `?`).\n\n**Contract.** Implement three functions:\n\n- `train(text: str, alphabet: str, budget_seconds: float) -> model` returns any object. Submit gives a 240-second wall-clock budget on a T4 GPU.\n- `init_state(model, batch_size: int) -> state` returns the memory for `batch_size` fresh documents: a **2-D numpy array or torch tensor of shape `(batch_size, S)`**, any dtype.\n- `step(model, state, prev: list[int]) -> (logprobs, state)`: `prev[b]` is the alphabet index of the previous character of document `b`, or `-1` at the start of a document. Return log-probabilities of shape `(batch_size, 96)` (numpy or torch) for the next character, one normalised distribution per row, and the new state.\n\nThe harness scores 48 documents in parallel, one character at a time. Before every call it **shuffles the rows** of the batch and of your state together, so everything a document needs must travel in its own row of the state.\n\n**Score.** text bits per character = average -log2 p over ordinary characters; recall bits per character = the same over characters only memory can predict (every repeat mention of a name and the final code). **score = (text + recall) / 2.** The report also shows overall bits per character, the state size and the time used. Clearing 3.0 counts as solved; everything below that is leaderboard.\n\n**Gates.** The score is set to 99.0 (a fail) if: the state is not a 2-D array or tensor with one row per document; the state ever holds more than **131,072 bytes per document** (32,768 float32 values); any log-probability is non-finite or positive, or a row is not normalised (logsumexp within 1e-3 of 0); `train` exceeds its budget or scoring takes over 120 seconds; or the same document scored twice (fresh, and after another document) gets different log-probabilities, which catches memory kept outside the state and nondeterminism.\n\n**New to this?** The learn section walks through a first submission step by step: a plain two-layer GRU that scores about 1.7, well inside the floor, without a line of code.\n\n**Run vs Submit.** Run trains on about 1.5 million characters for 90 seconds and scores 32 documents of about 1,500 characters; Submit uses the full budget and 48 documents of about 3,000 characters. Libraries: torch (including `torch.compile`), Triton for your own GPU kernels, numpy and the standard library; no pretrained weights.","tags":["mamba","state-space-models","recurrent","language-modeling","triton","open-ended","leaderboard"],"id":"00141453-bba9-434d-98e3-be380b4473fb","dataset_id":"tinystories","img_type":"triton","difficulty":"hard","evaluation_metric":"score","min_eval_metric":3.0,"category":"Language Modeling","title":"Best Language Model with a Fixed-Size Memory","dataset":"TinyStories (recall planted)","time_limits_seconds":{"dev":360,"test":600}},{"created_at":"2026-11-05T02:48:16.858000+00:00","type":"general","constraints":["train gets about 25 s and predict 40% of that, scaled to the machine's measured speed; a call more than 15% late scores 0","predict returns whole-number class ids 0 to 5, shape (len(images), 64, 64), as a numpy array","numpy, torch, scipy and scikit-learn on a Tesla T4; the harness owns all data access","at most 12000 characters of code, 300 numbers, 400 characters of strings, 200 defined names","attribute assignment only on self inside a method of a class"],"test_cases":[{"test":"import numpy as np\n_r = np.random.default_rng(0)\n_yy, _xx = np.mgrid[0:64, 0:64]\ndef _make(n):\n    X = _r.integers(0, 50, (n, 64, 64, 3)).astype(np.uint8)\n    Y = np.zeros((n, 64, 64), np.uint8)\n    for i in range(n):\n        cy, cx, s = _r.integers(14, 50), _r.integers(14, 50), _r.integers(6, 12)\n        if i % 2:\n            m = (_yy - cy) ** 2 + (_xx - cx) ** 2 <= s * s\n        else:\n            m = (abs(_yy - cy) <= s) & (abs(_xx - cx) <= s)\n        X[i][m] = _r.integers(120, 256, 3)\n        Y[i][m] = 1 if i % 2 else 3\n    return X, Y\ntry:\n    _p\nexcept NameError:\n    _Xa, _Ya = _make(400)\n    _Xb, _Yb = _make(60)\n    _m = train(_Xa, _Ya, 15.0)\n    _p = np.asarray(predict(_m, _Xb))\nprint(_p.shape)","expected_output":"(60, 64, 64)"},{"test":"import numpy as np\n_r = np.random.default_rng(0)\n_yy, _xx = np.mgrid[0:64, 0:64]\ndef _make(n):\n    X = _r.integers(0, 50, (n, 64, 64, 3)).astype(np.uint8)\n    Y = np.zeros((n, 64, 64), np.uint8)\n    for i in range(n):\n        cy, cx, s = _r.integers(14, 50), _r.integers(14, 50), _r.integers(6, 12)\n        if i % 2:\n            m = (_yy - cy) ** 2 + (_xx - cx) ** 2 <= s * s\n        else:\n            m = (abs(_yy - cy) <= s) & (abs(_xx - cx) <= s)\n        X[i][m] = _r.integers(120, 256, 3)\n        Y[i][m] = 1 if i % 2 else 3\n    return X, Y\ntry:\n    _p\nexcept NameError:\n    _Xa, _Ya = _make(400)\n    _Xb, _Yb = _make(60)\n    _m = train(_Xa, _Ya, 15.0)\n    _p = np.asarray(predict(_m, _Xb))\nprint(bool(np.all(_p == np.round(_p)) and _p.min() >= 0 and _p.max() <= 5))","expected_output":"True"},{"test":"import numpy as np\n_r = np.random.default_rng(0)\n_yy, _xx = np.mgrid[0:64, 0:64]\ndef _make(n):\n    X = _r.integers(0, 50, (n, 64, 64, 3)).astype(np.uint8)\n    Y = np.zeros((n, 64, 64), np.uint8)\n    for i in range(n):\n        cy, cx, s = _r.integers(14, 50), _r.integers(14, 50), _r.integers(6, 12)\n        if i % 2:\n            m = (_yy - cy) ** 2 + (_xx - cx) ** 2 <= s * s\n        else:\n            m = (abs(_yy - cy) <= s) & (abs(_xx - cx) <= s)\n        X[i][m] = _r.integers(120, 256, 3)\n        Y[i][m] = 1 if i % 2 else 3\n    return X, Y\ntry:\n    _p\nexcept NameError:\n    _Xa, _Ya = _make(400)\n    _Xb, _Yb = _make(60)\n    _m = train(_Xa, _Ya, 15.0)\n    _p = np.asarray(predict(_m, _Xb))\nprint(bool((_p[_Yb > 0] == _Yb[_Yb > 0]).mean() > 0.8))","expected_output":"True"}],"lower_is_better":false,"approved_user_libraries":["numpy","torch","scipy","sklearn"],"data_info":"Synthetic scenes generated inside the grader (no dataset file). Each scene is a 64x64 RGB image (uint8, channels last) with a 64x64 label map: 0 background, 1 disk, 2 ring, 3 square, 4 triangle, 5 cross. Objects have random colours and rotations, some are striped, they overlap (the top one owns the pixels) and can be cut by the border; backgrounds are smooth gradients with soft blotches and thin lines that count as background; every image has sensor noise. About 85% of pixels are background.\n\ntrain receives 2,000 scenes. Run scores 256 new scenes (64 like the training scenes, 96 out of focus, 96 with low-contrast objects). Submit trains on a different 2,000 and scores 384 (128 like the training scenes and 256 from four variations never shown before: patterned backgrounds, uneven lighting with heavy noise and blur, much smaller or larger objects, and crowded scenes). The label maps are fixed by the grader's seeds; the sensor noise is fresh on every run. predict receives the scored images only, in random order.","time_limits":{"test":180,"dev":150},"gpu":true,"description":"## Highest mIoU on Synthetic Segmentation Scenes\n\nYou get 2,000 small synthetic scenes with a label for every pixel, one GPU and a stopwatch. Train whatever segmenter you think learns fastest and holds up best, then label every pixel of scenes you have never seen. The highest mean IoU wins.\n\nAny method is allowed. The only things that count are the mean IoU you reach and whether you finish on time.\n\n### The scenes\n\nEach scene is a 64 by 64 RGB image with up to ten objects on a background. Every pixel has one of six classes:\n\n- 0 background, 1 disk, 2 ring, 3 square, 4 triangle, 5 cross.\n\nColour tells you nothing about the class: every object and every background gets random colours, and some objects are striped. Squares, triangles and crosses are rotated at random. Objects overlap, and the one on top owns the pixels. A ring's hole shows whatever lies beneath it. Objects can be cut off by the image border. The background is a smooth colour gradient with soft blotches, crossed by thin lines that also count as background, and every image has sensor noise.\n\n### What you write\n\n```python\ndef train(images, masks, budget_seconds):\n    ...\n    return model                    # anything you like\n\ndef predict(model, images):\n    ...\n    return labels                   # np.ndarray, shape (len(images), 64, 64)\n```\n\n- `images`: `uint8` array of shape `(n, 64, 64, 3)`, channels last, values 0 to 255.\n- `masks`: `uint8` array of shape `(n, 64, 64)`, class ids 0 to 5.\n- `budget_seconds`: a float, how long `train` may run on this machine (see below).\n- `labels`: whole numbers from 0 to 5, one per pixel, as a numpy array (not a torch tensor).\n\n### How it is graded\n\nThe grader counts, over every pixel of every scored scene, how often each true class meets each predicted class. For each class $c$ that gives\n\n$$\n\\mathrm{IoU}_c = \\frac{TP_c}{TP_c + FP_c + FN_c}\n$$\n\nand your score is the **mean IoU over the six classes**, background included. Small classes count as much as the background, so labelling everything as background scores badly even though most pixels are background. **Higher is better**, and the lab is passed at **0.40 or above**. The report also prints each class's IoU, pixel accuracy and the mean IoU of each kind of scene.\n\n- **Run**: train on 2,000 scenes, then score 256 new ones: 64 drawn like the training scenes, 96 slightly out of focus and 96 where objects have colours close to what lies beneath them.\n- **Submit**: train on a different set of 2,000 scenes drawn the same way, then score 384: 128 drawn like the training scenes and 256 from four variations that neither the training scenes nor Run ever show. They change how a scene looks, never what the classes mean: a patterned background instead of a smooth one, uneven lighting with heavy noise and blur, objects much smaller or larger than in training, and crowded scenes with many overlapping objects. Their exact settings are hidden.\n\nWhich pixels belong to which class is fixed by the grader's seeds, so everyone is scored on the same label maps. The sensor noise is drawn fresh on every run, so no image repeats byte for byte. Your process gets the scored images only after `train` has returned, and never their labels.\n\n**The score is noisy.** Training on a GPU is not exactly repeatable. In calibration, repeating the same code moved a Submit score with a standard deviation of about 0.01 and a Run score with about 0.02, and up to about 0.05 between the best and worst of five runs, so compare ideas over more than one run.\n\n### The budget\n\n- `train` gets about **25 seconds**, and `predict` gets 40% of whatever `train` got.\n- Before your file loads, the grader times a fixed training workload on the GPU it was given and scales `budget_seconds` to match, so a slower machine gets more seconds and a faster one fewer. Read `budget_seconds`, do not hard-code it.\n- The clock is the grader's, and it runs from the moment `train` is called until it returns. Importing libraries and loading your file are free, but a file that takes over 20 s to load is stopped.\n- Stay inside `budget_seconds`. Machines still differ a little after scaling, so the grader only stops a call at 15% past its budget. A stopped call scores 0 for the whole run.\n- You get a Tesla T4 GPU and PyTorch. If a run does not get a GPU, or the GPU is far from the expected speed, the grader says it did **not score** the run. That is a platform problem, not your code, so run it again.\n\n### Rules\n\n- Libraries: numpy, torch, scipy and scikit-learn, plus small standard-library helpers (math, random, time, collections, itertools, copy, heapq, bisect, statistics, warnings, typing, enum, abc). torchvision and tinygrad are not available here.\n- The harness owns the data: reading or writing files, dataset loaders, network access, serialization (`torch.save`, `torch.load`, `np.load`, `pickle`) and pretrained weights are refused. Weights have to come from your `train`.\n- Write classes the ordinary way: `self.conv = nn.Conv2d(...)` inside a method is fine, and so are `torch.backends.cudnn.benchmark` and `.deterministic`. Outside a method, assigning to any other attribute is refused, so use `p.requires_grad_(False)` rather than `p.requires_grad = False`, and keep other state in local variables, lists or dicts.\n- Dynamic access is refused (`getattr`, `setattr`, `vars`, `globals`, `exec`, `compile`, names starting with two underscores other than the usual methods such as `__init__`), and so are `os`, `sys` and text or byte decoders (`ord`, `chr`, `tobytes`, `encode`, `decode`).\n- A file can carry at most 12,000 characters of code (comments and docstrings do not count), 300 numbers of at most 8 characters each, 400 characters of strings, 200 names you define, each up to 24 characters, and 32 items in any one list, tuple, set or dict you write out. That leaves ordinary code plenty of room, and no room for weights trained somewhere else.\n\nA refused file, an exception, a wrong shape, labels outside 0 to 5 or a missed budget sets the score to 0 and fails the run.\n","tags":["semantic-segmentation","miou","u-net","dilated-convolution","data-augmentation","distribution-shift","time-budget","competitive","computer-vision"],"id":"03c81e4d-b53b-460d-a325-7f88478346ac","img_type":"full","dataset_id":"synthetic","evaluation_metric":"miou","difficulty":"hard","min_eval_metric":0.4,"category":"Computer Vision","title":"Highest mIoU on Synthetic Segmentation Scenes","dataset":"Synthetic shape scenes generated in the grader (64x64, 6 classes)","time_limits_seconds":{"dev":150,"test":180}},{"created_at":"2026-11-01T00:03:46.249000+00:00","type":"general","test_cases":[{"test":"import numpy as np\nif \"_tc_st\" not in globals():\n    _tc_r = np.random.default_rng(5)\n    def _tc_faces(n):\n        y, x = np.mgrid[0:64, 0:64] / 63.0\n        out = []\n        for _ in range(n):\n            a = _tc_r.normal(size=6)\n            f = 0.5 + 0.1 * (a[0] * np.sin(3 * x + a[1]) + a[2] * np.cos(4 * y + a[3]) + 0.5 * a[4] * np.sin(5 * (x + y) + a[5]))\n            out.append(np.clip(f, 0, 1))\n        return np.array(out, dtype=np.float32)\n    _tc_st = fit(_tc_faces(40))\nprint(type(_tc_st) in (bytes, bytearray), len(_tc_st) <= 65536)","expected_output":"True True"},{"test":"import numpy as np\nif \"_tc_st\" not in globals():\n    _tc_r = np.random.default_rng(5)\n    def _tc_faces(n):\n        y, x = np.mgrid[0:64, 0:64] / 63.0\n        out = []\n        for _ in range(n):\n            a = _tc_r.normal(size=6)\n            f = 0.5 + 0.1 * (a[0] * np.sin(3 * x + a[1]) + a[2] * np.cos(4 * y + a[3]) + 0.5 * a[4] * np.sin(5 * (x + y) + a[5]))\n            out.append(np.clip(f, 0, 1))\n        return np.array(out, dtype=np.float32)\n    _tc_st = fit(_tc_faces(40))\n_tc_b = encode(bytes(_tc_st), _tc_faces(1)[0])\nprint(type(_tc_b) in (bytes, bytearray), len(_tc_b) <= 256)","expected_output":"True True"},{"test":"import numpy as np\nif \"_tc_st\" not in globals():\n    _tc_r = np.random.default_rng(5)\n    def _tc_faces(n):\n        y, x = np.mgrid[0:64, 0:64] / 63.0\n        out = []\n        for _ in range(n):\n            a = _tc_r.normal(size=6)\n            f = 0.5 + 0.1 * (a[0] * np.sin(3 * x + a[1]) + a[2] * np.cos(4 * y + a[3]) + 0.5 * a[4] * np.sin(5 * (x + y) + a[5]))\n            out.append(np.clip(f, 0, 1))\n        return np.array(out, dtype=np.float32)\n    _tc_st = fit(_tc_faces(40))\n_tc_d = np.asarray(decode(bytes(_tc_st), bytes(encode(bytes(_tc_st), _tc_faces(1)[0]))), dtype=float)\nprint(_tc_d.shape, bool(np.all(np.isfinite(_tc_d))))","expected_output":"(64, 64) True"},{"test":"import numpy as np\nif \"_tc_st\" not in globals():\n    _tc_r = np.random.default_rng(5)\n    def _tc_faces(n):\n        y, x = np.mgrid[0:64, 0:64] / 63.0\n        out = []\n        for _ in range(n):\n            a = _tc_r.normal(size=6)\n            f = 0.5 + 0.1 * (a[0] * np.sin(3 * x + a[1]) + a[2] * np.cos(4 * y + a[3]) + 0.5 * a[4] * np.sin(5 * (x + y) + a[5]))\n            out.append(np.clip(f, 0, 1))\n        return np.array(out, dtype=np.float32)\n    _tc_st = fit(_tc_faces(40))\n_tc_p = []\nfor _tc_x in _tc_faces(5):\n    _tc_o = np.clip(np.asarray(decode(bytes(_tc_st), bytes(encode(bytes(_tc_st), _tc_x))), dtype=float), 0, 1)\n    _tc_p.append(10 * np.log10(1 / max(float(np.mean((_tc_o - _tc_x) ** 2)), 1e-10)))\nprint(\"mean PSNR on smooth test images above 30 dB:\", bool(np.mean(_tc_p) > 30))","expected_output":"mean PSNR on smooth test images above 30 dB: True"}],"lower_is_better":false,"approved_user_libraries":["numpy","scipy","sklearn","torch"],"data_info":"Olivetti faces from the dml_data registry (olivetti-faces), loaded by the grader: 400 float32 images, 64 x 64, pixels in [0, 1], 40 people with 10 images each. The split is by person. Submit: fit on 300 faces of 30 people, encode and decode the 100 faces of the other 10. Run: fit on 200 faces of 20 of those 30 people, encode and decode the 50 faces of 5 others. Your code never reads the dataset itself; the grader hands it the arrays.","time_limits":{"test":480,"dev":360},"example":{"input":"fit(train_images (300, 64, 64)) -> state of at most 65,536 bytes; encode(state, image (64, 64)) -> at most 256 bytes; decode(state, bitstream) -> (64, 64)","output":"Mean PSNR over the 100 faces of 10 held-out people; about 21.6 dB for 2 bits per pixel on a 32 x 32 thumbnail"},"gpu":false,"description":"The book turns K-means into a compressor: replace each vector by the index of its nearest prototype and you only send $\\log_2 K$ bits per vector, plus the codebook once, $O(N \\log_2 K + KDB)$ bits in all. Your job is to rebuild faces you have never seen from **256 bytes each**, which is 0.5 bits per pixel, as faithfully as you can. A codebook is the natural place to start; any codec you can write is allowed.\n\n## The data\n\nThe Olivetti faces: 400 grey 64 x 64 images of 40 people, 10 images per person, as float32 pixels in [0, 1]. The grader holds out **people**, not images, so nobody you are scored on appears in training.\n\n- **Submit** trains on the 300 faces of 30 people and scores the 100 faces of the other 10.\n- **Run** trains on the 200 faces of 20 of those 30 people and scores the 50 faces of 5 others. It never touches the people Submit scores.\n\n## Your functions\n\n```python\ndef fit(train_images):\n    ...\n    return state            # bytes, at most 65,536 of them\n\ndef encode(state, image):\n    ...\n    return bitstream        # bytes, at most 256 of them\n\ndef decode(state, bitstream):\n    ...\n    return reconstruction   # array of shape (64, 64)\n```\n\n`train_images` is float32 with shape `(n, 64, 64)` and `image` is float32 with shape `(64, 64)`. `state` is exactly the bytes `fit` returned, and it is the only thing that survives `fit`: your codebook, transforms, probability tables or network weights all have to fit inside it. Build it with `ndarray.tobytes()`, `np.frombuffer` and `struct`. The grader clips the reconstruction to [0, 1].\n\n## How the rate is enforced\n\nThe grader counts the bytes `encode` returns and hands those bytes, and nothing else, to `decode`. The three stages run one after another in separate fresh processes, and each process is dead before the next one starts:\n\n1. `fit` sees the training faces only.\n2. `encode` sees the state and one held-out face per call.\n3. `decode` sees the state and one bitstream per call, in shuffled order. It has never been in a process that held a face.\n\nEvery `encode` and `decode` call runs in its own short-lived fork of its stage's process, so anything one call stores in a variable is gone for the next: each face is coded alone. Your module-level code runs once per stage process, so imports and small setup belong there and long work does not.\n\n## Score (higher is better)\n\nFor each scored face, $\\mathrm{PSNR} = 10 \\log_{10}(1 / \\mathrm{MSE})$ in dB, with MSE the mean squared pixel error of the clipped reconstruction. The score is the **mean PSNR over the scored faces**. You pass at **27 dB**; above that, higher ranks higher. Spending fewer than 256 bytes earns nothing extra. The report also shows the 10th and 90th percentile PSNR, bytes per face, bits per pixel, the size of your state and the seconds each stage used.\n\n## Budget and gates\n\n`fit` gets **120 CPU seconds**. `encode` and `decode` each get **1 CPU second per scored face** in total, and any single call may take at most 20 s. The run is CPU only and numeric libraries run single-threaded. Approved libraries: numpy, scipy, scikit-learn and torch, plus math, cmath, random, time, collections, itertools, functools, heapq, bisect, struct, zlib, lzma, bz2, array, copy, typing, dataclasses, abc and fractions.\n\nThe run fails with a score of 0 if:\n\n- a bitstream is over 256 bytes, the state is over 65,536 bytes, or either one is not `bytes`;\n- any of your functions raises, a budget is exceeded, or a reconstruction has the wrong shape or a non-finite value;\n- your code writes a file, or reads data the grader did not hand it. Imports outside the approved list, `dml_data`, dataset loaders, file and network access (`open`, `np.save`, `np.load`, `.tofile`,...), `getattr`/`setattr`/`globals`/`vars`, shared memory, dunder attributes such as `__dict__` and private attributes of libraries are all refused before `fit` is called;\n- your source is over 30,000 characters without comments and blank lines, its string constants add up to more than 1,500 bytes, it has more than 1,000 numeric literals or they add up to more than 3,000 characters, an integer literal has more than 18 digits, its distinct names add up to more than 5,000 bytes, or it uses names more than 6,000 times. Those caps keep a codebook trained elsewhere out of your source: what your codec knows about faces has to be learned by `fit` during the run.\n\n**Run** shows your prints (the first 2,000 characters per stage) and your tracebacks, so debug there. **Submit** discards your prints and reports an exception by stage and type only, because the held-out faces stay hidden.","tags":["vector-quantization","k-means","compression","rate-distortion","codebook","psnr","open-ended","leaderboard"],"id":"072b2938-4ef1-45ce-a79b-ce07ae9ec024","img_type":"full","dataset_id":"olivetti-faces","evaluation_metric":"psnr_db","difficulty":"medium","min_eval_metric":27.0,"category":"Computer Vision","title":"Best Image Codebook at 0.5 Bits per Pixel","dataset":"Olivetti Faces (400 images of 40 people, split by person)","time_limits_seconds":{"dev":360,"test":480}},{"description":"Implement a custom transformation class `MyTransform` to modify each input image tensor used by a PyTorch `DataLoader`. The DataLoader will apply your transform through a provided collate function, so your implementation must define how each image is transformed before training. The goal is to learn to integrate PyTorch transformations directly into data pipelines.","constraints":["Implement ONLY `MyTransform`.","You MUST return a tensor of the SAME shape and dtype.","The transform must NOT be the identity function.","It must be deterministic under a fixed random seed."],"id":"1","test_cases":[{"test":"import torch\nx = torch.rand(1,28,28)\nT = MyTransform()\ny = T(x)\nprint(y.shape == x.shape)","expected_output":"True"}],"approved_user_libraries":["torch"],"difficulty":"medium","evaluation_metric":"Accuracy","data_info":"MNIST 28x28 grayscale digits (10 classes). Inputs initially scaled to [0,255] and shaped (N,1,28,28).","time_limits":{"test":"240 seconds","dev":"90 seconds"},"schema":"practical_question_v1","min_eval_metric":0.8,"example":{"input":{"X":"array([[[  0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,\n           0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,\n           0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.],\n        [  0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,\n           0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,\n           0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.],\n        [  0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,\n           0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,\n           0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.],\n        [  0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,\n           0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,\n           0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.],\n        [  0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,\n           0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,\n           0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.],\n        [  0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,\n           0.,   0.,   3.,  18.,  18.,  18., 126., 136., 175.,  26.,\n         166., 255., 247., 127.,   0.,   0.,   0.,   0.],..."},"output":{"y":"5"}},"category":"Data Pipelines","dataset":"MNIST","title":"MNIST: Pytorch DataLoader","model_specs":"Small CNN: Conv→ReLU→MaxPool x2, then Linear→ReLU→Linear(10). Batch size: 128, Optimizer: Adam lr=1e-3, epochs: 2.","memory_limit":"2 GB","createdAt":"2026-05-15T12:09:45.523000+00:00","time_limits_seconds":{"dev":90,"test":240},"type":"epoch","lower_is_better":false,"gpu":false},{"constraints":["Your attention function must use only NumPy (no PyTorch, TensorFlow, or other ML frameworks)","Must return a NumPy array with correct shape","Must produce valid attention weights (non-negative, sum to 1 per query)","Must be deterministic (same input → same output)","Must handle batched inputs","Your function will be plugged into a PyTorch model for training (harness handles conversion)"],"test_cases":[{"description":"Output shape matches expected","test":"import numpy as np\nQ = np.random.randn(4, 10, 32); K = np.random.randn(4, 10, 32); V = np.random.randn(4, 10, 32); out = attention(Q, K, V); print(out.shape == (4, 10, 32))","expected_output":"True"},{"description":"Works with different query and key lengths","test":"import numpy as np\nQ = np.random.randn(4, 5, 32); K = np.random.randn(4, 10, 32); V = np.random.randn(4, 10, 32); out = attention(Q, K, V); print(out.shape == (4, 5, 32))","expected_output":"True"},{"description":"Deterministic output","test":"import numpy as np\nnp.random.seed(42)\nQ = np.random.randn(2, 4, 16); K = np.random.randn(2, 4, 16); V = np.random.randn(2, 4, 16); out1 = attention(Q, K, V); out2 = attention(Q, K, V); print(np.allclose(out1, out2))","expected_output":"True"},{"description":"No NaN or Inf in output","test":"import numpy as np\nQ = np.random.randn(4, 8, 32); K = np.random.randn(4, 8, 32); V = np.random.randn(4, 8, 32); out = attention(Q, K, V); print(np.all(np.isfinite(out)))","expected_output":"True"}],"approved_user_libraries":["numpy"],"input_format":{"K":"Key matrix of shape (batch_size, seq_len, dim)","Q":"Query matrix of shape (batch_size, seq_len, dim)","V":"Value matrix of shape (batch_size, seq_len, dim)"},"data_info":"IMDB Movie Reviews from TensorFlow's official .npz dataset: 50,000 reviews labeled as positive (1) or negative (0). Reviews are tokenized into sequences of word indices (vocabulary size 5,000). Sequences are padded/truncated to 80 tokens. Your attention mechanism helps the model focus on sentiment-bearing words.","time_limits":{"test":"300 seconds","dev":"120 seconds"},"example":{"input":{"K":"np.array shape (64, 80, 64), key vectors","Q":"np.array shape (64, 80, 64), query vectors","V":"np.array shape (64, 80, 64), value vectors"},"output":{"attended":"np.array shape (64, 80, 64), weighted combination of values based on query-key compatibility"}},"output_format":{"output":"Attended output of shape (batch_size, seq_len, dim)"},"model_specs":"PyTorch sequence classifier: Embedding(5000→64) → Q,K,V projection → [YOUR NUMPY ATTENTION] + Residual → GlobalAvgPool → Linear(64→1) → Sigmoid. Your NumPy attention function is wrapped in a custom PyTorch autograd Function for seamless integration.","function_signature":"attention(Q, K, V) -> output","description":"Implement an attention mechanism for sentiment analysis on movie reviews. Your attention function will help a neural network learn which words in a review are most important for determining whether the sentiment is positive or negative.","id":"10","difficulty":"medium","evaluation_metric":"Accuracy","schema":"practical_question_v1","min_eval_metric":0.7,"category":"Attention & Transformers","createdAt":"2026-05-13T21:01:39.924000+00:00","title":"Design Your Own Attention Mechanism","topics":["attention","transformers","sequence modeling","deep learning","NLP"],"memory_limit":"2 GB","dataset":"IMDB Movie Reviews","time_limits_seconds":{"dev":120,"test":300},"type":"epoch","lower_is_better":false,"gpu":false},{"description":"Implement a function to handle missing data (NaN values). Your function should fill in all NaN values with reasonable estimates. Your imputed data will be used to train a sklearn RandomForestRegressor on the Boston Housing dataset. Performance is evaluated on Mean Squared Error (MSE). Lower MSE is better. Since MSE is a loss metric, it is converted to an accuracy score using: val_accuracy = 1.0 - (MSE / 50.0). This means MSE of 0 gives accuracy of 1.0, MSE of 25 gives accuracy of 0.5, and the passing threshold of MSE < 35 corresponds to accuracy > 0.3.","type":"general","constraints":["Implement ONLY the `impute` function.","Output array must have the SAME shape as input X.","Output array must contain NO NaN or Inf values.","Only numpy is allowed."],"id":"11","test_cases":[{"test":"import numpy as np\nX = np.array([[1, np.nan], [3, 4], [np.nan, 6]])\nX_clean = impute(X)\nprint(X_clean.shape == X.shape)","expected_output":"True"},{"test":"import numpy as np\nX = np.array([[1, np.nan], [3, 4], [np.nan, 6]])\nX_clean = impute(X)\nprint(not np.isnan(X_clean).any())","expected_output":"True"}],"approved_user_libraries":["numpy"],"difficulty":"medium","evaluation_metric":"MSE Accuracy","data_info":"Boston Housing dataset with 13 features predicting median home value ($1000s). ~400 training samples, ~100 test samples. ~15-25% values artificially set to NaN.","time_limits":{"test":"120 seconds","dev":"60 seconds"},"schema":"practical_question_v1","min_eval_metric":0.3,"example":{"input":{"X":"np.array with shape (n, 13) containing housing features with NaN values. The 13 features are: [0] CRIM (per capita crime rate), [1] ZN (proportion of residential land zoned for large lots), [2] INDUS (proportion of non-retail business acres), [3] CHAS (Charles River dummy: 1 if bounds river, 0 otherwise), [4] NOX (nitric oxide concentration), [5] RM (average rooms per dwelling), [6] AGE (proportion of old owner-occupied units), [7] DIS (distance to employment centers), [8] RAD (highway accessibility index), [9] TAX (property tax rate per $10k), [10] PTRATIO (pupil-teacher ratio), [11] B (proportion of Black residents), [12] LSTAT (% lower status population)"},"output":{"X_clean":"np.array with shape (n, 13) - same shape as X, no NaN values"}},"category":"Data Preprocessing","title":"Data Preprocessing: Handling Missing Values","model_specs":"RandomForestRegressor(n_estimators=100) trained on your cleaned data.","memory_limit":"1 GB","dataset":"Boston Housing","createdAt":"2026-05-15T12:10:20.607000+00:00","time_limits_seconds":{"dev":60,"test":120},"lower_is_better":false,"gpu":false},{"description":"Implement a function `train_step(model, x_batch, y_batch, lr)` that performs ONE step of gradient descent training. You must manually: (1) compute the forward pass, (2) compute the loss, (3) compute gradients using backpropagation, and (4) update the model parameters. Do NOT use torch.optim - update weights yourself using the gradients. This teaches how gradient descent actually works in PyTorch.","constraints":["Must compute forward pass through the model.","Must compute cross-entropy loss (or similar classification loss).","Must call backward() to compute gradients.","Must zero gradients before backward pass.","Must use torch.no_grad() when updating parameters.","Must return the loss value as a Python float.","Do not use Optim "],"id":"12","test_cases":[{"test":"import torch\nimport torch.nn as nn\nmodel = nn.Linear(10, 2)\nx = torch.randn(4, 10)\ny = torch.tensor([0, 1, 0, 1])\nloss = train_step(model, x, y, lr=0.1)\nprint(isinstance(loss, float) and loss > 0)","expected_output":"True"},{"test":"import torch\nimport torch.nn as nn\nmodel = nn.Sequential(nn.Linear(10, 5), nn.ReLU(), nn.Linear(5, 2))\nx = torch.randn(4, 10)\ny = torch.tensor([0, 1, 0, 1])\nloss = train_step(model, x, y, lr=0.1)\nprint(isinstance(loss, float))","expected_output":"True"},{"test":"import torch\nimport torch.nn as nn\n\n# Detect if torch.optim is used\n_optim_used = [False]\n_OrigSGD = torch.optim.SGD\n_OrigAdam = torch.optim.Adam\nclass _FakeSGD(_OrigSGD):\n    def __init__(self, *a, **kw):\n        _optim_used[0] = True\n        super().__init__(*a, **kw)\nclass _FakeAdam(_OrigAdam):\n    def __init__(self, *a, **kw):\n        _optim_used[0] = True\n        super().__init__(*a, **kw)\ntorch.optim.SGD = _FakeSGD\ntorch.optim.Adam = _FakeAdam\n\nmodel = nn.Linear(10, 2)\nx = torch.randn(4, 10)\ny = torch.tensor([0, 1, 0, 1])\ntrain_step(model, x, y, lr=0.1)\n\ntorch.optim.SGD = _OrigSGD\ntorch.optim.Adam = _OrigAdam\nprint(not _optim_used[0])","expected_output":"True"}],"difficulty":"medium","approved_user_libraries":["torch"],"evaluation_metric":"Accuracy","time_limits":{"test":"120 seconds","dev":"60 seconds"},"data_info":"MNIST 28x28 grayscale digits flattened to 784-dim vectors, scaled to [0,1]. Trained with a 3-layer MLP (784->128->128->10).","schema":"practical_question_v1","min_eval_metric":0.85,"example":{"input":{"x_batch":"torch.Tensor of shape (batch_size, features)","model":"nn.Module (e.g., nn.Linear(784, 10) or nn.Sequential(...))","y_batch":"torch.Tensor of shape (batch_size,) with class labels","lr":"float, learning rate (e.g., 0.01)"},"output":{"loss":"float, the loss value for this batch"}},"category":"PyTorch Fundamentals","dataset":"MNIST","title":"PyTorch: Implement Your Own Gradient Descent Training Step","memory_limit":"2 GB","createdAt":"2026-05-15T12:10:24.590000+00:00","time_limits_seconds":{"dev":60,"test":120},"type":"epoch","lower_is_better":false,"gpu":false},{"description":"Implement a function `train_model(model, X_train, y_train, X_val, y_val, epochs, batch_size, lr)` that trains a neural network using PyTorch. Use `torch.optim` for optimization and implement proper batching, shuffling, and validation. Return a list of dictionaries containing training metrics for each epoch.","constraints":["Must use torch.optim (SGD, Adam, or similar) for optimization.","Must implement mini-batch training with the specified batch_size.","Must shuffle training data each epoch.","Must compute validation accuracy and loss after each epoch.","Must return a list of dicts with keys: 'epoch', 'train_loss', 'val_loss', 'val_accuracy'.","Must use cross-entropy loss for classification."],"id":"13","test_cases":[{"test":"import torch\nimport torch.nn as nn\nmodel = nn.Linear(10, 2)\nX_train = torch.randn(100, 10)\ny_train = torch.randint(0, 2, (100,))\nX_val = torch.randn(20, 10)\ny_val = torch.randint(0, 2, (20,))\nhistory = train_model(model, X_train, y_train, X_val, y_val, epochs=2, batch_size=16, lr=0.01)\nprint(isinstance(history, list) and len(history) == 2)","expected_output":"True"},{"test":"import torch\nimport torch.nn as nn\nmodel = nn.Linear(10, 2)\nX_train = torch.randn(100, 10)\ny_train = torch.randint(0, 2, (100,))\nX_val = torch.randn(20, 10)\ny_val = torch.randint(0, 2, (20,))\nhistory = train_model(model, X_train, y_train, X_val, y_val, epochs=2, batch_size=16, lr=0.01)\nprint(all('epoch' in h and 'train_loss' in h and 'val_loss' in h and 'val_accuracy' in h for h in history))","expected_output":"True"},{"test":"import torch\nimport torch.nn as nn\nmodel = nn.Linear(10, 2)\nX_train = torch.randn(100, 10)\ny_train = torch.randint(0, 2, (100,))\nX_val = torch.randn(20, 10)\ny_val = torch.randint(0, 2, (20,))\nhistory = train_model(model, X_train, y_train, X_val, y_val, epochs=3, batch_size=16, lr=0.01)\nprint(history[0]['epoch'] == 1 and history[-1]['epoch'] == 3)","expected_output":"True"},{"test":"import torch\nimport torch.nn as nn\nmodel = nn.Sequential(nn.Linear(10, 5), nn.ReLU(), nn.Linear(5, 2))\nX_train = torch.randn(80, 10)\ny_train = torch.randint(0, 2, (80,))\nX_val = torch.randn(20, 10)\ny_val = torch.randint(0, 2, (20,))\nw_before = model[0].weight.clone().detach()\nhistory = train_model(model, X_train, y_train, X_val, y_val, epochs=5, batch_size=16, lr=0.1)\nw_after = model[0].weight.clone().detach()\nprint(not torch.allclose(w_before, w_after))","expected_output":"True"}],"approved_user_libraries":["torch"],"difficulty":"easy","evaluation_metric":"Accuracy","data_info":"MNIST 28x28 grayscale digits flattened to 784-dim vectors, scaled to [0,1]. Trained with a 3-layer MLP (784->128->128->10).","time_limits":{"test":"120 seconds","dev":"60 seconds"},"schema":"practical_question_v1","min_eval_metric":0.85,"example":{"input":{"X_train":"torch.Tensor of shape (N, features)","batch_size":"int, mini-batch size","y_val":"torch.Tensor of shape (M,) with class labels","epochs":"int, number of training epochs","lr":"float, learning rate","X_val":"torch.Tensor of shape (M, features)","model":"nn.Module (e.g., nn.Sequential(nn.Linear(784, 128), nn.ReLU(), nn.Linear(128, 10)))","y_train":"torch.Tensor of shape (N,) with class labels"},"output":{"history":"List[Dict] with keys 'epoch', 'train_loss', 'val_accuracy'"}},"category":"PyTorch Fundamentals","title":"PyTorch: Build a Complete Training Loop","dataset":"MNIST","memory_limit":"2 GB","createdAt":"2026-05-15T12:10:28.906000+00:00","time_limits_seconds":{"dev":60,"test":120},"type":"epoch","lower_is_better":false,"gpu":false},{"type":"general","constraints":["Implement using NumPy only. No sklearn, scipy.linalg, or other high-level libraries.","Must implement: fit(X), transform(X), and fit_transform(X).","transform() must return shape (n_samples, 10).","The reduction must be deterministic (same input -> same output).","Cannot simply select features or random subsets.","Projection matrix must be at most shape (n_features, 10)."],"test_cases":[{"test":"import numpy as np\nnp.random.seed(42)\nX = np.random.randn(100, 50)\nreducer = MyReducer()\nreducer.fit(X)\nX_t = reducer.transform(X)\nprint(X_t.shape == (100, 10))","expected_output":"True"},{"test":"import numpy as np\nnp.random.seed(42)\nX = np.random.randn(100, 50)\nreducer = MyReducer()\nX_t1 = reducer.fit_transform(X)\nX_t2 = reducer.transform(X)\nprint(np.allclose(X_t1, X_t2))","expected_output":"True"},{"test":"import numpy as np\nnp.random.seed(42)\nX = np.random.randn(80, 30)\nreducer1 = MyReducer()\nreducer2 = MyReducer()\nX_t1 = reducer1.fit_transform(X)\nX_t2 = reducer2.fit_transform(X)\nprint(np.allclose(X_t1, X_t2))","expected_output":"True"}],"approved_user_libraries":["numpy"],"data_info":"Validation: MNIST (2000 train, 500 test, 784 -> 10 dims). Test: MNIST (5000 train, 1000 test, 784 -> 10 dims). Evaluated with k-NN classifier.","time_limits":{"test":"180 seconds","dev":"90 seconds"},"example":{"input":{"X":"np.array of shape (n_samples, n_features), e.g. shape (5000, 784) for 5000 MNIST images"},"output":{"X_reduced":"np.array of shape (n_samples, n_components), e.g. shape (5000, 50) for 50-dimensional projection"}},"model_specs":"sklearn KNeighborsClassifier (k=5) trained on MNIST reduced to 10 dimensions.","model_specifications":"sklearn KNeighborsClassifier (k=5) trained on MNIST reduced to 10 dimensions.","description":"Implement a dimensionality reduction class `MyReducer` that projects high-dimensional data down to 10 dimensions using NumPy. Your reducer will be evaluated by training a k-NN classifier on the reduced MNIST data and measuring accuracy.","id":"14","difficulty":"medium","evaluation_metric":"Accuracy","schema":"practical_question_v1","min_eval_metric":0.8,"category":"Dimensionality Reduction","title":"Numpy: Design Your Own Dimensionality Reduction","dataset":"MNIST","createdAt":"2026-05-15T12:10:51.564000+00:00","memory_limit":"2 GB","time_limits_seconds":{"dev":90,"test":180},"lower_is_better":false,"gpu":false},{"description":"Implement a dimensionality reduction class `MyReducer` that projects high-dimensional data down to 10 dimensions. You can use sklearn and NumPy. Your reducer will be evaluated by training a k-NN classifier on the reduced MNIST data and measuring accuracy.","constraints":["Must implement: fit(X), transform(X), and fit_transform(X).","transform() must return shape (n_samples, 10).","The reduction must be deterministic (same input -> same output).","Can use sklearn and numpy only.","Cannot simply select features or random subsets."],"id":"15","test_cases":[{"test":"import numpy as np\nnp.random.seed(42)\nX = np.random.randn(100, 50)\nreducer = MyReducer()\nreducer.fit(X)\nX_t = reducer.transform(X)\nprint(X_t.shape == (100, 10))","expected_output":"True"},{"test":"import numpy as np\nnp.random.seed(42)\nX = np.random.randn(100, 50)\nreducer = MyReducer()\nX_t1 = reducer.fit_transform(X)\nX_t2 = reducer.transform(X)\nprint(np.allclose(X_t1, X_t2))","expected_output":"True"},{"test":"import numpy as np\nnp.random.seed(42)\nX = np.random.randn(80, 30)\nreducer1 = MyReducer()\nreducer2 = MyReducer()\nX_t1 = reducer1.fit_transform(X)\nX_t2 = reducer2.fit_transform(X)\nprint(np.allclose(X_t1, X_t2))","expected_output":"True"}],"approved_user_libraries":["numpy","sklearn"],"difficulty":"easy","evaluation_metric":"Accuracy","data_info":"Validation: MNIST (2000 train, 500 test, 784 -> 10 dims). Test: MNIST (5000 train, 1000 test, 784 -> 10 dims). Evaluated with k-NN classifier.","time_limits":{"test":"180 seconds","dev":"90 seconds"},"schema":"practical_question_v1","min_eval_metric":0.85,"example":{"input":{"X":"np.array of shape (n_samples, n_features), e.g. shape (5000, 784) for 5000 MNIST images"},"output":{"X_reduced":"np.array of shape (n_samples, 10)"}},"category":"Dimensionality Reduction","title":"Dimensionality Reduction with Sklearn","model_specs":"sklearn KNeighborsClassifier (k=5) trained on MNIST reduced to 10 dimensions.","memory_limit":"2 GB","dataset":"MNIST","createdAt":"2026-05-13T21:01:40.633000+00:00","time_limits_seconds":{"dev":90,"test":180},"type":"epoch","lower_is_better":false,"gpu":false},{"description":"You are training a digit classifier on Colored MNIST, where each digit is colored with a class-correlated color (e.g., 0s are usually red, 1s are usually green). During training, colors are 80% correlated with digit class, creating a shortcut the model can exploit. At test time, colors are only 30% correlated, so a model relying on color will perform poorly. Your task is to implement a `FeatureDeconfounder` layer that removes the linear influence of color metadata from neural network features during training, forcing the model to learn digit shapes instead of color shortcuts.","constraints":["Implement ONLY the FeatureDeconfounder class with fit() and transform() methods.","fit() must precompute Sigma_inv = (X^T X + reg*I)^{-1} from training metadata.","transform() must compute beta = Sigma_inv @ X^T @ f and return residual = f - X @ beta.","transform() must allow gradients to flow through for end-to-end training.","Must handle both numpy arrays and PyTorch tensors as input."],"id":"16","test_cases":[{"test":"import torch\ndeconf = FeatureDeconfounder()\nmeta = torch.rand(100, 3)\ndeconf.fit(meta)\nf = torch.rand(10, 64)\nout = deconf.transform(f, torch.rand(10, 3))\nprint(out.shape == f.shape)","expected_output":"True"},{"test":"import torch\nimport torch.nn as nn\ndeconf = FeatureDeconfounder()\nmeta = torch.rand(100, 3)\ndeconf.fit(meta)\nf = torch.rand(10, 64, requires_grad=True)\nm = torch.rand(10, 3)\nout = deconf.transform(f, m)\nloss = out.sum()\nloss.backward()\nprint(f.grad is not None)","expected_output":"True"}],"approved_user_libraries":["torch","numpy"],"evaluation_metric":"Accuracy","data_info":"Colored MNIST dataset where each grayscale digit is colorized. Training data has 80% color-class correlation (digit 0 is usually red, digit 1 is usually green, etc.). Test data has 30% correlation (reduced bias). Metadata is 3-dimensional RGB color values. The model must learn to classify digits by shape, not color, to succeed on the less-biased test set.","time_limits":{"test":180,"validation":120},"difficulty":"hard","schema":"FeatureDeconfounder class with fit(metadata) and transform(features, metadata) methods","min_eval_metric":0.5,"example":{"input":{"features":"torch.Tensor of shape (M, D) - batch of encoder features","colors_train":"torch.Tensor of shape (N, 3) - all training colors for fit()","metadata":"torch.Tensor of shape (M, K) - corresponding color values (RGB)"},"output":{"note":"Gradients flow through transform() for end-to-end training","residual":"torch.Tensor of shape (M, D) - features with color influence removed"}},"category":"Feature Deconfounding","title":"Feature Deconfounder for Biased Image Data","model_specs":"Small CNN: Conv(3,16)→ReLU→Pool→Conv(16,32)→ReLU→Pool→FC(1568,64). Training: Adam lr=1e-3, batch_size=128, epochs=5.","memory_limit":"4GB","dataset":"Colored MNIST","createdAt":"2026-05-15T12:11:09.647000+00:00","time_limits_seconds":{"dev":60,"test":180},"type":"epoch","lower_is_better":false,"gpu":false},{"description":"Implement a `train` function that takes standardized training data and randomly initialized weights, and returns trained weights for a linear regression model.\n\nThe harness handles everything else: data loading, feature standardization, weight initialization, prediction (`y = X @ W + b`), and evaluation. You just define **how the weights get updated**.\n\nYou may use ANY training strategy you like: gradient descent, the normal equation, momentum, adaptive learning rates, mini-batching, or anything else -- as long as you only use NumPy and the returned `(W, b)` produce good predictions.","type":"general","constraints":["Use ONLY numpy - no sklearn, PyTorch, TensorFlow, or other ML libraries","Your function signature must be: train(X, y, W, b) -> (W, b)","X and y are already standardized (zero mean, unit variance) -- do NOT re-standardize","W is a 1-D array of shape (n_features,), b is a float","Must return W as a 1-D numpy array and b as a float (or 0-d array)","Must be deterministic under a fixed numpy random seed","Any training strategy is valid!"],"id":"18","test_cases":[{"description":"Returns correct types and shapes","test":"import numpy as np\nnp.random.seed(42)\nX = np.random.randn(100, 5)\ny = np.random.randn(100)\nW = np.random.randn(5) * 0.01\nb = 0.0\nW_out, b_out = train(X, y, W, b)\nprint(W_out.shape == (5,) and np.isscalar(b_out) or b_out.ndim == 0)","expected_output":"True"},{"description":"Output contains no NaN or Inf","test":"import numpy as np\nnp.random.seed(42)\nX = np.random.randn(100, 5)\ny = np.random.randn(100)\nW = np.random.randn(5) * 0.01\nb = 0.0\nW_out, b_out = train(X, y, W, b)\nprint(np.all(np.isfinite(W_out)) and np.isfinite(b_out))","expected_output":"True"},{"description":"Actually learns (predictions improve over random weights)","test":"import numpy as np\nnp.random.seed(42)\nX = np.random.randn(200, 3)\ntrue_w = np.array([1.0, -2.0, 0.5])\ny = X @ true_w + 0.1 * np.random.randn(200)\nW = np.random.randn(3) * 0.01\nb = 0.0\nW_out, b_out = train(X, y, W, b)\npreds_before = X @ W + b\npreds_after = X @ W_out + b_out\nmse_before = np.mean((y - preds_before)**2)\nmse_after = np.mean((y - preds_after)**2)\nprint(mse_after < mse_before * 0.1)","expected_output":"True"},{"description":"Deterministic output","test":"import numpy as np\nnp.random.seed(42)\nX = np.random.randn(100, 4)\ny = np.random.randn(100)\nW = np.random.randn(4) * 0.01\nb = 0.0\nnp.random.seed(99)\nW1, b1 = train(X.copy(), y.copy(), W.copy(), b)\nnp.random.seed(99)\nW2, b2 = train(X.copy(), y.copy(), W.copy(), b)\nprint(np.allclose(W1, W2) and np.isclose(b1, b2))","expected_output":"True"}],"approved_user_libraries":["numpy"],"difficulty":"easy","evaluation_metric":"R2","data_info":"California Housing dataset from sklearn: 20,640 samples with 8 numerical features (MedInc, HouseAge, AveRooms, AveBedrms, Population, AveOccup, Latitude, Longitude). Target is median house value in $100,000s. Both features and target are standardized (zero mean, unit variance) before being passed to your function.","time_limits":{"test":"60 seconds","dev":"30 seconds"},"schema":"practical_question_v1","min_eval_metric":0.5,"example":{"input":{"X":"numpy array of shape (3000, 8) -- standardized training features","y":"numpy array of shape (3000,) -- standardized target values","W":"numpy array of shape (8,) -- randomly initialized weights","b":"float -- initialized bias (0.0)"},"output":{"W":"numpy array of shape (8,) -- trained weights","b":"float -- trained bias"}},"category":"Regression","title":"Train a Linear Regression Model","model_specs":"Linear model: y = X @ W + b. Harness standardizes data, initializes W ~ N(0, 0.01), b = 0. User trains weights, harness evaluates R^2 on held-out data.","memory_limit":"1 GB","dataset":"California Housing","createdAt":"2026-05-15T12:11:17.612000+00:00","time_limits_seconds":{"dev":30,"test":60},"lower_is_better":false,"gpu":false},{"description":"Implement a `train_tokenizer` function that learns a vocabulary from a training corpus of names and returns `encode` and `decode` functions.\n\nThe harness will use your tokenizer to train a bigram language model on the tokenized corpus, then evaluate how well that model predicts held-out names. A better tokenizer creates more predictable token sequences, leading to lower bits-per-character (BPC) on held-out data.\n\nYou may use ANY tokenization strategy: character-level, byte pair encoding (BPE), frequency-based subword merging, common n-gram extraction, word-level with character fallback, or anything creative -- as long as you only use standard Python (no external libraries).","type":"general","constraints":["Use ONLY the Python standard library -- no numpy, sklearn, or other external libraries","Your function signature must be: train_tokenizer(corpus, vocab_size) -> (encode, decode)","corpus is a list[str] of training documents (names), vocab_size is an int (256)","encode: str -> list[int], all token IDs must be in range [0, vocab_size)","decode: list[int] -> str, must satisfy decode(encode(text)) == text for all text","Must handle any text composed of characters seen in the training corpus","Must be deterministic -- same input always produces same output"],"id":"19","test_cases":[{"description":"Returns callable encode and decode","test":"corpus = ['hello', 'world', 'help', 'held', 'helm', 'hero']\nencode, decode = train_tokenizer(corpus, 64)\nprint(callable(encode) and callable(decode))","expected_output":"True"},{"description":"encode returns list of ints in range","test":"corpus = ['hello', 'world', 'help', 'held', 'helm', 'hero']\nencode, decode = train_tokenizer(corpus, 64)\ntokens = encode('hello')\nprint(isinstance(tokens, list) and all(isinstance(t, int) and 0 <= t < 64 for t in tokens))","expected_output":"True"},{"description":"Lossless roundtrip on training data","test":"corpus = ['hello', 'world', 'help', 'held', 'helm', 'hero']\nencode, decode = train_tokenizer(corpus, 64)\nprint(all(decode(encode(w)) == w for w in corpus))","expected_output":"True"},{"description":"Handles unseen text with known characters","test":"corpus = ['hello', 'world', 'help', 'held', 'helm', 'hero']\nencode, decode = train_tokenizer(corpus, 64)\nprint(decode(encode('herd')) == 'herd' and decode(encode('howl')) == 'howl')","expected_output":"True"}],"difficulty":"medium","evaluation_metric":"BPC_improvement","data_info":"Names dataset (32,033 human names) from Karpathy's makemore project. Each name is a short lowercase string (average ~6 characters, alphabet of 26 letters). Training set: 25,000 names. The harness trains a bigram language model on the tokenized training data and evaluates bits-per-character on held-out names.","time_limits":{"test":"120 seconds","dev":"120 seconds"},"approved_user_libraries":["math"],"schema":"practical_question_v1","min_eval_metric":-0.05,"example":{"input":{"corpus":"list[str] -- 25,000 training names, e.g. ['emma', 'olivia', 'ava', ...]","vocab_size":"int -- maximum vocabulary size (256)"},"output":{"encode":"callable: str -> list[int], e.g. encode('emma') -> [4, 26, 0] (token IDs in [0, 256))","decode":"callable: list[int] -> str, e.g. decode([4, 26, 0]) -> 'emma'"}},"category":"NLP","title":"Build a Tokenizer for Language Modeling","model_specs":"Harness loads 32K names, gives 25K to user's train_tokenizer(). Then trains a bigram language model on the tokenized training data with interpolation smoothing. Evaluates bits-per-character (BPC) on held-out names. Score = char_baseline_BPC - user_BPC. Character-level scores ~0.0 (baseline). Better tokenizers score higher.","memory_limit":"1 GB","dataset":"Names (Karpathy makemore)","createdAt":"2026-05-13T21:01:41.183000+00:00","time_limits_seconds":{"dev":120,"test":120},"lower_is_better":false,"gpu":false},{"created_at":"2026-11-01T01:10:30.459000+00:00","type":"general","constraints":["at most 32 full-covariance components; the grader computes the density itself","fit <= 4 s of wall-clock time per task; past 4.6 s the run fails","numpy, scipy, scikit-learn and torch plus small standard-library helpers; attribute assignment only on self inside a class method","source capped at 30000 characters, 800 numeric literals, 3000 characters of string constants"],"test_cases":[{"test":"import numpy as np\n_r = np.random.default_rng(0)\n_mu = np.array([[-6.0, 0.0], [6.0, 2.0], [0.0, 8.0]])\n_sd = np.array([[1.0, 0.3], [0.4, 1.5], [0.7, 0.7]])\n_z = _r.integers(0, 3, 900)\n_X = _mu[_z] + _r.normal(size=(900, 2)) * _sd[_z]\n_w, _m, _c = fit(_X.copy(), 1.5)\n_w, _m, _c = np.asarray(_w, float), np.asarray(_m, float), np.asarray(_c, float)\nprint(_w.ndim, _m.shape[1], _c.shape[1:], len(_w) == len(_m) == len(_c), len(_w) <= 32)","expected_output":"1 2 (2, 2) True True"},{"test":"import numpy as np\n_r = np.random.default_rng(0)\n_mu = np.array([[-6.0, 0.0], [6.0, 2.0], [0.0, 8.0]])\n_sd = np.array([[1.0, 0.3], [0.4, 1.5], [0.7, 0.7]])\n_z = _r.integers(0, 3, 900)\n_X = _mu[_z] + _r.normal(size=(900, 2)) * _sd[_z]\n_w, _m, _c = fit(_X.copy(), 1.5)\n_w, _m, _c = np.asarray(_w, float), np.asarray(_m, float), np.asarray(_c, float)\nprint(bool(abs(_w.sum() - 1) < 1e-6 and (_w >= 0).all() and np.abs(_c - _c.transpose(0, 2, 1)).max() < 1e-6 and np.linalg.eigvalsh(_c).min() > 0))","expected_output":"True"},{"test":"import numpy as np\n_r = np.random.default_rng(0)\n_mu = np.array([[-6.0, 0.0], [6.0, 2.0], [0.0, 8.0]])\n_sd = np.array([[1.0, 0.3], [0.4, 1.5], [0.7, 0.7]])\n_z = _r.integers(0, 3, 900)\n_X = _mu[_z] + _r.normal(size=(900, 2)) * _sd[_z]\n_w, _m, _c = fit(_X.copy(), 1.5)\n_w, _m, _c = np.asarray(_w, float), np.asarray(_m, float), np.asarray(_c, float)\n_t = _r.integers(0, 3, 20000)\n_Y = _mu[_t] + _r.normal(size=(20000, 2)) * _sd[_t]\n_lp = np.log(sum(np.exp(-0.5 * (((_Y - _mu[k]) / _sd[k]) ** 2).sum(1)) / (2 * np.pi * _sd[k].prod()) / 3 for k in range(3)))\ndef _lq(Y):\n    t = []\n    for k in range(len(_w)):\n        L = np.linalg.cholesky(_c[k])\n        y = np.linalg.solve(L, (Y - _m[k]).T)\n        t.append(np.log(_w[k] + 1e-300) - 0.5 * (y * y).sum(0) - np.log(np.diag(L)).sum() - np.log(2 * np.pi))\n    t = np.stack(t, 1)\n    a = t.max(1, keepdims=True)\n    return a[:, 0] + np.log(np.exp(t - a).sum(1))\n_kl = float((_lp - _lq(_Y)).mean()) / 2\nprint(bool(_kl < 0.1))","expected_output":"True"},{"test":"import numpy as np\n_r = np.random.default_rng(0)\n_mu = np.array([[-6.0, 0.0], [6.0, 2.0], [0.0, 8.0]])\n_sd = np.array([[1.0, 0.3], [0.4, 1.5], [0.7, 0.7]])\n_z = _r.integers(0, 3, 900)\n_X = _mu[_z] + _r.normal(size=(900, 2)) * _sd[_z]\n_w, _m, _c = fit(_X.copy(), 1.5)\n_w, _m, _c = np.asarray(_w, float), np.asarray(_m, float), np.asarray(_c, float)\n_t = _r.integers(0, 3, 20000)\n_Y = _mu[_t] + _r.normal(size=(20000, 2)) * _sd[_t]\n_lp = np.log(sum(np.exp(-0.5 * (((_Y - _mu[k]) / _sd[k]) ** 2).sum(1)) / (2 * np.pi * _sd[k].prod()) / 3 for k in range(3)))\ndef _lq(Y):\n    t = []\n    for k in range(len(_w)):\n        L = np.linalg.cholesky(_c[k])\n        y = np.linalg.solve(L, (Y - _m[k]).T)\n        t.append(np.log(_w[k] + 1e-300) - 0.5 * (y * y).sum(0) - np.log(np.diag(L)).sum() - np.log(2 * np.pi))\n    t = np.stack(t, 1)\n    a = t.max(1, keepdims=True)\n    return a[:, 0] + np.log(np.exp(t - a).sum(1))\n_kl = float((_lp - _lq(_Y)).mean()) / 2\nprint(bool(_kl < 0.02))","expected_output":"True"}],"approved_user_libraries":["numpy","scipy","sklearn","torch"],"lower_is_better":true,"time_limits":{"test":360,"dev":210},"data_info":"Generated by the grader from hidden seeds, with no dataset. Each task draws X_train from its own density, with its own random rotation, column scales (0.1 to 10) and offsets. D is 2 to 16, N is 120 to 4,000. 40,000 further samples from the same density score your mixture and never leave the grader's scoring process.\n\nRun (29 tasks) uses these families, with the names the report prints:\n- blobs: 2 to 20 separated Gaussians of unequal weight, size and elongation\n- overlap: 2 to 8 heavily overlapping Gaussians\n- tied: 3 to 20 Gaussians sharing one elongated covariance\n- lowrank: 2 to 8 Gaussians whose covariances are low rank plus a little noise\n- curve: a thin noisy closed curve or spiral in 2 or 3 dimensions, with Gaussian noise in the remaining dimensions\n- sheet: a thin rolled-up sheet in 3 dimensions, with Gaussian noise in the remaining dimensions\n- heavy: 1 to 5 multivariate Student-t components\n- warped: a small Gaussian mixture passed through a skewing, tail-changing map on each coordinate\n- banana: a small Gaussian mixture bent by quadratic shears\n\nSubmit (52 tasks) uses all of these with fresh densities, plus four families that are not described here. Its summary names them after the run.","gpu":false,"description":"## Best Gaussian Mixture Density\n\nYou get a table of numbers drawn from a density you are never told, and you answer with a mixture of at most 32 full-covariance Gaussians. The grader knows the true density, computes your mixture's density itself, and measures how far apart the two are. The closest mixture wins.\n\n### What you write\n\n```python\ndef fit(X_train, time_budget_s):\n    ...\n    return weights, means, covs     # shapes (K,), (K, D), (K, D, D), with K <= 32\n```\n\n- `X_train`: float64 array of shape `(N, D)`, one sample per row, with $D$ from 2 to 16 and $N$ from 120 to 4,000. Columns come with arbitrary offsets and scales.\n- `time_budget_s`: the wall-clock seconds this call may use, 4 on every task.\n- `fit` is called once per task, and every task has its own density.\n\n### How it is graded\n\nFor one task with true density $p$ and your mixture $q$, the grader draws 40,000 fresh samples from $p$ and estimates the KL divergence per dimension, capped at 1:\n\n$$\ns = \\min\\left( \\frac{1}{D} \\, \\mathbb{E}_{x \\sim p}\\left[ \\log p(x) - \\log q(x) \\right], \\; 1 \\right)\n$$\n\nYour score is the mean of $s$ over all tasks, in nats per dimension. **Lower is better**, $0$ means your mixture equals the truth, and the lab is passed at **0.21 or below**. The score is the held-out negative log likelihood per dimension minus the true density's entropy per dimension. Rescaling or rotating the data does not change it.\n\n- **Run**: 29 tasks. The report has one line per task with its family, $D$, $N$, your $K$, your $s$ and your seconds, then a per-family summary.\n- **Submit**: 52 tasks with fresh densities, including four families of shapes that Run never shows. The report has the per-family summary only.\n\n### Budgets and rules\n\n- One `fit` call may take 4 s of wall-clock time, including any conversion of what you return. A call that runs past 4.6 s fails the run. Machines vary, so read the clock in your own code and leave a margin.\n- Libraries: numpy, scipy, scikit-learn and torch (CPU), plus math, itertools, collections, heapq, bisect, random, statistics, time, warnings, typing.\n- You can write ordinary classes: `self.x = ...` is fine inside a method written in a class body. Any other attribute assignment or deletion (`np.mean = ...`, `model.weights_ = ...`) is refused, because it could change how your run is graded.\n- `getattr`, `setattr`, `vars`, `open`, most dunder attributes and names such as `os`, `sys`, `json`, `functools`, `load` and `save` are refused anywhere in your source, including as your own variable names.\n- Your code may not write files. A run that changes any file under the Python installation or the system libraries fails.\n- Your source is capped at 30,000 characters, 800 numeric literals and 3,000 characters of string constants.\n\n### What fails the run\n\nAny of these sets the score to 99 and exits: more than 32 components; a wrong shape; a NaN or infinity; weights that are negative or do not sum to 1 within $10^{-6}$; a covariance that is not symmetric; a covariance whose smallest eigenvalue is below 1e-06 times the smallest column variance of `X_train`; an exception; a call over the time limit; a refused construct in your source.\n","tags":["gaussian-mixture","em","map-estimation","density-estimation","kl-divergence","competitive","pml-book"],"id":"1b19b370-372b-470e-b722-87e4c5bbec66","dataset_id":"synthetic","img_type":"full","difficulty":"hard","evaluation_metric":"kl_nats_per_dim","min_eval_metric":0.21,"category":"Machine Learning","dataset":"Hidden densities generated by the grader","title":"Best Gaussian Mixture Density","time_limits_seconds":{"dev":210,"test":360}},{"created_at":"2026-10-27T19:54:02.975000+00:00","type":"general","test_cases":[{"test":"import base64 as _tc_b64\n_TC = {}\nexec(_tc_b64.b64decode('IyAtLS0tIFVPcCBJUiAoZHJhZnRzL3Vpci9TUEVDLm1kIHN1YnNldCB1c2VkIGJ5IHRoZSB3ZWVrLTcgbGFiKSAtLS0tCkxPRzJFID0gMS40NDI2OTUwNDA4ODg5NjM0CkxOMiA9IDAuNjkzMTQ3MTgwNTU5OTQ1MwpfVU5BUlkgPSAoIlJFQ0lQIiwgIlNRUlQiLCAiRVhQMiIsICJMT0cyIikKX0JJTkFSWSA9ICgiQUREIiwgIk1VTCIsICJNQVgiLCAiQ01QTFQiKQpfTU9WRU1FTlQgPSAoIlJFU0hBUEUiLCAiUEVSTVVURSIsICJFWFBBTkQiKQoKCmNsYXNzIFVPcDoKICAgICIiIkltbXV0YWJsZSwgaGFzaC1jb25zZWQgVU9wKG9wLCBzcmMsIGFyZykgd2l0aCBkZXJpdmVkIGR0eXBlIGFuZCBzaGFwZS4iIiIKICAgIF9fc2xvdHNfXyA9ICgib3AiLCAic3JjIiwgImFyZyIsICJkdHlwZSIsICJzaGFwZSIpCiAgICBfY2FjaGUgPSB7fQoKICAgIGRlZiBfX3NldGF0dHJfXyhzZWxmLCBuYW1lLCB2YWx1ZSk6CiAgICAgICAgcmFpc2UgQXR0cmlidXRlRXJyb3IoIlVPcHMgYXJlIGltbXV0YWJsZSIpCgogICAgZGVmIF9fcmVwcl9fKHNlbGYpOgogICAgICAgIHJldHVybiBmIlVPcCh7c2VsZi5vcH0sIHNoYXBlPXtzZWxmLnNoYXBlfSwgYXJnPXtzZWxmLmFyZyFyfSkiCgogICAgZGVmIHRvcG9zb3J0KHNlbGYpOgogICAgICAgICIiIkV2ZXJ5IG5vZGUgdGhpcyBvbmUgZGVwZW5kcyBvbiAoaXRzZWxmIGxhc3QpLCBlYWNoIG9uY2UsIGNoaWxkcmVuIGJlZm9yZSBwYXJlbnRzLiIiIgogICAgICAgIHNlZW4sIG9yZGVyLCBzdGFjayA9IHNldCgpLCBbXSwgWyhzZWxmLCBGYWxzZSldCiAgICAgICAgd2hpbGUgc3RhY2s6CiAgICAgICAgICAgIHUsIGRvbmUgPSBzdGFjay5wb3AoKQogICAgICAgICAgICBpZiBkb25lOgogICAgICAgICAgICAgICAgb3JkZXIuYXBwZW5kKHUpCiAgICAgICAgICAgICAgICBjb250aW51ZQogICAgICAgICAgICBpZiBpZCh1KSBpbiBzZWVuOgogICAgICAgICAgICAgICAgY29udGludWUKICAgICAgICAgICAgc2Vlbi5hZGQoaWQodSkpCiAgICAgICAgICAgIHN0YWNrLmFwcGVuZCgodSwgVHJ1ZSkpCiAgICAgICAgICAgIGZvciBzIGluIHJldmVyc2VkKHUuc3JjKToKICAgICAgICAgICAgICAgIGlmIGlkKHMpIG5vdCBpbiBzZWVuOgogICAgICAgICAgICAgICAgICAgIHN0YWNrLmFwcGVuZCgocywgRmFsc2UpKQogICAgICAgIHJldHVybiBvcmRlcgoKCmRlZiBfcHJvZCh4cyk6CiAgICBwID0gMQogICAgZm9yIHggaW4geHM6CiAgICAgICAgcCAqPSB4CiAgICByZXR1cm4gcAoKCmRlZiBfZjMyKHYpOgogICAgaW1wb3J0IHN0cnVjdAogICAgcmV0dXJuIHN0cnVjdC51bnBhY2soImYiLCBzdHJ1Y3QucGFjaygiZiIsIGZsb2F0KHYpKSlbMF0KCgpkZWYgdW9wKG9wLCBzcmM9KCksIGFyZz1Ob25lKToKICAgIHNyYyA9IHR1cGxlKHNyYykKICAgIGlmIG9wID09ICJDT05TVCI6CiAgICAgICAgYXJnID0gX2YzMihhcmcpCiAgICBrZXkgPSAob3AsIHR1cGxlKGlkKHMpIGZvciBzIGluIHNyYyksIGFyZykKICAgIGhpdCA9IFVPcC5fY2FjaGUuZ2V0KGtleSkKICAgIGlmIGhpdCBpcyBub3QgTm9uZToKICAgICAgICByZXR1cm4gaGl0CiAgICBkdHlwZSwgc2hhcGUgPSAiZjMyIiwgKCkKICAgIGlmIG9wID09ICJCVUZGRVIiOgogICAgICAgIHNoYXBlID0gKGludChhcmdbMV0pLCkKICAgIGVsaWYgb3AgPT0gIkNPTlNUIjoKICAgICAgICBzaGFwZSA9ICgpCiAgICBlbGlmIG9wID09ICJSRVNIQVBFIjoKICAgICAgICBhc3NlcnQgX3Byb2QoYXJnKSA9PSBfcHJvZChzcmNbMF0uc2hhcGUpLCAoYXJnLCBzcmNbMF0uc2hhcGUpCiAgICAgICAgc2hhcGUgPSB0dXBsZShhcmcpCiAgICBlbGlmIG9wID09ICJQRVJNVVRFIjoKICAgICAgICBhc3NlcnQgc29ydGVkKGFyZykgPT0gbGlzdChyYW5nZShsZW4oc3JjWzBdLnNoYXBlKSkpCiAgICAgICAgc2hhcGUgPSB0dXBsZShzcmNbMF0uc2hhcGVbaV0gZm9yIGkgaW4gYXJnKQogICAgZWxpZiBvcCA9PSAiRVhQQU5EIjoKICAgICAgICBhc3NlcnQgbGVuKGFyZykgPT0gbGVuKHNyY1swXS5zaGFwZSkgYW5kIGFsbChzIGluICgxLCB0KSBmb3IgcywgdCBpbiB6aXAoc3JjWzBdLnNoYXBlLCBhcmcpKQogICAgICAgIHNoYXBlID0gdHVwbGUoYXJnKQogICAgZWxpZiBvcCA9PSAiUkVEVUNFIjoKICAgICAgICBhc3NlcnQgYXJnWzBdIGluICgiYWRkIiwgIm1heCIpIGFuZCAxIDw9IGFyZ1sxXSA8PSBsZW4oc3JjWzBdLnNoYXBlKQogICAgICAgIHNoYXBlID0gc3JjWzBdLnNoYXBlW2FyZ1sxXTpdCiAgICBlbGlmIG9wIGluIF9VTkFSWToKICAgICAgICBzaGFwZSA9IHNyY1swXS5zaGFwZQogICAgZWxpZiBvcCBpbiBfQklOQVJZOgogICAgICAgIGEsIGIgPSBzcmMKICAgICAgICBhc3NlcnQgYS5zaGFwZSA9PSBiLnNoYXBlIG9yIGEuc2hhcGUgPT0gKCkgb3IgYi5zaGFwZSA9PSAoKSwgKG9wLCBhLnNoYXBlLCBiLnNoYXBlKQogICAgICAgIHNoYXBlID0gYS5zaGFwZSBpZiBhLnNoYXBlICE9ICgpIGVsc2UgYi5zaGFwZQogICAgICAgIGR0eXBlID0gImJvb2wiIGlmIG9wID09ICJDTVBMVCIgZWxzZSAiZjMyIgogICAgZWxpZiBvcCA9PSAiV0hFUkUiOgogICAgICAgIHNoYXBlID0gbWF4KChzLnNoYXBlIGZvciBzIGluIHNyYyksIGtleT1sZW4pCiAgICAgICAgYXNzZXJ0IGFsbChzLnNoYXBlIGluICgoKSwgc2hhcGUpIGZvciBzIGluIHNyYykKICAgIGVsc2U6CiAgICAgICAgcmFpc2UgVmFsdWVFcnJvcihvcCkKICAgIHUgPSBvYmplY3QuX19uZXdfXyhVT3ApCiAgICBmb3IgaywgdiBpbiAoKCJvcCIsIG9wKSwgKCJzcmMiLCBzcmMpLCAoImFyZyIsIGFyZyksICgiZHR5cGUiLCBkdHlwZSksICgic2hhcGUiLCBzaGFwZSkpOgogICAgICAgIG9iamVjdC5fX3NldGF0dHJfXyh1LCBrLCB2KQogICAgVU9wLl9jYWNoZVtrZXldID0gdQogICAgcmV0dXJuIHUKCgpkZWYgX2xpdCh2KToKICAgIHJldHVybiB1b3AoIkNPTlNUIiwgKCksIHYpIGlmIG5vdCBpc2luc3RhbmNlKHYsIFVPcCkgZWxzZSB2CgoKZGVmIGJ1ZmZlcihzbG90LCBuKTogcmV0dXJuIHVvcCgiQlVGRkVSIiwgKCksIChzbG90LCBuKSkKZGVmIHJlc2hhcGUoeCwgc2hhcGUpOiByZXR1cm4gdW9wKCJSRVNIQVBFIiwgKHgsKSwgdHVwbGUoc2hhcGUpKQpkZWYgcGVybXV0ZSh4LCBvcmRlcik6IHJldHVybiB1b3AoIlBFUk1VVEUiLCAoeCwpLCB0dXBsZShvcmRlcikpCmRlZiBleHBhbmQoeCwgc2hhcGUpOiByZXR1cm4gdW9wKCJFWFBBTkQiLCAoeCwpLCB0dXBsZShzaGFwZSkpCmRlZiByZWR1Y2UoeCwgb3AsIHBvcD0xKTogcmV0dXJuIHVvcCgiUkVEVUNFIiwgKHgsKSwgKG9wLCBwb3ApKQpkZWYgYWRkKGEsIGIpOiByZXR1cm4gdW9wKCJBREQiLCAoX2xpdChhKSwgX2xpdChiKSkpCmRlZiBtdWwoYSwgYik6IHJldHVybiB1b3AoIk1VTCIsIChfbGl0KGEpLCBfbGl0KGIpKSkKZGVmIG1heGltdW0oYSwgYik6IHJldHVybiB1b3AoIk1BWCIsIChfbGl0KGEpLCBfbGl0KGIpKSkKZGVmIGNtcGx0KGEsIGIpOiByZXR1cm4gdW9wKCJDTVBMVCIsIChfbGl0KGEpLCBfbGl0KGIpKSkKZGVmIHdoZXJlKGMsIGEsIGIpOiByZXR1cm4gdW9wKCJXSEVSRSIsIChjLCBfbGl0KGEpLCBfbGl0KGIpKSkKZGVmIHJlY2lwKHgpOiByZXR1cm4gdW9wKCJSRUNJUCIsICh4LCkpCmRlZiBzcXJ0KHgpOiByZXR1cm4gdW9wKCJTUVJUIiwgKHgsKSkKZGVmIGV4cDIoeCk6IHJldHVybiB1b3AoIkVYUDIiLCAoeCwpKQpkZWYgbG9nMih4KTogcmV0dXJuIHVvcCgiTE9HMiIsICh4LCkpCmRlZiBuZWcoeCk6IHJldHVybiBtdWwoeCwgLTEuMCkKZGVmIHN1YihhLCBiKTogcmV0dXJuIGFkZChhLCBuZWcoYikpCgoKZGVmIHJvd3ModiwgUiwgQyk6CiAgICAiIiJbUl0gLT4gW1IsIENdLCBvbmUgdmFsdWUgcGVyIHJvdy4iIiIKICAgIHJldHVybiBleHBhbmQocmVzaGFwZSh2LCAoUiwgMSkpLCAoUiwgQykpCgoKZGVmIGNvbHModiwgUiwgQyk6CiAgICAiIiJbQ10gLT4gW1IsIENdLCBvbmUgdmFsdWUgcGVyIGNvbHVtbi4iIiIKICAgIHJldHVybiBleHBhbmQocmVzaGFwZSh2LCAoMSwgQykpLCAoUiwgQykpCgoKZGVmIHJvd19yZWR1Y2UoeCwgb3ApOgogICAgIiIiW1IsIENdIC0+IFtSXSwgcmVkdWNpbmcgZWFjaCByb3cgKFJFRFVDRSBwb3BzIGxlYWRpbmcgYXhlcywgc28gdGhlIHJvdyBheGlzIGdvZXMgbGFzdCBmaXJzdCkuIiIiCiAgICByZXR1cm4gcmVkdWNlKHBlcm11dGUoeCwgKDEsIDApKSwgb3AsIDEpCgoKZGVmIHRvX3RleHQocm9vdCk6CiAgICAiIiJDYW5vbmljYWwgLnVpciB0ZXh0OiBvbmUgc3RhdGVtZW50IHBlciBub2RlIGluIHRvcG9sb2dpY2FsIG9yZGVyLCBsaXRlcmFscyBpbmxpbmUuIiIiCiAgICBuYW1lcywgbGluZXMgPSB7fSwgW10KICAgIGZvciB1IGluIHJvb3QudG9wb3NvcnQoKToKICAgICAgICBpZiB1Lm9wID09ICJDT05TVCI6CiAgICAgICAgICAgIGNvbnRpbnVlCgogICAgICAgIGRlZiByZWYocyk6CiAgICAgICAgICAgIHJldHVybiBuYW1lc1tpZChzKV0gaWYgcy5vcCAhPSAiQ09OU1QiIGVsc2UgcmVwcihzLmFyZykKICAgICAgICBuYW1lID0gIiUiICsgc3RyKGxlbihuYW1lcykpCiAgICAgICAgbmFtZXNbaWQodSldID0gbmFtZQogICAgICAgIGxvID0gdS5vcC5sb3dlcigpCiAgICAgICAgaWYgdS5vcCA9PSAiQlVGRkVSIjoKICAgICAgICAgICAgcmhzID0gZiJidWZmZXIge3UuYXJnWzFdfSA6IGR0eXBlPWYzMiBzbG90PXt1LmFyZ1swXX0iCiAgICAgICAgZWxpZiB1Lm9wIGluIF9NT1ZFTUVOVDoKICAgICAgICAgICAgcmhzID0gZiJ7bG99IHtyZWYodS5zcmNbMF0pfSBbeycgJy5qb2luKHN0cih4KSBmb3IgeCBpbiB1LmFyZyl9XSIKICAgICAgICBlbGlmIHUub3AgPT0gIlJFRFVDRSI6CiAgICAgICAgICAgIHJocyA9IGYicmVkdWNlIHtyZWYodS5zcmNbMF0pfSA6IG9wPXt1LmFyZ1swXX0gcG9wPXt1LmFyZ1sxXX0iCiAgICAgICAgZWxzZToKICAgICAgICAgICAgcmhzID0gbG8gKyAiICIgKyAiICIuam9pbihyZWYocykgZm9yIHMgaW4gdS5zcmMpCiAgICAgICAgbGluZXMuYXBwZW5kKGYie25hbWV9ID0ge3Joc30iKQogICAgbGluZXMuYXBwZW5kKGYiJXJlc3VsdCA9IHtuYW1lc1tpZChyb290KV19IikKICAgIHJldHVybiAiXG4iLmpvaW4obGluZXMpICsgIlxuIgoKCmNsYXNzIFByb2dyYW06CiAgICAiIiJXaGF0IGNvZGVnZW4ocHJvZ3JhbSkgcmVjZWl2ZXMuIiIiCiAgICBfX3Nsb3RzX18gPSAoIm5hbWUiLCAicm9vdCIsICJpbnB1dHMiLCAib3V0X3NoYXBlIiwgInRleHQiKQoKICAgIGRlZiBfX2luaXRfXyhzZWxmLCBuYW1lLCByb290LCBpbnB1dHMpOgogICAgICAgIG9iamVjdC5fX3NldGF0dHJfXyhzZWxmLCAibmFtZSIsIG5hbWUpCiAgICAgICAgb2JqZWN0Ll9fc2V0YXR0cl9fKHNlbGYsICJyb290Iiwgcm9vdCkKICAgICAgICBvYmplY3QuX19zZXRhdHRyX18oc2VsZiwgImlucHV0cyIsIHR1cGxlKGlucHV0cykpCiAgICAgICAgb2JqZWN0Ll9fc2V0YXR0cl9fKHNlbGYsICJvdXRfc2hhcGUiLCByb290LnNoYXBlKQogICAgICAgIG9iamVjdC5fX3NldGF0dHJfXyhzZWxmLCAidGV4dCIsIHRvX3RleHQocm9vdCkpCgogICAgZGVmIF9fc2V0YXR0cl9fKHNlbGYsIG5hbWUsIHZhbHVlKToKICAgICAgICByYWlzZSBBdHRyaWJ1dGVFcnJvcigicHJvZ3JhbXMgYXJlIGltbXV0YWJsZSIpCgogICAgZGVmIF9fcmVwcl9fKHNlbGYpOgogICAgICAgIHJldHVybiBmIlByb2dyYW0oe3NlbGYubmFtZX0sIG91dF9zaGFwZT17c2VsZi5vdXRfc2hhcGV9LCBpbnB1dHM9e1tiLmFyZyBmb3IgYiBpbiBzZWxmLmlucHV0c119KSIKCiMgLS0tLSBwcm9ncmFtIGZhbWlsaWVzOiAoVU9wIGdyYXBoLCB0b3JjaCBiYXNlbGluZSkgcGFpcnMgLS0tLQojIEV2ZXJ5IGZhbWlseSByZXR1cm5zIChyb290LCBidWZmZXJzLCBiYXNlbGluZSwga2luZCk7IGJhc2VsaW5lKGxpc3Qgb2YgZmxhdCB0b3JjaCB0ZW5zb3JzKSAtPiBvdXRwdXQgdGVuc29yIHdpdGgKIyByb290LnNoYXBlLCB3cml0dGVuIHRoZSB3YXkgYSBQeVRvcmNoIHVzZXIgd291bGQgKGZ1c2VkIGxpYnJhcnkga2VybmVscyB3aGVyZSB0b3JjaCBoYXMgdGhlbSkuCgpkZWYgZmFtX2JpYXNfYWN0KFIsIEMsIGFjdCk6CiAgICBYLCBiLCBzID0gYnVmZmVyKDAsIFIgKiBDKSwgYnVmZmVyKDEsIEMpLCBidWZmZXIoMiwgUikKICAgIHkgPSBhZGQocmVzaGFwZShYLCAoUiwgQykpLCBjb2xzKGIsIFIsIEMpKQogICAgaWYgYWN0ID09ICJyZWx1IjoKICAgICAgICBhID0gbWF4aW11bSh5LCAwLjApCiAgICBlbGlmIGFjdCA9PSAic2lsdSI6CiAgICAgICAgYSA9IG11bCh5LCByZWNpcChhZGQoZXhwMihtdWwoeSwgLUxPRzJFKSksIDEuMCkpKQogICAgZWxzZTogICMgbGVha3kKICAgICAgICBhID0gd2hlcmUoY21wbHQoeSwgMC4wKSwgbXVsKHksIDAuMDEpLCB5KQogICAgcm9vdCA9IG11bChhLCByb3dzKHMsIFIsIEMpKQoKICAgIGRlZiBiYXNlKHQpOgogICAgICAgIGltcG9ydCB0b3JjaC5ubi5mdW5jdGlvbmFsIGFzIEYKICAgICAgICB5XyA9IHRbMF0udmlldyhSLCBDKSArIHRbMV0KICAgICAgICBhXyA9IEYucmVsdSh5XykgaWYgYWN0ID09ICJyZWx1IiBlbHNlIEYuc2lsdSh5XykgaWYgYWN0ID09ICJzaWx1IiBlbHNlIEYubGVha3lfcmVsdSh5XywgMC4wMSkKICAgICAgICByZXR1cm4gYV8gKiB0WzJdLnZpZXcoUiwgMSkKICAgIHJldHVybiByb290LCBbWCwgYiwgc10sIGJhc2UKCgpkZWYgZmFtX3NvZnRtYXgoUiwgQywgc2NhbGU9Tm9uZSwgbWFzaz1GYWxzZSk6CiAgICBYID0gYnVmZmVyKDAsIFIgKiBDKQogICAgYnVmcyA9IFtYXQogICAgeCA9IHJlc2hhcGUoWCwgKFIsIEMpKQogICAgaWYgc2NhbGUgaXMgbm90IE5vbmU6CiAgICAgICAgeCA9IG11bCh4LCBzY2FsZSkKICAgIGlmIG1hc2s6CiAgICAgICAgTSA9IGJ1ZmZlcigxLCBSICogQykKICAgICAgICBidWZzLmFwcGVuZChNKQogICAgICAgIHggPSBhZGQoeCwgcmVzaGFwZShNLCAoUiwgQykpKQogICAgbSA9IHJvd19yZWR1Y2UoeCwgIm1heCIpCiAgICBlID0gZXhwMihtdWwoc3ViKHgsIHJvd3MobSwgUiwgQykpLCBMT0cyRSkpCiAgICByb290ID0gbXVsKGUsIHJvd3MocmVjaXAocm93X3JlZHVjZShlLCAiYWRkIikpLCBSLCBDKSkKCiAgICBkZWYgYmFzZSh0KToKICAgICAgICBpbXBvcnQgdG9yY2gKICAgICAgICB4XyA9IHRbMF0udmlldyhSLCBDKQogICAgICAgIGlmIHNjYWxlIGlzIG5vdCBOb25lOgogICAgICAgICAgICB4XyA9IHhfICogc2NhbGUKICAgICAgICBpZiBtYXNrOgogICAgICAgICAgICB4XyA9IHhfICsgdFsxXS52aWV3KFIsIEMpCiAgICAgICAgcmV0dXJuIHRvcmNoLnNvZnRtYXgoeF8sIC0xKQogICAgcmV0dXJuIHJvb3QsIGJ1ZnMsIGJhc2UKCgpkZWYgZmFtX2xheWVybm9ybShSLCBDLCBlcHM9MWUtNSk6CiAgICBYLCBnLCBiID0gYnVmZmVyKDAsIFIgKiBDKSwgYnVmZmVyKDEsIEMpLCBidWZmZXIoMiwgQykKICAgIHggPSByZXNoYXBlKFgsIChSLCBDKSkKICAgIG1lYW4gPSBtdWwocm93X3JlZHVjZSh4LCAiYWRkIiksIDEuMCAvIEMpCiAgICBkID0gc3ViKHgsIHJvd3MobWVhbiwgUiwgQykpCiAgICB2YXIgPSBtdWwocm93X3JlZHVjZShtdWwoZCwgZCksICJhZGQiKSwgMS4wIC8gQykKICAgIGludiA9IHJlY2lwKHNxcnQoYWRkKHZhciwgZXBzKSkpCiAgICByb290ID0gYWRkKG11bChtdWwoZCwgcm93cyhpbnYsIFIsIEMpKSwgY29scyhnLCBSLCBDKSksIGNvbHMoYiwgUiwgQykpCgogICAgZGVmIGJhc2UodCk6CiAgICAgICAgaW1wb3J0IHRvcmNoLm5uLmZ1bmN0aW9uYWwgYXMgRgogICAgICAgIHJldHVybiBGLmxheWVyX25vcm0odFswXS52aWV3KFIsIEMpLCAoQywpLCB0WzFdLCB0WzJdLCBlcHMpCiAgICByZXR1cm4gcm9vdCwgW1gsIGcsIGJdLCBiYXNlCgoKZGVmIGZhbV9ybXNub3JtKFIsIEMsIGVwcz0xZS02KToKICAgIFgsIGcgPSBidWZmZXIoMCwgUiAqIEMpLCBidWZmZXIoMSwgQykKICAgIHggPSByZXNoYXBlKFgsIChSLCBDKSkKICAgIG1zID0gbXVsKHJvd19yZWR1Y2UobXVsKHgsIHgpLCAiYWRkIiksIDEuMCAvIEMpCiAgICByb290ID0gbXVsKG11bCh4LCByb3dzKHJlY2lwKHNxcnQoYWRkKG1zLCBlcHMpKSksIFIsIEMpKSwgY29scyhnLCBSLCBDKSkKCiAgICBkZWYgYmFzZSh0KToKICAgICAgICBpbXBvcnQgdG9yY2gubm4uZnVuY3Rpb25hbCBhcyBGCiAgICAgICAgcmV0dXJuIEYucm1zX25vcm0odFswXS52aWV3KFIsIEMpLCAoQywpLCB0WzFdLCBlcHMpCiAgICByZXR1cm4gcm9vdCwgW1gsIGddLCBiYXNlCgoKZGVmIGZhbV9sb2dzdW1leHAoUiwgQyk6CiAgICBYID0gYnVmZmVyKDAsIFIgKiBDKQogICAgeCA9IHJlc2hhcGUoWCwgKFIsIEMpKQogICAgbSA9IHJvd19yZWR1Y2UoeCwgIm1heCIpCiAgICBzID0gcm93X3JlZHVjZShleHAyKG11bChzdWIoeCwgcm93cyhtLCBSLCBDKSksIExPRzJFKSksICJhZGQiKQogICAgcm9vdCA9IGFkZChtLCBtdWwobG9nMihzKSwgTE4yKSkKCiAgICBkZWYgYmFzZSh0KToKICAgICAgICBpbXBvcnQgdG9yY2gKICAgICAgICByZXR1cm4gdG9yY2gubG9nc3VtZXhwKHRbMF0udmlldyhSLCBDKSwgLTEpCiAgICByZXR1cm4gcm9vdCwgW1hdLCBiYXNlCgoKZGVmIGZhbV9nZW1tKE0sIE4sIEssIGFfbGF5b3V0PSJtayIsIGVwaWxvZ3VlPU5vbmUpOgogICAgQSwgQiA9IGJ1ZmZlcigwLCBNICogSyksIGJ1ZmZlcigxLCBLICogTikKICAgIGJ1ZnMgPSBbQSwgQl0KICAgIGFfa20gPSBwZXJtdXRlKHJlc2hhcGUoQSwgKE0sIEspKSwgKDEsIDApKSBpZiBhX2xheW91dCA9PSAibWsiIGVsc2UgcmVzaGFwZShBLCAoSywgTSkpCiAgICBhMyA9IGV4cGFuZChyZXNoYXBlKGFfa20sIChLLCBNLCAxKSksIChLLCBNLCBOKSkKICAgIGIzID0gZXhwYW5kKHJlc2hhcGUoQiwgKEssIDEsIE4pKSwgKEssIE0sIE4pKQogICAgYWNjID0gcmVkdWNlKG11bChhMywgYjMpLCAiYWRkIiwgMSkKICAgIHJvb3QgPSBhY2MKICAgIGlmIGVwaWxvZ3VlIGluICgiYmlhc19yZWx1IiwgInJlc2lkdWFsIik6CiAgICAgICAgYmlhcyA9IGJ1ZmZlcigyLCBOKQogICAgICAgIGJ1ZnMuYXBwZW5kKGJpYXMpCiAgICAgICAgcm9vdCA9IGFkZChhY2MsIGNvbHMoYmlhcywgTSwgTikpCiAgICAgICAgaWYgZXBpbG9ndWUgPT0gImJpYXNfcmVsdSI6CiAgICAgICAgICAgIHJvb3QgPSBtYXhpbXVtKHJvb3QsIDAuMCkKICAgICAgICBlbHNlOgogICAgICAgICAgICByZXMgPSBidWZmZXIoMywgTSAqIE4pCiAgICAgICAgICAgIGJ1ZnMuYXBwZW5kKHJlcykKICAgICAgICAgICAgcm9vdCA9IGFkZChyb290LCByZXNoYXBlKHJlcywgKE0sIE4pKSkKCiAgICBkZWYgYmFzZSh0KToKICAgICAgICBpbXBvcnQgdG9yY2gKICAgICAgICBhXyA9IHRbMF0udmlldyhNLCBLKSBpZiBhX2xheW91dCA9PSAibWsiIGVsc2UgdFswXS52aWV3KEssIE0pLnQoKQogICAgICAgIG91dCA9IGFfIEAgdFsxXS52aWV3KEssIE4pCiAgICAgICAgaWYgZXBpbG9ndWUgPT0gImJpYXNfcmVsdSI6CiAgICAgICAgICAgIG91dCA9IHRvcmNoLnJlbHUob3V0ICsgdFsyXSkKICAgICAgICBlbGlmIGVwaWxvZ3VlID09ICJyZXNpZHVhbCI6CiAgICAgICAgICAgIG91dCA9IG91dCArIHRbMl0gKyB0WzNdLnZpZXcoTSwgTikKICAgICAgICByZXR1cm4gb3V0CiAgICByZXR1cm4gcm9vdCwgYnVmcywgYmFzZQoKCmRlZiBmYW1fdHJhbnNwb3NlX2FkZChSLCBDKToKICAgIFgsIFkgPSBidWZmZXIoMCwgUiAqIEMpLCBidWZmZXIoMSwgQyAqIFIpCiAgICByb290ID0gYWRkKHBlcm11dGUocmVzaGFwZShYLCAoUiwgQykpLCAoMSwgMCkpLCByZXNoYXBlKFksIChDLCBSKSkpCgogICAgZGVmIGJhc2UodCk6CiAgICAgICAgcmV0dXJuIHRbMF0udmlldyhSLCBDKS50KCkgKyB0WzFdLnZpZXcoQywgUikKICAgIHJldHVybiByb290LCBbWCwgWV0sIGJhc2UKCgpkZWYgZmFtX2NvbHN1bShSLCBDKToKICAgIFggPSBidWZmZXIoMCwgUiAqIEMpCiAgICByb290ID0gcmVkdWNlKHJlc2hhcGUoWCwgKFIsIEMpKSwgImFkZCIsIDEpCgogICAgZGVmIGJhc2UodCk6CiAgICAgICAgcmV0dXJuIHRbMF0udmlldyhSLCBDKS5zdW0oMCkKICAgIHJldHVybiByb290LCBbWF0sIGJhc2UKCgpGQU1JTElFUyA9IHsKICAgICJiaWFzX2FjdCI6IGZhbV9iaWFzX2FjdCwgInNvZnRtYXgiOiBmYW1fc29mdG1heCwgImxheWVybm9ybSI6IGZhbV9sYXllcm5vcm0sICJybXNub3JtIjogZmFtX3Jtc25vcm0sCiAgICAibG9nc3VtZXhwIjogZmFtX2xvZ3N1bWV4cCwgImdlbW0iOiBmYW1fZ2VtbSwgInRyYW5zcG9zZV9hZGQiOiBmYW1fdHJhbnNwb3NlX2FkZCwgImNvbHN1bSI6IGZhbV9jb2xzdW0sCn0KCgpkZWYgYnVpbGRfcHJvZ3JhbXMoc3BlY3MpOgogICAgIiIic3BlY3M6IGxpc3Qgb2YgKGZhbWlseSwga3dhcmdzKS4gUmV0dXJucyBbKFByb2dyYW0sIGJhc2VsaW5lLCBmbG9wc19vcl9ieXRlc19ub3RlKV0uIiIiCiAgICBvdXQgPSBbXQogICAgZm9yIGksIChmYW0sIGt3KSBpbiBlbnVtZXJhdGUoc3BlY3MpOgogICAgICAgIHJvb3QsIGJ1ZnMsIGJhc2UgPSBGQU1JTElFU1tmYW1dKCoqa3cpCiAgICAgICAgYXNzZXJ0IFtiLmFyZ1swXSBmb3IgYiBpbiBidWZzXSA9PSBsaXN0KHJhbmdlKGxlbihidWZzKSkpCiAgICAgICAgb3V0LmFwcGVuZCgoUHJvZ3JhbShmInByb2dyYW1fe2l9Iiwgcm9vdCwgYnVmcyksIGJhc2UsIGZhbSkpCiAgICByZXR1cm4gb3V0CgojIC0tLS0gaGVscGVycyBmb3IgdGhlIGxhYidzIHF1aWNrIHRlc3QgY2FzZXMgKGVtYmVkZGVkIGJhc2U2NCBhZnRlciBpci5weSArIGZhbWlsaWVzLnB5KSAtLS0tCmltcG9ydCBjdHlwZXMgYXMgX2N0CmltcG9ydCBvcyBhcyBfb3MKaW1wb3J0IHN1YnByb2Nlc3MgYXMgX3NwCmltcG9ydCB0ZW1wZmlsZSBhcyBfdGYKaW1wb3J0IHRpbWUgYXMgX3RpbWUKCmltcG9ydCB0b3JjaCBhcyBfdG9yY2gKCgpkZWYgdGNfYnVpbGQoZmFtLCAqKmt3KToKICAgIHByb2csIGJhc2UsIF8gPSBidWlsZF9wcm9ncmFtcyhbKGZhbSwga3cpXSlbMF0KICAgIHJldHVybiBwcm9nLCBiYXNlCgoKZGVmIHRjX2NvbXBpbGUoc3JjKToKICAgIGQgPSBfdGYubWtkdGVtcChwcmVmaXg9ImRtbF90Y18iKQogICAgY3UsIHNvID0gX29zLnBhdGguam9pbihkLCAiay5jdSIpLCBfb3MucGF0aC5qb2luKGQsICJrLnNvIikKICAgIHdpdGggb3BlbihjdSwgInciKSBhcyBmaDoKICAgICAgICBmaC53cml0ZShzcmMpCiAgICByID0gX3NwLnJ1bihbIm52Y2MiLCAiLU8zIiwgIi1hcmNoPXNtXzc1IiwgIi1zdGQ9YysrMTciLCAiLXNoYXJlZCIsICItWGNvbXBpbGVyIiwgIi1mUElDIiwgIi13IiwgIi1vIiwgc28sIGN1XSwKICAgICAgICAgICAgICAgIGNhcHR1cmVfb3V0cHV0PVRydWUsIHRleHQ9VHJ1ZSwgdGltZW91dD0xMjApCiAgICBpZiByLnJldHVybmNvZGUgIT0gMDoKICAgICAgICByYWlzZSBSdW50aW1lRXJyb3IoIm52Y2MgZmFpbGVkOlxuIiArIChyLnN0ZGVyciBvciByLnN0ZG91dClbLTIwMDA6XSkKICAgIGZuID0gX2N0LkNETEwoc28pLmxhdW5jaAogICAgZm4uYXJndHlwZXMgPSBbX2N0LlBPSU5URVIoX2N0LmNfdm9pZF9wKV0KICAgIGZuLnJlc3R5cGUgPSBOb25lCiAgICByZXR1cm4gZm4KCgpkZWYgdGNfc2V0dXAoY29kZWdlbiwgZmFtLCBrdyk6CiAgICBwcm9nLCBiYXNlID0gdGNfYnVpbGQoZmFtLCAqKmt3KQogICAgZm4gPSB0Y19jb21waWxlKGNvZGVnZW4ocHJvZykpCiAgICBpbnMgPSBbX3RvcmNoLnJhbmRuKGIuYXJnWzFdLCBkZXZpY2U9ImN1ZGEiKSBmb3IgYiBpbiBwcm9nLmlucHV0c10KICAgIG4gPSAxCiAgICBmb3IgZCBpbiBwcm9nLm91dF9zaGFwZToKICAgICAgICBuICo9IGQKICAgIG91dCA9IF90b3JjaC5mdWxsKChuLCksIGZsb2F0KCJuYW4iKSwgZGV2aWNlPSJjdWRhIikKICAgIHB0cnMgPSAoX2N0LmNfdm9pZF9wICogKDEgKyBsZW4oaW5zKSkpKG91dC5kYXRhX3B0cigpLCAqW3QuZGF0YV9wdHIoKSBmb3IgdCBpbiBpbnNdKQogICAgcmV0dXJuIGZuLCBpbnMsIG91dCwgcHRycywgYmFzZQoKCmRlZiB0Y19jb3JyZWN0KGNvZGVnZW4sIGZhbSwgKiprdyk6CiAgICBmbiwgaW5zLCBvdXQsIHB0cnMsIGJhc2UgPSB0Y19zZXR1cChjb2RlZ2VuLCBmYW0sIGt3KQogICAgZm4ocHRycykKICAgIF90b3JjaC5jdWRhLnN5bmNocm9uaXplKCkKICAgIHJlZiA9IGJhc2UoaW5zKQogICAgbyA9IG91dC52aWV3KHJlZi5zaGFwZSkKICAgIGlmIG5vdCBib29sKF90b3JjaC5pc2Zpbml0ZShvKS5hbGwoKSk6CiAgICAgICAgcmV0dXJuIEZhbHNlCiAgICBkaWZmID0gKG8gLSByZWYpLmRvdWJsZSgpCiAgICByZXR1cm4gZmxvYXQoZGlmZi5ub3JtKCkgLyByZWYuZG91YmxlKCkubm9ybSgpKSA8PSAyZS0zIGFuZCBcCiAgICAgICAgZmxvYXQoZGlmZi5hYnMoKS5tYXgoKSAvIHJlZi5kb3VibGUoKS5hYnMoKS5tYXgoKSkgPD0gMmUtMgoKCmRlZiB0Y19zcGVlZHVwKGNvZGVnZW4sIGZhbSwgKiprdyk6CiAgICBmbiwgaW5zLCBvdXQsIHB0cnMsIGJhc2UgPSB0Y19zZXR1cChjb2RlZ2VuLCBmYW0sIGt3KQoKICAgIGRlZiB0KGYpOgogICAgICAgIGYoKQogICAgICAgIF90b3JjaC5jdWRhLnN5bmNocm9uaXplKCkKICAgICAgICB0aW1lcyA9IFtdCiAgICAgICAgZm9yIF8gaW4gcmFuZ2UoNyk6CiAgICAgICAgICAgIF90b3JjaC5jdWRhLnN5bmNocm9uaXplKCkKICAgICAgICAgICAgdDAgPSBfdGltZS5wZXJmX2NvdW50ZXIoKQogICAgICAgICAgICBmKCkKICAgICAgICAgICAgX3RvcmNoLmN1ZGEuc3luY2hyb25pemUoKQogICAgICAgICAgICB0aW1lcy5hcHBlbmQoX3RpbWUucGVyZl9jb3VudGVyKCkgLSB0MCkKICAgICAgICByZXR1cm4gc29ydGVkKHRpbWVzKVszXQogICAgcmV0dXJuIHQobGFtYmRhOiBiYXNlKGlucykpIC8gdChsYW1iZGE6IGZuKHB0cnMpKQo=').decode(), _TC)\nprint(callable(codegen))","expected_output":"True"},{"test":"_p, _b = _TC['tc_build']('bias_act', R=64, C=96, act='relu')\n_s = codegen(_p)\nprint(isinstance(_s, str) and 'launch' in _s)","expected_output":"True"},{"test":"print(all(_TC['tc_correct'](codegen, f, **kw) for f, kw in [\n    ('bias_act', dict(R=64, C=96, act='silu')), ('softmax', dict(R=33, C=50)),\n    ('layernorm', dict(R=17, C=40)), ('gemm', dict(M=40, N=24, K=56, epilogue='bias_relu')),\n    ('colsum', dict(R=70, C=30))]))","expected_output":"True"},{"test":"print(_TC['tc_speedup'](codegen, 'softmax', R=4096, C=1024) >= 0.5)","expected_output":"True"},{"test":"print(_TC['tc_speedup'](codegen, 'gemm', M=1024, N=1024, K=1024) >= 0.3)","expected_output":"True"}],"lower_is_better":false,"approved_user_libraries":["numpy"],"data_info":"Synthetic programs built inside the grader: elementwise chains with broadcasts, row reductions, matrix multiplies with and without fused epilogues, transposes and column reductions, at shapes from about 10^6 to 1.7x10^7 output elements. Inputs are standard-normal float32 tensors, refilled every repetition. Run: 6 programs; Submit: 12 held-out programs.","time_limits":{"test":300,"dev":180},"example":{"input":"program.text of a 2x3 bias-add:\n%0 = buffer 6 : dtype=f32 slot=0\n%1 = reshape %0 [2 3]\n%2 = buffer 3 : dtype=f32 slot=1\n%3 = reshape %2 [1 3]\n%4 = expand %3 [2 3]\n%5 = add %1 %4\n%result = %5","output":"CUDA source defining extern \"C\" void launch(float** bufs) that writes bufs[0][r * 3 + c] = bufs[1][r * 3 + c] + bufs[2][c]"},"gpu":true,"description":"Week 7 of *Compilers for Machine Learning* turns the compiler into a GPU compiler. In this lab you write only its back end: a function that turns a UOp program into CUDA C++. The grader compiles your source with `nvcc`, runs it on a Tesla T4 and times it against PyTorch running the same computation. Your score is how much faster (or slower) you are.\n\n## What you write\n\n```python\ndef codegen(program) -> str:\n    ...\n```\n\nIt returns the complete source of one CUDA C++ file that defines\n\n```cpp\nextern \"C\" void launch(float** bufs);\n```\n\n`bufs[0]` is the output and `bufs[1 + i]` is the input `BUFFER` with slot `i`. All of them are float32 device pointers to contiguous row-major data. `launch` may start any number of kernels; the grader synchronizes the device after it returns. You may allocate scratch memory with `cudaMalloc`, but allocation inside `launch` is timed, so allocate once and keep the pointer (for example in a `static` variable).\n\n## The programs\n\n`program.root` is the root `UOp` of a pure shape graph in the course's UOp format. A `UOp` has `op`, `src` (a tuple of UOps), `arg`, `dtype` and `shape`, and `root.toposort()` lists every node once, inputs first. `program.inputs` are the `BUFFER` nodes in slot order, `program.out_shape` is the output shape and `program.text` is the canonical `.uir` text. The ops:\n\n- `BUFFER` (arg `(slot, n)`): a flat float32 input with `n` elements.\n- `RESHAPE` (arg: new shape, row-major), `PERMUTE` (arg: axis order), `EXPAND` (arg: new shape; broadcasts axes of size 1).\n- `REDUCE` (arg `(op, k)`, op `\"add\"` or `\"max\"`): reduces the `k` leading axes.\n- `CONST` (arg: a float32 value, shape `()`): a literal operand that broadcasts against the other operand.\n- `ADD`, `MUL`, `MAX`, `CMPLT` (gives bool), `WHERE(cond, a, b)`, `RECIP`, `SQRT`, `EXP2`, `LOG2`.\n\nApart from literals, the operands of an op always have the same shape: broadcasting is explicit through `EXPAND`. There is no subtraction op, so `a - b` appears as `ADD(a, MUL(b, -1.0))`. The transcendentals `EXP2`, `LOG2` and `SQRT` are single ops here. The output is the root's value in row-major order.\n\n## How you are scored\n\nFor every program the grader calls `codegen`, checks the source (rules below) and compiles it with\n\n```\nnvcc -O3 -arch=sm_75 -std=c++17 -shared -Xcompiler -fPIC -w -o lib.so lib.cu\n```\n\nIt then runs warm-up rounds followed by timed repetitions. In each repetition the inputs are refilled with fresh standard-normal values and the output is filled with NaN. The grader flushes the L2 cache, times one call to your `launch` (wall clock with the device synchronized before and after), then times PyTorch's implementation of the same computation, written the way a PyTorch user would write it (`torch.matmul`, `torch.softmax`, `F.layer_norm`, eager elementwise ops and so on). Your output is checked against PyTorch's every repetition.\n\n- A program's **speedup** is the median PyTorch time divided by your median time.\n- The **score** (`speedup_vs_torch`) is the geometric mean of the speedups over all programs. Higher is better.\n- **Run** grades 6 programs. **Submit** grades 12 programs at other shapes, including op patterns that never appear in Run.\n- Submit needs a score of at least **0.75** to pass. The leaderboard ranks Submit scores.\n\nA run scores 0 if, in any repetition:\n\n- the output has NaN or inf;\n- the relative RMS error exceeds `2e-3`;\n- the maximum absolute error exceeds `2e-2` times the largest magnitude in PyTorch's output;\n- an input buffer changed;\n- anything was written past the end of the output.\n\n## Rules\n\n- `codegen` may import only `math`, `collections`, `heapq`, `bisect`, `itertools`, `functools`, `typing`, `dataclasses`, `re`, `string`, `textwrap` and `numpy`.\n- No file access, introspection, `eval`/`exec`/`compile`, or touching the grader.\n- All `codegen` calls together get 60 s on Run and 120 s on Submit.\n- The generated source may have at most 400,000 characters.\n- It may `#include` only `cuda_runtime.h`, `cuda_fp16.h`, `cuda_bf16.h`, `mma.h`, `math.h`/`cmath`, `stdint.h`/`cstdint`, `float.h`/`cfloat`, `limits.h`/`climits`, `cooperative_groups.h`, `cooperative_groups/reduce.h` and `cuda_pipeline.h`.\n- It may call no library beyond the CUDA runtime: no cuBLAS, cuDNN, CUB, Thrust, CUTLASS, NVRTC or the driver API.\n- Also not allowed: printing, exiting or aborting, file, process, signal or thread calls, `dlopen`/`dlsym`, `__attribute__`, destructors, and token pasting (`##`). Inline PTX is allowed.\n- Each source must compile within 120 s, and a single `launch` call must finish within 2 s.\n- Breaking any rule, a compile error, or a wrong result scores 0.\n\nThe GPU is a Tesla T4 (Turing, `sm_75`):\n\n- 40 SMs and up to 64 KB of shared memory per SM;\n- about 320 GB/s of DRAM bandwidth;\n- about 8 TFLOP/s of float32;\n- about 65 TFLOP/s on its fp16 tensor cores.\n\nThe starter is a complete, correct and deliberately naive compiler: one thread per output element, and every `REDUCE` computed into its own scratch buffer. It scores about 0.5 on Submit.\n","tags":["compilers","cuda","gpu","codegen","kernels","tensor-cores"],"id":"1d3c6673-32f5-44a6-8764-46ba194052f2","dataset_id":"synthetic","img_type":"triton","difficulty":"hard","evaluation_metric":"speedup_vs_torch","min_eval_metric":0.75,"category":"Compilers","dataset":"Synthetic UOp programs","title":"Fastest GPU Kernels","time_limits_seconds":{"dev":180,"test":300}},{"created_at":"2026-11-01T01:07:31.066000+00:00","type":"general","constraints":["budget of 5 to 60 full gradients per objective; a shard call costs 1 / oracle.shards; 5 s of your own time per objective","minimize returns a finite array of shape x0.shape; a fresh process per objective","module level and class bodies hold only imports, constants, and function and class definitions; no calls there","numpy, scipy, math, itertools, collections, heapq, bisect, random, statistics, time, warnings, typing, copy only; attributes may be assigned only on self, inside a method defined in a class body","source capped at 30000 characters, 500 numeric literals, 2000 characters of string constants"],"test_cases":[{"test":"import numpy as np\nclass BudgetExhausted(Exception):\n    pass\nclass _Toy:\n    shards = 0\n    def __init__(self, dim, budget):\n        r = np.random.default_rng(0)\n        self.Q = np.linalg.qr(r.normal(size=(dim, dim)))[0]\n        self.lam = 10.0 ** np.linspace(-2, 0, dim)\n        self.star = r.normal(size=dim)\n        self.dim, self.budget, self.spent = dim, budget, 0.0\n    @property\n    def remaining(self):\n        return self.budget - self.spent\n    def gap(self, x):\n        z = self.Q.T @ (np.asarray(x) - self.star)\n        return 0.5 * float(z @ (self.lam * z))\n    def __call__(self, x):\n        if self.remaining < 1:\n            raise BudgetExhausted('no budget left')\n        self.spent += 1\n        return self.gap(x) + 3.0, self.Q @ (self.lam * (self.Q.T @ (np.asarray(x) - self.star)))\n    def shard(self, x, j):\n        raise ValueError('this objective has no shards')\n_o = _Toy(20, 30)\n_x0 = np.zeros(20)\n_x = np.asarray(minimize(_o, _x0.copy(), 30), dtype=float)\nprint(_x.shape)","expected_output":"(20,)"},{"test":"import numpy as np\nclass BudgetExhausted(Exception):\n    pass\nclass _Toy:\n    shards = 0\n    def __init__(self, dim, budget):\n        r = np.random.default_rng(0)\n        self.Q = np.linalg.qr(r.normal(size=(dim, dim)))[0]\n        self.lam = 10.0 ** np.linspace(-2, 0, dim)\n        self.star = r.normal(size=dim)\n        self.dim, self.budget, self.spent = dim, budget, 0.0\n    @property\n    def remaining(self):\n        return self.budget - self.spent\n    def gap(self, x):\n        z = self.Q.T @ (np.asarray(x) - self.star)\n        return 0.5 * float(z @ (self.lam * z))\n    def __call__(self, x):\n        if self.remaining < 1:\n            raise BudgetExhausted('no budget left')\n        self.spent += 1\n        return self.gap(x) + 3.0, self.Q @ (self.lam * (self.Q.T @ (np.asarray(x) - self.star)))\n    def shard(self, x, j):\n        raise ValueError('this objective has no shards')\n_o = _Toy(20, 30)\n_x0 = np.zeros(20)\n_x = np.asarray(minimize(_o, _x0.copy(), 30), dtype=float)\nprint(bool(np.isfinite(_x).all()) and _o.spent <= 30)","expected_output":"True"},{"test":"import numpy as np\nclass BudgetExhausted(Exception):\n    pass\nclass _Toy:\n    shards = 0\n    def __init__(self, dim, budget):\n        r = np.random.default_rng(0)\n        self.Q = np.linalg.qr(r.normal(size=(dim, dim)))[0]\n        self.lam = 10.0 ** np.linspace(-2, 0, dim)\n        self.star = r.normal(size=dim)\n        self.dim, self.budget, self.spent = dim, budget, 0.0\n    @property\n    def remaining(self):\n        return self.budget - self.spent\n    def gap(self, x):\n        z = self.Q.T @ (np.asarray(x) - self.star)\n        return 0.5 * float(z @ (self.lam * z))\n    def __call__(self, x):\n        if self.remaining < 1:\n            raise BudgetExhausted('no budget left')\n        self.spent += 1\n        return self.gap(x) + 3.0, self.Q @ (self.lam * (self.Q.T @ (np.asarray(x) - self.star)))\n    def shard(self, x, j):\n        raise ValueError('this objective has no shards')\n_o = _Toy(20, 30)\n_x0 = np.zeros(20)\n_x = np.asarray(minimize(_o, _x0.copy(), 30), dtype=float)\nprint(bool(np.log10(_o.gap(_x) / _o.gap(_x0)) < -2.0))","expected_output":"True"},{"test":"import numpy as np\nclass BudgetExhausted(Exception):\n    pass\nclass _Toy:\n    shards = 0\n    def __init__(self, dim, budget):\n        r = np.random.default_rng(0)\n        self.Q = np.linalg.qr(r.normal(size=(dim, dim)))[0]\n        self.lam = 10.0 ** np.linspace(-2, 0, dim)\n        self.star = r.normal(size=dim)\n        self.dim, self.budget, self.spent = dim, budget, 0.0\n    @property\n    def remaining(self):\n        return self.budget - self.spent\n    def gap(self, x):\n        z = self.Q.T @ (np.asarray(x) - self.star)\n        return 0.5 * float(z @ (self.lam * z))\n    def __call__(self, x):\n        if self.remaining < 1:\n            raise BudgetExhausted('no budget left')\n        self.spent += 1\n        return self.gap(x) + 3.0, self.Q @ (self.lam * (self.Q.T @ (np.asarray(x) - self.star)))\n    def shard(self, x, j):\n        raise ValueError('this objective has no shards')\n_o = _Toy(20, 30)\n_x0 = np.zeros(20)\n_x = np.asarray(minimize(_o, _x0.copy(), 30), dtype=float)\nprint(bool(np.log10(_o.gap(_x) / _o.gap(_x0)) < -6.0))","expected_output":"True"}],"approved_user_libraries":["numpy","scipy"],"lower_is_better":true,"data_info":"There is no dataset to read: the oracle is your only contact with each objective, and the grader builds every objective in a separate process.\n\nRun uses 36 objectives, 4 from each of these 9 families:\n1. Ill-conditioned quadratics, condition number from 100 to 1,000,000\n2. Chained Rosenbrock-type valleys\n3. Planted phase retrieval, nonconvex, with shards\n4. Planted low-rank matrix factorization, nonconvex\n5. Least absolute deviations with a planted solution, non-smooth, with shards\n6. L1-regularized least squares, non-smooth\n7. Quadratics behind an oracle with additive noise on the value and the gradient\n8. Least squares in expectation, where every call sees a fresh mini-batch\n9. L2-regularized logistic regression on public tabular data, with shards\n\nSubmit uses 68 objectives, 4 from each of 17 families: these 9 with new seeds and data, plus 8 more that are not listed here.\n\nDimensions run from about 10 to 800. Your code receives only the starting point, the budget and the oracle.","time_limits":{"test":420,"dev":240},"gpu":false,"description":"## Fewest Gradients to the Optimum\n\nEvery optimizer in the chapter claims to be fast. Here you get a hidden objective, a small budget of gradient evaluations and a starting point, and you return the point you want scored. The objectives include badly conditioned bowls, curved valleys, functions with kinks, and oracles that answer with noise, and your code is never told which one it is facing. The smallest remaining gap to the optimum wins.\n\n### What you write\n\n```python\ndef minimize(oracle, x0, budget):\n    ...\n    return x                        # np.ndarray, same shape as x0\n```\n\n`minimize` runs once per objective, each time in a fresh process, so nothing carries over from one objective to the next. The oracle is your only contact with the objective:\n\n- `oracle(x)` returns `(value, gradient)` and costs **1**. Where the objective has a kink, the gradient is a subgradient. Some oracles add fresh random error to both numbers on every call.\n- `oracle.shard(x, j)` returns `(value, gradient)` of shard `j` and costs **`1 / oracle.shards`**. A finite-sum objective is the exact average of `oracle.shards` fixed shards, each holding many examples. `oracle.shards == 0` means this objective has none.\n- `oracle.dim`, `oracle.budget`, `oracle.spent` and `oracle.remaining` tell you where you stand.\n\nA call you cannot afford is not answered: it raises `BudgetExhausted`, a name your functions can use. You may catch it and return, or check `oracle.remaining` first. The point you return does not have to be one you queried, and scoring it costs nothing.\n\n### How it is graded\n\nFor each objective, the grader evaluates the noiseless objective $f$ at your returned $x_T$ and at the starting point $x_0$, and takes\n\n$$\ns = \\operatorname{clip}\\left( \\log_{10} \\frac{f(x_T) - f^*}{f(x_0) - f^*},\\ -12,\\ 0 \\right)\n$$\n\nso $-3$ means the gap to the optimum shrank a thousandfold, and returning something worse than $x_0$ scores the same as returning $x_0$. $f^*$ is known exactly, or computed to high precision by the grader. Your score is the mean of $s$ over all objectives. **Lower is better**, and the lab is passed at **-2.00 or below**.\n\nEach objective hides behind a random shift and rescaling of $x$, a random rescaling of $f$ and an unknown constant added to the value, and most are also rotated. So no step size, and no value of $f^*$, carries over from one objective to another.\n\n- **Run**: 36 objectives from 9 families, listed under Data, with per-objective results and your printed output shown.\n- **Submit**: 68 hidden objectives from 17 families, 8 of which never appear in Run, drawn with different seeds and, for the real-data families, different data. Submit reports means only and hides your printed output.\n- Budgets vary by objective, from 5 to 60.\n\n### Budgets and rules\n\n- `minimize` gets 5 seconds of its own time per objective, not counting the time the oracle takes to answer.\n- Libraries: numpy, scipy, math, itertools, collections, heapq, bisect, random, statistics, time, warnings, typing, copy. Everything else, including file access and any dataset, is refused.\n- Write classes as usual: `self.x = ...` works inside a method defined in a class body. Assigning to or deleting an attribute of anything else (`x.y = ...`) is refused, and so are names that reach modules or object internals (`getattr`, `__dict__` and so on).\n- Module level and class bodies may hold only imports from that list, constants, and function and class definitions (`@staticmethod`, `@classmethod` and `@property` work on methods without annotations). Calls, loops and conditions go inside your functions. `minimize` runs in a fresh process for each objective, so nothing is lost by doing setup there.\n- Your source is capped at 30,000 characters, 500 numeric literals and 2,000 characters of string constants.\n- An exception out of `minimize` (an uncaught `BudgetExhausted` included), a non-finite or wrongly shaped result, an objective that is not finite at your result, or a broken cap or time limit fails the run with a score of 99.\n","tags":["optimization","gradient-descent","l-bfgs","non-smooth","stochastic","competitive","pml-book"],"id":"1fc59ecf-f458-4684-893a-a030f18e560e","img_type":"full","dataset_id":"synthetic","difficulty":"hard","evaluation_metric":"log10_gap_mean","min_eval_metric":-2.0,"category":"Optimization","dataset":"Hidden objectives built in the grader, some on public tabular data","title":"Fewest Gradients to the Optimum","time_limits_seconds":{"dev":240,"test":420}},{"created_at":"2026-10-27T15:08:27.728000+00:00","type":"general","test_cases":[{"test":"OK = {(a, b) for a in (-1, 0, 1) for b in (-1, 0, 1)}\na = Agent(30, 20, 5000)\nx = a.act((29, 7, 0, 0))\na.observe((29, 7, 0, 0), x, -1.0, (28, 7, 1, 0), False)\ny = a.policy((10, 7, 2, 1))\nprint(tuple(x) in OK and tuple(y) in OK)","expected_output":"True"},{"test":"OK = {(a, b) for a in (-1, 0, 1) for b in (-1, 0, 1)}\na = Agent(30, 20, 5000)\nx = a.act((29, 7, 0, 0))\na.observe((29, 7, 0, 0), x, -1.0, None, True)\nz = a.act((29, 8, 0, 0))\nprint(tuple(z) in OK)","expected_output":"True"},{"test":"\n# a tiny noise-free right turn with the lab's rules: '.' track, 'S' starting line, 'F' finish line\nG = [\"#.....F\",\n     \"#.....F\",\n     \"#..####\",\n     \"#..####\",\n     \"#..####\",\n     \"#..####\",\n     \"#SS####\"]\nH, W = len(G), len(G[0])\ndef cell(r, c):\n    return G[r][c] if 0 <= r < H and 0 <= c < W else \"#\"\ndef step(r, c, vy, vx, a):\n    ny, nx = min(max(vy + a[0], 0), 4), min(max(vx + a[1], 0), 4)\n    if ny == 0 and nx == 0 and cell(r, c) != \"S\":\n        ny, nx = vy, vx\n    n = 4 * max(ny, nx)\n    pts = [(int((r - ny * k / n) + 0.5 + 1000) - 1000, int((c + nx * k / n) + 0.5 + 1000) - 1000) for k in range(1, n + 1)]\n    if any(cell(*p) == \"F\" for p in pts):\n        return None, \"finish\"\n    if any(cell(*p) == \"#\" for p in pts):\n        return (H - 1, 1, 0, 0), \"crash\"\n    return (r - ny, c + nx, ny, nx), \"move\"\nagent = Agent(H, W, 2000)\ns = (H - 1, 1, 0, 0)\nfor t in range(2000):\n    a = tuple(agent.act(s))\n    s2, what = step(*s, a)\n    agent.observe(s, a, -1.0, s2, what == \"finish\")\n    s = (H - 1, 1 + t % 2, 0, 0) if s2 is None else s2\ndef lap(c0):\n    s = (H - 1, c0, 0, 0)\n    for k in range(40):\n        s, what = step(*s, tuple(agent.policy(s)))\n        if what == \"finish\":\n            return True\n        if what == \"crash\":\n            return False\n    return False\nprint(lap(1) and lap(2))\n","expected_output":"True"}],"approved_user_libraries":["numpy","math","collections","itertools","functools","random"],"lower_is_better":true,"data_info":"Synthetic racetracks generated inside the grader: right turns of 28-34 rows and 15-34 columns, with ragged and jogging walls. Run uses 2 fixed tracks; Submit draws 20 new tracks (10 narrow, 10 wide) on every submission. The agent sees only (row, col, vy, vx) states and -1 rewards.","time_limits":{"test":360,"dev":120},"example":{"input":"act((29, 7, 0, 0)) at the start of a lap; observe((29, 7, 0, 0), (1, 0), -1.0, (28, 7, 1, 0), False)","output":"(1, 1)  (velocity increments); after training the grader reports e.g. steps_vs_optimal 1.12"},"gpu":false,"description":"Drive a race car around a right turn you have never seen, as in the racetrack task of Sutton and Barto. On each hidden track your agent gets a fixed budget of driving steps to learn from; then the policy it ends up with is scored by the exact expected number of steps it needs to cross the finish line. The leaderboard ranks by **expected lap time divided by the best possible lap time on that track, averaged over tracks, lower is better** (1.0 means you drive the optimal policy).\n\n**Contract.** Define a class `Agent`:\n\n- `Agent(n_rows, n_cols, step_budget)` is created once per track.\n- `act(state) -> (dvy, dvx)` is called on every training step. `state` is `(row, col, vy, vx)`, all ints. Row 0 is the top row. `vy` is the upward speed (the row number drops by `vy` each step) and `vx` the rightward speed (the column number rises by `vx`). Return the velocity increments, each in -1, 0, +1.\n- `observe(state, action, reward, next_state, done)` is called after every training step. `reward` is always -1. When the car crosses the finish line, `done` is True and `next_state` is None; the next `act` call starts a new lap.\n- `policy(state) -> (dvy, dvx)` is called after training, once for every `(row, col, vy, vx)` with `0 <= row < n_rows`, `0 <= col < n_cols` and `0 <= vy, vx <= 4`, in an order that does not depend on the track. These answers are the policy that gets scored. Nothing is observed during this phase.\n\n**The track (the book's rules).**\n\n- The grid has `n_rows x n_cols` cells. Each is track, off the track, or finish line. The starting line is the track cells of the bottom row; the finish line is the track cells of the rightmost column. Every track is a right turn: up from the starting line, then right to the finish line. The shape is hidden.\n- Each step, the action is added to the velocity and each component is clipped to 0..4. If both components would be zero while the car is not on the starting line, the velocity stays as it was. With probability 0.1, independently on every step, both increments are zero whatever the action.\n- The car then moves from `(row, col)` to `(row - vy, col + vx)`. Its path is checked at `n = 4 * max(vy, vx)` points: point `k = 1..n` is `(row - vy * k / n, col + vx * k / n)` rounded to the nearest cell (halves round up). If any point is a finish-line cell, the lap ends. Otherwise, if any point is off the track or outside the grid, the car crashes: it goes to a uniformly random starting-line cell with velocity (0, 0) and the lap continues. Otherwise it moves.\n- Every lap starts on a uniformly random starting-line cell with velocity (0, 0). Every step costs -1.\n\n**Budgets.**\n\n- Run: 2 fixed tracks. Submit: 20 tracks (10 narrow turns, 10 wide ones) drawn fresh on every submission, so they cannot be precomputed.\n- 5,000 training steps per track. Laps restart automatically inside the budget.\n- Total time spent inside your `Agent` (constructor, `act`, `observe`, `policy`) is capped at 60 s on Run and 200 s on Submit.\n- `random` and `numpy.random` are seeded before every track.\n\n**Score.** For each track, the harness computes the exact expected number of steps from a uniformly random starting cell to the finish line under your policy, with the 0.1 noise, counting each lap as at most 60 steps. It divides that by the same quantity for the optimal policy, which it finds with value iteration on the true track. The score is the mean of that ratio over the tracks. The report also shows each track's expected steps, the optimum, and how many laps you finished and crashes you had while training. A score at or below **3.0** counts as solved; everything below that is leaderboard.\n\n**Gates.** The run fails with a score of 99 if any of these happen:\n- `act` or `policy` returns anything but a pair of ints, each -1, 0 or 1.\n- Any method raises or exits.\n- The time budget runs out.\n- Your code imports anything other than `numpy`, `math`, `collections`, `heapq`, `bisect`, `itertools`, `functools` and `random`, reads files, uses introspection (`globals`, `vars`, `getattr`/`setattr`, frames, tracebacks, `eval`/`exec`), or assigns to, aliases or reaches into the internals of an imported module.","tags":["reinforcement-learning","racetrack","model-based-rl","rtdp","monte-carlo","exploration","sutton-barto","open-ended","leaderboard"],"id":"1fd872eb-af18-4cbf-b931-796bdaa44f17","dataset_id":"synthetic","img_type":"full","difficulty":"hard","evaluation_metric":"steps_vs_optimal","min_eval_metric":3.0,"category":"Reinforcement Learning","dataset":"Synthetic racetracks (Sutton and Barto Exercise 5.12)","title":"Fastest Lap on an Unknown Racetrack","time_limits_seconds":{"dev":120,"test":360}},{"description":"Implement a function `build_model()` that returns a PyTorch `nn.Module` to classify MNIST digits. You may use ANY layers/ops, but if your model has more than **2048 trainable parameters**, your reported accuracy will be **0**. Keep it tiny and clever (e.g., global pooling, grouped/depthwise convs, shared weights, etc.).","constraints":["Implement ONLY `build_model()`; return an `nn.Module` instance.","All trainable parameters (requires_grad=True) count toward the 2048 limit.","If param_count > 2048, the grader sets accuracy to 0.","Use GPU if available."],"id":"2","test_cases":[{"test":"import torch, torch.nn as nn\nm = build_model()\nprint(isinstance(m, nn.Module))","expected_output":"True"},{"test":"import torch, torch.nn as nn\nm = build_model()\nparams = sum(p.numel() for p in m.parameters() if p.requires_grad)\nprint(params <= 2048)","expected_output":"True"}],"approved_user_libraries":["torch","numpy"],"difficulty":"medium","evaluation_metric":"Accuracy","data_info":"MNIST 28x28 grayscale digits (10 classes). Inputs scaled to [0,1] and shaped (N,1,28,28).","time_limits":{"test":"240 seconds","dev":"90 seconds"},"schema":"practical_question_v1","min_eval_metric":0.85,"example":{"input":{"X":"array([[[  0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,\n         0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,\n         0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.],\n        [  0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,\n         0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,\n         0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.],\n        [  0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,\n         0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,\n         0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.],\n        [  0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,\n         0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,\n         0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.],\n        [  0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,\n         0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,\n         0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.],\n        [  0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,\n         0.,   0.,   3.,  18.,  18.,  18., 126., 136., 175.,  26.,\n       166., 255., 247., 127.,   0.,   0.,   0.,   0.], ... ]])  # shape (1,28,28), values in [0,255] before scaling","y":"5"},"output":{"note":"If param_count > 2048 → accuracy is set to 0 in the final JSON.","param_count":"≤ 2048"}},"category":"Model Architecture","title":"MNIST: Design-Your-Own tiny Pytorch Model","model_specs":"You choose the architecture. Training: Adam lr=1e-3, batch size=128, epochs=10.","memory_limit":"2 GB","dataset":"MNIST","createdAt":"2026-05-13T21:01:41.403000+00:00","time_limits_seconds":{"dev":90,"test":240},"type":"epoch","lower_is_better":false,"gpu":false},{"description":"Implement a `train` function that learns to classify handwritten digits using ONLY Python and the math standard library.\n\nThe harness loads the sklearn digits dataset (8x8 pixel images of digits 0-9, giving 64 features per sample), normalizes pixel values to [0, 1], and passes training and validation data as nested Python lists.\n\nYou must return a `predict` function that classifies new images. You may use ANY approach: nearest-neighbor, centroid classifier, logistic regression, neural network with hand-rolled backprop, decision trees, or anything creative -- as long as you only use Python and the math module.","type":"general","constraints":["Use ONLY Python and the math standard library -- no numpy, sklearn, torch, or other libraries","Your function signature must be: train(X_train, y_train, X_val, y_val, n_classes) -> predict","X_train and X_val are list[list[float]], each inner list has 64 floats in [0, 1]","y_train and y_val are list[int], each value in [0, n_classes)","predict must be callable: list[list[float]] -> list[int]","predict must return a list of integer class predictions, one per input sample","Must complete training and prediction within the time limit"],"id":"20","test_cases":[{"description":"Returns callable predict function","test":"X = [[0.1]*64 for _ in range(20)]\ny = [i % 10 for i in range(20)]\npredict = train(X, y, X[:5], y[:5], 10)\nprint(callable(predict))","expected_output":"True"},{"description":"predict returns list of ints","test":"X = [[0.1]*64 for _ in range(20)]\ny = [i % 10 for i in range(20)]\npredict = train(X, y, X[:5], y[:5], 10)\npreds = predict(X[:5])\nprint(isinstance(preds, list) and all(isinstance(p, int) for p in preds))","expected_output":"True"},{"description":"predict returns correct number of predictions","test":"X = [[0.1]*64 for _ in range(20)]\ny = [i % 10 for i in range(20)]\npredict = train(X, y, X[:5], y[:5], 10)\npreds = predict(X[:8])\nprint(len(preds) == 8)","expected_output":"True"},{"description":"Predictions are valid class indices","test":"X = [[0.1]*64 for _ in range(20)]\ny = [i % 10 for i in range(20)]\npredict = train(X, y, X[:5], y[:5], 10)\npreds = predict(X)\nprint(all(0 <= p < 10 for p in preds))","expected_output":"True"}],"approved_user_libraries":["math","random"],"difficulty":"hard","evaluation_metric":"Accuracy","data_info":"sklearn digits dataset: 1,797 samples of 8x8 pixel grayscale images of handwritten digits (0-9). Each sample has 64 features (pixel intensities normalized to [0, 1]). 10 classes. Training: 1,000 samples, validation: 400 samples, test: 500 samples. Data is passed as nested Python lists.","time_limits":{"test":"60 seconds","dev":"60 seconds"},"schema":"practical_question_v1","min_eval_metric":0.8,"example":{"input":{"X_train":"list[list[float]] -- 1000 training images, each 64 floats in [0, 1]","n_classes":"int -- number of classes (10)","y_train":"list[int] -- 1000 training labels in [0, 9]","X_val":"list[list[float]] -- 400 validation images","y_val":"list[int] -- 400 validation labels"},"output":{"predict":"callable: list[list[float]] -> list[int], returns predicted class for each input image"}},"category":"Classification","title":"Build a Digit Classifier from Scratch","model_specs":"Harness loads sklearn digits (8x8 images, 64 features, 10 classes), normalizes to [0,1], converts to nested Python lists. User implements train() returning predict(). Evaluated on accuracy. User may only use Python + math module.","dataset":"Digits (sklearn)","memory_limit":"2 GB","createdAt":"2026-05-13T21:01:41.516000+00:00","time_limits_seconds":{"dev":60,"test":60},"lower_is_better":false,"gpu":false},{"created_at":"2026-10-26T20:39:42.155000+00:00","type":"general","test_cases":[{"test":"class _Req:\n    def __init__(self, i, t, s, n, bh):\n        self.id, self.arrival, self.session, self.prompt_tokens, self.block_hashes = i, t, s, n, bh\nidle = [{'queued_requests': 0, 'queued_prompt_tokens': 0} for _ in range(8)]\nr = Router(8, 64, 3050, 6100)\nout = [r.route(_Req(k, 1.0 * k, 100 + k, 1000, tuple(range(10 * k, 10 * k + 15))), idle) for k in range(20)]\nprint(all(isinstance(x, int) and 0 <= x < 8 for x in out))","expected_output":"True"},{"test":"class _Req:\n    def __init__(self, i, t, s, n, bh):\n        self.id, self.arrival, self.session, self.prompt_tokens, self.block_hashes = i, t, s, n, bh\nidle = [{'queued_requests': 0, 'queued_prompt_tokens': 0} for _ in range(8)]\ndef play():\n    r = Router(8, 64, 3050, 6100)\n    return [r.route(_Req(k, 0.5 * k, k % 5, 3000 + k, tuple(range(k % 5, k % 5 + 40))), idle) for k in range(30)]\nprint(play() == play())","expected_output":"True"},{"test":"class _Req:\n    def __init__(self, i, t, s, n, bh):\n        self.id, self.arrival, self.session, self.prompt_tokens, self.block_hashes = i, t, s, n, bh\nidle = [{'queued_requests': 0, 'queued_prompt_tokens': 0} for _ in range(8)]\nr = Router(8, 64, 3050, 6100)\nbh = tuple(range(1000, 1100))\na = r.route(_Req(0, 0.0, 7, 6500, bh), idle)\nb = r.route(_Req(1, 100.0, 7, 6500, bh), idle)\nc = r.route(_Req(2, 200.0, 7, 6500, bh), idle)\nprint(a == b == c)","expected_output":"True"}],"approved_user_libraries":["numpy","math","collections","itertools","functools","random"],"lower_is_better":true,"data_info":"Synthetic, deterministic traces generated inside the grader from fixed seeds: Run = 2 traces x 120 s on 8 replicas (~1,500-1,700 requests each); Submit = 3 held-out traces x 180 s on 8 or 10 replicas (~2,600-2,900 requests each). Each request exposes id, arrival, session, prompt_tokens and block_hashes (64-token blocks).","time_limits":{"test":180,"dev":120},"example":{"input":"route(request, replicas) with request.block_hashes = (h0, h1, ..., h40), request.session = 81234, replicas = [{'queued_requests': 2, 'queued_prompt_tokens': 9100}, ...]","output":"3  (the replica index); the grader replays the whole trace and reports the mean P90 TTFT, e.g. 412.6 ms"},"gpu":false,"description":"Route every request of a live LLM serving trace to one of several identical replicas so that users see their first token as soon as possible. Each replica keeps its own prefix cache, so where a request lands decides both how much of its prompt has to be recomputed and how long it waits behind other requests. The leaderboard ranks by **mean P90 time to first token in milliseconds, lower is better**.\n\n**Contract.** Define a class `Router`:\n\n- `Router(n_replicas, block_size, g1_blocks, g2_blocks)` is created once per trace (`block_size` is 64 tokens).\n- `route(request, replicas) -> int` returns the index of the replica that serves `request`. It is called once per request in arrival order.\n- Optional: `on_first_token(request_id, replica, cached_tokens, ttft_seconds)` is called for every request whose first token has appeared by the time of the next `route` call, in the order the tokens appeared.\n\n`request` has `id`, `arrival` (seconds since the trace started; this is \"now\"), `session` (an integer shared by every request of one conversation, RAG thread or agent run; one-off prompts get their own), `prompt_tokens`, and `block_hashes`: a tuple with one integer per full 64-token block of the prompt, where hash `i` identifies the entire prompt up to the end of block `i`. Two requests share hash `i` exactly when their first `64 * (i + 1)` tokens are identical. `replicas` is a list with one dict per replica: `queued_requests` (requests routed there whose first token has not appeared yet) and `queued_prompt_tokens` (the sum of their prompt lengths).\n\n**The replicas (identical, fixed).**\n\n- A replica prefills one request at a time, in the order you route them. A request starts at its arrival or when the replica's previous prefill ends, whichever is later. Its time to first token is its start plus its service time minus its arrival.\n- Service time is `0.015 s + uncached_tokens / 12000 + g2_tokens * 6.5e-6` seconds.\n- The cache lookup walks `block_hashes` from the first block. A block found in G1 (GPU memory) is free. A block found in G2 (host memory) is reloaded at the per-token cost above. The walk stops at the first block found in neither tier. Every token after that, including a partial last block, is uncached.\n- Once a request is served, all its full blocks sit in G1 as the most recently used (G2 hits are promoted). G1 holds 3050 blocks (64 GB of KV cache at 320 KB per token). When it is full, its least recently used block moves to G2. G2 holds 6100 blocks (128 GB of host memory) and drops its least recently used block when full.\n- A replica's cache, when a request is looked up, is what every request routed there before it left behind.\n\n**Traces.** The traffic mixes multi-turn chat, RAG over shared documents, tool-using agents, one-off prompts and occasional 12k–32k-token prompts, with arrival rates that change over time. Your router never sees future requests.\n\n- Run: two 120-second traces on 8 replicas.\n- Submit: three held-out 180-second traces on 8 or 10 replicas, with different seeds and traffic mixes.\n\n**Score.** For each trace, the P90 of time to first token over all its requests. The score is the mean over the traces, in ms. The report also shows P50 and P99, the share of prompt tokens served from cache, load imbalance, and `no_wait_shared_cache_p90_ms`: the P90 if every block computed anywhere before were free and nothing ever waited. That figure is not reachable; it shows how much room is left. A score at or below **800 ms** counts as solved; everything below that is leaderboard.\n\n**Budget and rules.** Total time spent inside your `Router` (constructor, `route`, `on_first_token`) is capped at 40 s on Run and 90 s on Submit. `random` and `numpy.random` are seeded before every trace. Your code may import only `numpy`, `math`, `collections`, `itertools`, `functools`, `random`, `heapq` and `bisect`, and may use an imported module only as `module.name`.\n\n**Gates.** The score is set to 1,000,000 ms and the run fails if any of these happen:\n- `route` returns anything but an int in `0..n_replicas-1`.\n- Any method raises.\n- The time budget runs out.\n- Your code reads files, uses introspection (`globals`, `vars`, `getattr`/`setattr`, frames, tracebacks, `eval`/`exec`), or assigns to, aliases or reaches into the internals of an imported module.","tags":["inference","prefix-caching","kv-cache","routing","load-balancing","serving","open-ended","leaderboard"],"id":"20e9526d-3f50-42b9-83ad-119c33160b5b","dataset_id":"synthetic","img_type":"full","difficulty":"hard","evaluation_metric":"p90_ttft_ms","min_eval_metric":800.0,"category":"Inference","title":"Best Cache-Aware Router","dataset":"Synthetic LLM serving traces (chat, RAG, agents)","time_limits_seconds":{"dev":120,"test":180}},{"description":"You are given a regression dataset that has been deliberately over-engineered with polynomial features and noise columns. A naive approach (e.g., ordinary least squares or unregularized gradient descent) will badly overfit: it achieves near-perfect training R² but catastrophically negative test R².\n\nYour task: implement a `train` function that returns a `predict` callable which actually generalizes to unseen data. You must use ONLY NumPy.\n\nThe harness generates degree-3 polynomial features plus 100 pure noise columns from the original 8-feature California Housing dataset, giving ~264 features but only ~250 training samples. This makes the problem deliberately overparameterized. Unregularized OLS will get Train R² ≈ 1.0 but Val R² ≈ -5.0 (worse than guessing the mean!).","type":"general","constraints":["Use ONLY numpy - no sklearn, PyTorch, TensorFlow, or other ML libraries","Your function signature must be: train(X_train, y_train, X_val, y_val) -> predict","predict must be callable: predict(X) -> y_pred (numpy array)","X_train and X_val are already standardized -- do NOT re-standardize","y_train and y_val are raw target values (not standardized)","Must be deterministic under a fixed numpy random seed","Any strategy is valid: L1, L2, ElasticNet, feature selection, early stopping, etc."],"id":"21","test_cases":[{"description":"Returns a callable predict function","test":"import numpy as np\nnp.random.seed(42)\nX_tr = np.random.randn(100, 50)\ny_tr = np.random.randn(100)\nX_v = np.random.randn(20, 50)\ny_v = np.random.randn(20)\npredict = train(X_tr, y_tr, X_v, y_v)\nprint(callable(predict))","expected_output":"True"},{"description":"predict returns correct shape","test":"import numpy as np\nnp.random.seed(42)\nX_tr = np.random.randn(100, 50)\ny_tr = np.random.randn(100)\nX_v = np.random.randn(20, 50)\ny_v = np.random.randn(20)\npredict = train(X_tr, y_tr, X_v, y_v)\npreds = predict(X_v)\nprint(preds.shape == (20,))","expected_output":"True"},{"description":"predict output contains no NaN or Inf","test":"import numpy as np\nnp.random.seed(42)\nX_tr = np.random.randn(100, 50)\ny_tr = np.random.randn(100)\nX_v = np.random.randn(20, 50)\ny_v = np.random.randn(20)\npredict = train(X_tr, y_tr, X_v, y_v)\npreds = predict(X_v)\nprint(np.all(np.isfinite(preds)))","expected_output":"True"},{"description":"Deterministic output","test":"import numpy as np\nX_tr = np.random.randn(80, 40)\ny_tr = np.random.randn(80)\nX_v = np.random.randn(20, 40)\ny_v = np.random.randn(20)\nnp.random.seed(99)\np1 = train(X_tr.copy(), y_tr.copy(), X_v.copy(), y_v.copy())\npreds1 = p1(X_v.copy())\nnp.random.seed(99)\np2 = train(X_tr.copy(), y_tr.copy(), X_v.copy(), y_v.copy())\npreds2 = p2(X_v.copy())\nprint(np.allclose(preds1, preds2))","expected_output":"True"}],"approved_user_libraries":["numpy"],"difficulty":"medium","evaluation_metric":"R2","data_info":"California Housing dataset expanded with degree-3 polynomial features (~164 from 8 original) plus 100 pure noise columns = ~264 total features. Only 250 training samples. The data is deliberately overparameterized (more features than samples) so that unregularized regression perfectly memorizes training data (R² ≈ 1.0) but fails catastrophically on validation (R² ≈ -5.0). Features are standardized to zero mean, unit variance. Target (median house value in $100Ks) is NOT standardized.","time_limits":{"test":"60 seconds","dev":"30 seconds"},"schema":"practical_question_v1","min_eval_metric":0.45,"example":{"input":{"X_train":"numpy array of shape (250, ~264) -- standardized polynomial + noise features (more features than samples!)","y_val":"numpy array of shape (300,) -- validation target values","y_train":"numpy array of shape (250,) -- target values (median house value in $100Ks)","X_val":"numpy array of shape (300, ~264) -- standardized validation features"},"output":{"predict":"callable: predict(X) -> numpy array of shape (n_samples,)"}},"category":"Regularized Regression","title":"Fix Overfitting with Regularization (NumPy)","model_specs":"Linear model. Harness creates ~264 features (degree-3 polynomial + 100 noise) from 8 original California Housing features with only 250 training samples. More features than samples = guaranteed overfitting without regularization. User must implement regularization to generalize. Evaluated on R² on held-out data.","memory_limit":"1 GB","dataset":"California Housing (polynomial expanded + noise)","createdAt":"2026-05-13T21:01:41.684000+00:00","time_limits_seconds":{"dev":30,"test":60},"lower_is_better":false,"gpu":false},{"description":"You are given a regression dataset that has been deliberately over-engineered with polynomial features and noise columns. A naive approach (e.g., `LinearRegression()`) will badly overfit: near-perfect training R² but catastrophically negative test R².\n\nYour task: implement a `train` function that returns a `predict` callable which actually generalizes to unseen data. You can use sklearn and NumPy.\n\nThe harness generates degree-3 polynomial features plus 100 pure noise columns from the original 8-feature California Housing dataset, giving ~264 features but only ~250 training samples. `LinearRegression()` will get Train R² ≈ 1.0 but Val R² ≈ -5.0. You need sklearn's regularized models to fix this.","type":"general","constraints":["You can use numpy and sklearn","Your function signature must be: train(X_train, y_train, X_val, y_val) -> predict","predict must be callable: predict(X) -> y_pred (numpy array)","X_train and X_val are already standardized -- do NOT re-standardize","y_train and y_val are raw target values (not standardized)","Must be deterministic under a fixed numpy random seed","Any strategy is valid: Ridge, Lasso, ElasticNet, feature selection, Pipeline, etc."],"id":"22","test_cases":[{"description":"Returns a callable predict function","test":"import numpy as np\nnp.random.seed(42)\nX_tr = np.random.randn(100, 50)\ny_tr = np.random.randn(100)\nX_v = np.random.randn(20, 50)\ny_v = np.random.randn(20)\npredict = train(X_tr, y_tr, X_v, y_v)\nprint(callable(predict))","expected_output":"True"},{"description":"predict returns correct shape","test":"import numpy as np\nnp.random.seed(42)\nX_tr = np.random.randn(100, 50)\ny_tr = np.random.randn(100)\nX_v = np.random.randn(20, 50)\ny_v = np.random.randn(20)\npredict = train(X_tr, y_tr, X_v, y_v)\npreds = predict(X_v)\nprint(preds.shape == (20,))","expected_output":"True"},{"description":"predict output contains no NaN or Inf","test":"import numpy as np\nnp.random.seed(42)\nX_tr = np.random.randn(100, 50)\ny_tr = np.random.randn(100)\nX_v = np.random.randn(20, 50)\ny_v = np.random.randn(20)\npredict = train(X_tr, y_tr, X_v, y_v)\npreds = predict(X_v)\nprint(np.all(np.isfinite(preds)))","expected_output":"True"},{"description":"Deterministic output","test":"import numpy as np\nX_tr = np.random.randn(80, 40)\ny_tr = np.random.randn(80)\nX_v = np.random.randn(20, 40)\ny_v = np.random.randn(20)\nnp.random.seed(99)\np1 = train(X_tr.copy(), y_tr.copy(), X_v.copy(), y_v.copy())\npreds1 = p1(X_v.copy())\nnp.random.seed(99)\np2 = train(X_tr.copy(), y_tr.copy(), X_v.copy(), y_v.copy())\npreds2 = p2(X_v.copy())\nprint(np.allclose(preds1, preds2))","expected_output":"True"}],"approved_user_libraries":["numpy","sklearn"],"difficulty":"easy","evaluation_metric":"R2","data_info":"California Housing dataset expanded with degree-3 polynomial features (~164 from 8 original) plus 100 pure noise columns = ~264 total features. Only 250 training samples. The data is deliberately overparameterized (more features than samples) so that unregularized LinearRegression() perfectly memorizes training data (R² ≈ 1.0) but fails catastrophically on validation (R² ≈ -5.0). Features are standardized to zero mean, unit variance. Target (median house value in $100Ks) is NOT standardized.","time_limits":{"test":"60 seconds","dev":"30 seconds"},"schema":"practical_question_v1","min_eval_metric":0.5,"example":{"input":{"X_train":"numpy array of shape (250, ~264) -- standardized polynomial + noise features (more features than samples!)","y_val":"numpy array of shape (300,) -- validation target values","y_train":"numpy array of shape (250,) -- target values (median house value in $100Ks)","X_val":"numpy array of shape (300, ~264) -- standardized validation features"},"output":{"predict":"callable: predict(X) -> numpy array of shape (n_samples,)"}},"category":"Regularized Regression","title":"Fix Overfitting with Regularization (Sklearn)","model_specs":"Sklearn linear model. Harness creates ~264 features (degree-3 polynomial + 100 noise) from 8 original California Housing features with only 250 training samples. More features than samples = guaranteed overfitting without regularization. User must use regularized sklearn models to generalize. Evaluated on R² on held-out data.","memory_limit":"1 GB","dataset":"California Housing (polynomial expanded + noise)","createdAt":"2026-05-13T21:01:41.782000+00:00","time_limits_seconds":{"dev":30,"test":60},"lower_is_better":false,"gpu":false},{"description":"You are given a binary classification dataset where the target is either 0 or 1. Implement a `train` function that returns a `predict` callable which classifies new samples accurately.\n\nThe harness loads the Breast Cancer dataset from sklearn (30 numerical features describing cell nuclei measurements), standardizes the features, splits into train/val/test, and calls your function. Your `predict` must return an array of 0s and 1s.\n\nYou can use any sklearn model or approach you like.","type":"general","constraints":["You can use numpy and sklearn","Your function signature must be: train(X_train, y_train, X_val, y_val) -> predict","predict must be callable: predict(X) -> y_pred (numpy array of 0s and 1s)","X_train and X_val are already standardized -- do NOT re-standardize","y_train and y_val are integer arrays with values 0 or 1","Must be deterministic under a fixed numpy random seed","Any sklearn model or strategy is valid"],"id":"23","test_cases":[{"description":"Returns a callable predict function","test":"import numpy as np\nnp.random.seed(42)\nX_tr = np.random.randn(100, 10)\ny_tr = np.random.randint(0, 2, 100)\nX_v = np.random.randn(20, 10)\ny_v = np.random.randint(0, 2, 20)\npredict = train(X_tr, y_tr, X_v, y_v)\nprint(callable(predict))","expected_output":"True"},{"description":"predict returns correct shape","test":"import numpy as np\nnp.random.seed(42)\nX_tr = np.random.randn(100, 10)\ny_tr = np.random.randint(0, 2, 100)\nX_v = np.random.randn(20, 10)\ny_v = np.random.randint(0, 2, 20)\npredict = train(X_tr, y_tr, X_v, y_v)\npreds = predict(X_v)\nprint(preds.shape == (20,))","expected_output":"True"},{"description":"predict returns only 0s and 1s","test":"import numpy as np\nnp.random.seed(42)\nX_tr = np.random.randn(100, 10)\ny_tr = np.random.randint(0, 2, 100)\nX_v = np.random.randn(20, 10)\ny_v = np.random.randint(0, 2, 20)\npredict = train(X_tr, y_tr, X_v, y_v)\npreds = predict(X_v)\nprint(set(preds.tolist()).issubset({0, 1}))","expected_output":"True"},{"description":"Deterministic output","test":"import numpy as np\nX_tr = np.random.randn(80, 10)\ny_tr = np.random.randint(0, 2, 80)\nX_v = np.random.randn(20, 10)\ny_v = np.random.randint(0, 2, 20)\nnp.random.seed(99)\np1 = train(X_tr.copy(), y_tr.copy(), X_v.copy(), y_v.copy())\npreds1 = p1(X_v.copy())\nnp.random.seed(99)\np2 = train(X_tr.copy(), y_tr.copy(), X_v.copy(), y_v.copy())\npreds2 = p2(X_v.copy())\nprint(np.array_equal(preds1, preds2))","expected_output":"True"}],"approved_user_libraries":["numpy","sklearn"],"difficulty":"easy","evaluation_metric":"Accuracy","data_info":"Breast Cancer Wisconsin dataset from sklearn: 569 samples with 30 numerical features describing cell nuclei measurements (mean radius, mean texture, mean perimeter, etc.). Binary target: 0 = malignant, 1 = benign. Features are standardized to zero mean, unit variance before being passed to your function.","time_limits":{"test":"60 seconds","dev":"30 seconds"},"schema":"practical_question_v1","min_eval_metric":0.92,"example":{"input":{"X_train":"numpy array of shape (350, 30) -- standardized cell nuclei measurements","y_val":"numpy array of shape (100,) -- validation labels","y_train":"numpy array of shape (350,) -- binary labels (0 = malignant, 1 = benign)","X_val":"numpy array of shape (100, 30) -- standardized validation features"},"output":{"predict":"callable: predict(X) -> numpy array of 0s and 1s, shape (n_samples,)"}},"category":"Logistic Regression","title":"Train a Binary Classifier","model_specs":"User's choice of sklearn model. Harness loads Breast Cancer dataset (30 features, binary target), standardizes features, splits into train/val/test. Evaluated on accuracy on held-out data.","memory_limit":"1 GB","dataset":"Breast Cancer Wisconsin","createdAt":"2026-05-15T12:11:59.896000+00:00","time_limits_seconds":{"dev":30,"test":60},"lower_is_better":false,"gpu":false},{"description":"Implement a **normalization function** for a neural network using only NumPy. Your `normalize(x)` function takes an array of activations and returns normalized outputs.\n\nThe training harness handles everything else (forward pass, backpropagation, weight updates). You just define **how activations are normalized before being passed to the next layer**.\n\nYou may implement **ANY normalization strategy** you like: LayerNorm, RMSNorm, BatchNorm-style, or something creative. Your normalization will be used in a simple neural network trained on MNIST.\n\nNormalization is a critical component in modern LLMs — models like DeepSeek V3, OLMo 2, Gemma 3, and Qwen3 all rely on variants of normalization (especially RMSNorm) to stabilize training and improve performance.","constraints":["Use ONLY numpy - no PyTorch, TensorFlow, or other libraries","normalize(x) must return an array of the SAME shape as input","Must actually change the distribution of values (not just returning x unchanged)","Should work element-wise across the last dimension (feature/hidden dimension)","Must handle batched 2D inputs of shape (batch_size, features)","Output must not contain NaN or Inf values","Any normalization strategy is valid!"],"id":"24","test_cases":[{"description":"Output shape matches input shape","test":"import numpy as np\nx = np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])\ny = normalize(x)\nprint(y.shape == x.shape)","expected_output":"True"},{"description":"Not the identity function","test":"import numpy as np\nx = np.array([[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0]])\ny = normalize(x)\nprint(not np.allclose(y, x))","expected_output":"True"},{"description":"Works on different sized inputs","test":"import numpy as np\nx = np.random.randn(8, 128)\ny = normalize(x)\nprint(y.shape == (8, 128))","expected_output":"True"},{"description":"Deterministic output","test":"import numpy as np\nnp.random.seed(42)\nx = np.random.randn(4, 64)\ny1 = normalize(x)\ny2 = normalize(x)\nprint(np.allclose(y1, y2))","expected_output":"True"},{"description":"No NaN or Inf in output","test":"import numpy as np\nx = np.random.randn(16, 32)\ny = normalize(x)\nprint(np.all(np.isfinite(y)))","expected_output":"True"},{"description":"Handles near-zero variance input","test":"import numpy as np\nx = np.ones((4, 16)) * 3.0\nx[0, 0] = 3.001\ny = normalize(x)\nprint(np.all(np.isfinite(y)))","expected_output":"True"}],"approved_user_libraries":["numpy"],"difficulty":"easy","evaluation_metric":"Accuracy","data_info":"MNIST 28x28 grayscale digits flattened to 784-dim vectors, scaled to [0,1]. Trained with a 3-layer neural network (784→128→128→10) using Pre-Norm placement. Your normalization is applied 3 times: before each linear layer.","time_limits":{"test":"180 seconds","dev":"90 seconds"},"schema":"practical_question_v1","min_eval_metric":0.8,"example":{"input":{"x":"numpy array of shape (batch_size, features), e.g., [[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0]]"},"output":{"normalized":"numpy array of same shape with normalization applied across the feature dimension, e.g., [[0.365, 0.730, 1.095, 1.461], [0.379, 0.455, 0.530, 0.606]]"},"reasoning":"For RMSNorm: RMS of row [1,2,3,4] = sqrt((1+4+9+16)/4) = sqrt(7.5) ≈ 2.739. Each element is divided by the RMS: [1/2.739, 2/2.739, 3/2.739, 4/2.739] ≈ [0.365, 0.730, 1.095, 1.461]"},"category":"Normalization","title":"Design Your Own Normalization Layer","model_specs":"3-layer neural network (784→128→128→10) with Pre-Norm placement. Your normalization is applied before each linear layer (used 3 times per forward pass), mimicking how RMSNorm is placed in modern LLMs like Llama 3 and DeepSeek V3.","memory_limit":"1 GB","dataset":"MNIST","createdAt":"2026-05-13T21:01:42.069000+00:00","function_signature":"normalize(x) -> normalized_x","time_limits_seconds":{"dev":90,"test":180},"type":"epoch","lower_is_better":false,"gpu":false},{"description":"Implement a **routing function** for a Mixture of Experts (MoE) layer using only NumPy. Your `route(x, W_gate)` function takes hidden activations and a gate weight matrix, and returns per-expert weights that determine how much each expert contributes to the output.\n\nThe training harness handles everything else: the input layer, expert computations, combining expert outputs using your weights, the output layer, and backpropagation. You just decide **which experts to use and how much**.\n\nThis lab uses **32 experts** with small capacity (16 neurons each) — close to real MoE architectures where many lightweight experts specialize on different inputs. With 32 experts, naive strategies that weight all experts equally perform poorly because gradient signal gets diluted. Smart routing focuses computation on the most relevant experts.\n\nMoE is the most discussed architectural pattern in modern LLMs — DeepSeek V3 uses 256 experts with top-8 routing, Llama 4 uses 128 experts with top-1, and Qwen3 uses 128 experts with top-8.","constraints":["Use ONLY numpy - no PyTorch, TensorFlow, or other libraries","route(x, W_gate) must return an array of shape (batch_size, num_experts)","All weights must be non-negative","Weights for each sample must sum to approximately 1.0","Must not return uniform weights for all inputs (must actually use W_gate)","Must handle batched 2D inputs","Output must not contain NaN or Inf values"],"id":"25","test_cases":[{"description":"Output shape is (batch_size, num_experts)","test":"import numpy as np\nnp.random.seed(42)\nx = np.random.randn(4, 128).astype('float32')\nW_gate = np.random.randn(128, 32).astype('float32') * 0.1\nw = route(x, W_gate)\nprint(w.shape == (4, 32))","expected_output":"True"},{"description":"All weights are non-negative","test":"import numpy as np\nnp.random.seed(42)\nx = np.random.randn(8, 128).astype('float32')\nW_gate = np.random.randn(128, 32).astype('float32') * 0.1\nw = route(x, W_gate)\nprint(np.all(w >= -1e-7))","expected_output":"True"},{"description":"Weights sum to ~1 per sample","test":"import numpy as np\nnp.random.seed(42)\nx = np.random.randn(8, 128).astype('float32')\nW_gate = np.random.randn(128, 32).astype('float32') * 0.1\nw = route(x, W_gate)\nprint(np.allclose(np.sum(w, axis=1), 1.0, atol=1e-4))","expected_output":"True"},{"description":"Not uniform weights (uses W_gate)","test":"import numpy as np\nnp.random.seed(42)\nx = np.random.randn(16, 128).astype('float32')\nW_gate = np.random.randn(128, 32).astype('float32') * 0.1\nw = route(x, W_gate)\nuniform = np.ones_like(w) / 32\nprint(not np.allclose(w, uniform, atol=0.01))","expected_output":"True"},{"description":"Different inputs produce different routing","test":"import numpy as np\nx1 = np.ones((1, 128), dtype='float32') * 0.5\nx2 = -np.ones((1, 128), dtype='float32') * 0.5\nW_gate = np.random.randn(128, 32).astype('float32') * 0.1\nw1 = route(x1, W_gate)\nw2 = route(x2, W_gate)\nprint(not np.allclose(w1, w2))","expected_output":"True"},{"description":"No NaN or Inf in output","test":"import numpy as np\nx = np.random.randn(32, 128).astype('float32') * 10\nW_gate = np.random.randn(128, 32).astype('float32') * 0.5\nw = route(x, W_gate)\nprint(np.all(np.isfinite(w)))","expected_output":"True"}],"approved_user_libraries":["numpy"],"difficulty":"medium","evaluation_metric":"Accuracy","time_limits":{"test":"180 seconds","dev":"90 seconds"},"data_info":"MNIST 28x28 grayscale digits flattened to 784-dim vectors, scaled to [0,1]. Network: Linear(784→128) → ReLU → [MoE layer: 32 experts, each 128→16] → ReLU → Linear(16→10) → Softmax. Your route() function controls how the 32 expert outputs are weighted and combined.","schema":"practical_question_v1","min_eval_metric":0.7,"example":{"input":{"W_gate":"numpy array of shape (hidden_dim, num_experts), e.g., shape (128, 32) — learnable gate weight matrix","x":"numpy array of shape (batch_size, hidden_dim), e.g., shape (64, 128) — hidden activations from the previous layer"},"output":{"weights":"numpy array of shape (batch_size, num_experts), e.g., shape (64, 32) — per-expert weights, non-negative, summing to 1 per row. For top-2 routing, 30 of 32 entries per row would be 0."},"reasoning":"For top-2 sparse gating: compute logits = x @ W_gate (shape 64×32), apply softmax to get scores, find the 2 highest-scoring experts per sample, zero out the remaining 30, and renormalize so weights sum to 1. This activates only 2 of 32 experts per input, making the layer sparse and efficient."},"category":"Mixture of Experts","dataset":"MNIST","title":"Design Your Own MoE Router","model_specs":"3-layer network: Linear(784→128) → ReLU → [MoE: 32 experts, each 128→16] → ReLU → Linear(16→10) → Softmax. Each expert has only 2,064 parameters (128×16 + 16), so routing quality directly determines which small experts get the gradient signal they need to specialize.","memory_limit":"1 GB","createdAt":"2026-05-13T21:01:42.220000+00:00","function_signature":"route(x, W_gate) -> weights","time_limits_seconds":{"dev":90,"test":180},"type":"epoch","lower_is_better":false,"gpu":false},{"type":"general","constraints":["Implement a class named `DecisionTree` with `__init__(self, max_depth=10, min_samples_split=2, max_features='sqrt', random_state=None)`, `fit(self, X, y) -> self`, and `predict(self, X) -> np.ndarray` of integer labels.","`fit` and `predict` must use only numpy. Do NOT use sklearn's tree implementation.","Predictions must be integer class labels (not probabilities).","Two trees constructed with the same `random_state` and trained on the same data must produce identical predictions (determinism).","Trees with different `random_state` values should produce different predictions, given enough features and samples.","Total runtime for fitting 30 trees + a single-tree baseline must fit within the time limit."],"test_cases":[{"description":"DecisionTree can be instantiated and fit","test":"import numpy as np\nnp.random.seed(0)\nX = np.random.randn(50, 10); y = np.random.randint(0, 3, 50)\ntree = DecisionTree(max_depth=5, random_state=0)\nresult = tree.fit(X, y)\nprint(result is not None)","expected_output":"True"},{"description":"predict returns a numpy array of correct shape","test":"import numpy as np\nnp.random.seed(0)\nX = np.random.randn(50, 10); y = np.random.randint(0, 3, 50)\ntree = DecisionTree(max_depth=5, random_state=0)\ntree.fit(X, y)\np = tree.predict(np.random.randn(7, 10))\nprint(isinstance(p, np.ndarray) and p.shape == (7,))","expected_output":"True"},{"description":"predict returns valid integer class labels","test":"import numpy as np\nnp.random.seed(0)\nX = np.random.randn(50, 10); y = np.random.randint(0, 3, 50)\ntree = DecisionTree(max_depth=5, random_state=0)\ntree.fit(X, y)\np = tree.predict(np.random.randn(20, 10))\nprint(set(np.unique(p).tolist()).issubset({0, 1, 2}))","expected_output":"True"},{"description":"Trees with different random_state produce different predictions on at least some inputs","test":"import numpy as np\nnp.random.seed(0)\nX = np.random.randn(200, 20); y = np.random.randint(0, 4, 200)\nX_te = np.random.randn(50, 20)\nt1 = DecisionTree(max_depth=8, random_state=1).fit(X, y)\nt2 = DecisionTree(max_depth=8, random_state=999).fit(X, y)\nprint(not np.array_equal(t1.predict(X_te), t2.predict(X_te)))","expected_output":"True"},{"description":"Same random_state and data produce identical predictions (determinism)","test":"import numpy as np\nnp.random.seed(0)\nX = np.random.randn(100, 10); y = np.random.randint(0, 3, 100)\nX_te = np.random.randn(20, 10)\nt1 = DecisionTree(max_depth=6, random_state=42).fit(X, y)\nt2 = DecisionTree(max_depth=6, random_state=42).fit(X, y)\nprint(np.array_equal(t1.predict(X_te), t2.predict(X_te)))","expected_output":"True"}],"approved_user_libraries":["numpy"],"lower_is_better":false,"data_info":"sklearn digits dataset: 1797 samples of 8x8 grayscale handwritten digits flattened to 64 features, 10 classes (digits 0-9). Splits: 1200 train / 200 val / 397 test. Features standardized to zero mean, unit variance using training-set statistics.","time_limits":{"test":"180 seconds","dev":"120 seconds"},"example":{"input":{"X_train":"numpy array of shape (1200, 64) -- standardized 8x8 digit images flattened to 64 features","y_val":"numpy array of shape (200,) -- validation labels","y_train":"numpy array of shape (1200,) -- integer class labels in [0, 10)","X_val":"numpy array of shape (200, 64) -- standardized validation features"},"output":{"DecisionTree":"class instance with .fit(X, y) -> self and .predict(X) -> np.ndarray of int class labels"}},"model_specs":"Harness builds an ensemble of 30 user-defined `DecisionTree` instances, each trained on a fresh bootstrap sample (sampling with replacement, same size as training set) and given a distinct `random_state`. Predictions are aggregated by majority vote. Single-tree baseline (trained on full train set, no bootstrap) is reported for comparison but not scored.","description":"Implement a `DecisionTree` class. The harness creates 30 instances of your tree, trains each on a different bootstrap sample of the training data, and aggregates their predictions by majority vote to form a Random Forest. You are scored on the **ensemble's** accuracy on a held-out test set, not on any single tree's accuracy.\n\nThe dataset is sklearn's digits dataset (8x8 handwritten digit images, 10 classes, 64 features). Features are standardized before being passed to your tree. To clear the passing threshold, the trees in the ensemble must be **diverse** -- bootstrap sampling alone is not enough. Consider what randomization you can add inside your tree (hint: at each split, only look at a random subset of the features) so that different `random_state` values produce genuinely different trees.\n\nThe harness will also report a single-tree baseline accuracy so you can see the gap your ensemble adds beyond what one tree can do.","id":"26","difficulty":"hard","evaluation_metric":"ensemble_accuracy","schema":"practical_question_v1","min_eval_metric":0.9,"category":"Ensembles","title":"Build a Tree for a Random Forest","dataset":"sklearn digits","createdAt":"2026-05-13T21:01:42.366000+00:00","memory_limit":"1 GB","time_limits_seconds":{"dev":120,"test":180},"gpu":false},{"type":"general","constraints":["Implement the function `train_ensemble(base_models, X_val, y_val) -> predict_callable`.","`predict` must return a numpy array of integer class labels in [0, 10), with shape (n_samples,).","Do NOT retrain the base models. They are already fit on a separate training set.","You may use any sklearn module to build your combiner (e.g., a meta-learner).","You only have access to `X_val` and `y_val` for tuning. The held-out test set is invisible to you.","Calling the returned `predict` twice on the same input must give identical results."],"test_cases":[{"description":"train_ensemble returns a callable","test":"import numpy as np\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.tree import DecisionTreeClassifier\nnp.random.seed(0)\nX = np.random.randn(80, 8); y = np.random.randint(0, 3, 80)\nXv = np.random.randn(40, 8); yv = np.random.randint(0, 3, 40)\nmodels = [LogisticRegression(max_iter=500).fit(X, y), DecisionTreeClassifier(max_depth=4, random_state=0).fit(X, y)]\npredict = train_ensemble(models, Xv, yv)\nprint(callable(predict))","expected_output":"True"},{"description":"predict returns numpy array of correct shape","test":"import numpy as np\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.tree import DecisionTreeClassifier\nnp.random.seed(0)\nX = np.random.randn(80, 8); y = np.random.randint(0, 3, 80)\nXv = np.random.randn(40, 8); yv = np.random.randint(0, 3, 40)\nmodels = [LogisticRegression(max_iter=500).fit(X, y), DecisionTreeClassifier(max_depth=4, random_state=0).fit(X, y)]\npredict = train_ensemble(models, Xv, yv)\np = predict(np.random.randn(15, 8))\nprint(isinstance(p, np.ndarray) and p.shape == (15,))","expected_output":"True"},{"description":"predict returns valid integer class labels","test":"import numpy as np\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.tree import DecisionTreeClassifier\nnp.random.seed(0)\nX = np.random.randn(120, 8); y = np.random.randint(0, 3, 120)\nXv = np.random.randn(60, 8); yv = np.random.randint(0, 3, 60)\nmodels = [LogisticRegression(max_iter=500).fit(X, y), DecisionTreeClassifier(max_depth=4, random_state=0).fit(X, y)]\npredict = train_ensemble(models, Xv, yv)\np = predict(np.random.randn(30, 8))\nprint(set(np.unique(p).tolist()).issubset({0, 1, 2}))","expected_output":"True"},{"description":"predict gives identical results when called twice with same input","test":"import numpy as np\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.tree import DecisionTreeClassifier\nnp.random.seed(0)\nX = np.random.randn(80, 8); y = np.random.randint(0, 3, 80)\nXv = np.random.randn(40, 8); yv = np.random.randint(0, 3, 40)\nmodels = [LogisticRegression(max_iter=500).fit(X, y), DecisionTreeClassifier(max_depth=4, random_state=0).fit(X, y)]\npredict = train_ensemble(models, Xv, yv)\nXt = np.random.randn(20, 8)\np1 = predict(Xt); p2 = predict(Xt)\nprint(np.array_equal(p1, p2))","expected_output":"True"}],"approved_user_libraries":["numpy","sklearn"],"lower_is_better":false,"data_info":"sklearn digits dataset (1797 samples, 64 features = 8x8 grayscale digit images, 10 classes). Splits: 200 train / 300 val / 1297 test. Features standardized using training-set statistics. Base models are pre-trained on the 200-sample training set.","time_limits":{"test":"120 seconds","dev":"60 seconds"},"example":{"input":{"y_val":"numpy array of shape (300,) -- integer labels in [0, 10)","X_val":"numpy array of shape (300, 64) -- standardized 8x8 digit features","base_models":"list of 5 trained sklearn-style classifiers (LogisticRegression, DecisionTreeClassifier, KNeighborsClassifier, GaussianNB, RandomForestClassifier), each supporting .predict(X) and .predict_proba(X)"},"output":{"predict":"callable: predict(X) -> numpy array of shape (n,) of integer class labels in [0, 10)"}},"model_specs":"Five pre-trained sklearn classifiers (LogisticRegression, DecisionTreeClassifier, KNeighborsClassifier, GaussianNB, RandomForestClassifier) are passed to your `train_ensemble` function along with a validation set. Your function returns a `predict` callable; the harness evaluates it on a held-out test set. Reference baselines (best individual, naive hard voting, naive soft voting) are reported alongside your score.","description":"The harness has trained five different classifiers (Logistic Regression, Decision Tree, K-Nearest Neighbors, Gaussian Naive Bayes, Random Forest) on a small training set drawn from sklearn's digits dataset (10-class image classification). Your job is to write a function `train_ensemble(base_models, X_val, y_val)` that combines these pre-trained models into an ensemble classifier with higher accuracy than any single one of them.\n\nYou receive the trained base models (each with `.predict` and `.predict_proba`) plus a validation set you can use to fit any meta-parameters of your combiner -- weights, a stacking model, or whatever else you decide. You return a `predict(X)` callable that the harness will run on a held-out test set.\n\nThe win threshold is set deliberately so that naive strategies (returning the best single model, hard voting, soft voting) will not pass. To clear it, your combiner needs to extract information from how the base models *disagree* on the validation set.","id":"27","difficulty":"medium","evaluation_metric":"ensemble_accuracy","schema":"practical_question_v1","min_eval_metric":0.91,"category":"Ensembles","title":"Combine Trained Models into an Ensemble","dataset":"sklearn digits","createdAt":"2026-05-13T21:01:42.513000+00:00","memory_limit":"1 GB","time_limits_seconds":{"dev":60,"test":120},"gpu":false},{"type":"general","constraints":["Implement `train(X_unlabeled, X_labeled, y_labeled, X_val, y_val) -> predict_callable`.","`predict` must return a numpy array of integer class labels in [0, 10), shape (n_samples,).","Features have already been standardized using statistics from labeled + unlabeled samples. Do NOT re-standardize.","You may use any sklearn module (clustering, classification, manifold learning, mixture models, etc.).","Calling the returned `predict` twice on the same input must give identical results.","You only have access to `X_val` and `y_val` for tuning. The held-out test set is invisible."],"test_cases":[{"description":"train returns a callable","test":"import numpy as np\nnp.random.seed(0)\nXu = np.random.randn(100, 8)\nXl = np.random.randn(20, 8); yl = np.random.randint(0, 5, 20)\nXv = np.random.randn(30, 8); yv = np.random.randint(0, 5, 30)\npredict = train(Xu, Xl, yl, Xv, yv)\nprint(callable(predict))","expected_output":"True"},{"description":"predict returns numpy array of correct shape","test":"import numpy as np\nnp.random.seed(0)\nXu = np.random.randn(100, 8)\nXl = np.random.randn(20, 8); yl = np.random.randint(0, 5, 20)\nXv = np.random.randn(30, 8); yv = np.random.randint(0, 5, 30)\npredict = train(Xu, Xl, yl, Xv, yv)\np = predict(np.random.randn(15, 8))\nprint(isinstance(p, np.ndarray) and p.shape == (15,))","expected_output":"True"},{"description":"predict returns valid integer class labels","test":"import numpy as np\nnp.random.seed(0)\nXu = np.random.randn(200, 8)\nXl = np.random.randn(20, 8); yl = np.random.randint(0, 5, 20)\nXv = np.random.randn(30, 8); yv = np.random.randint(0, 5, 30)\npredict = train(Xu, Xl, yl, Xv, yv)\np = predict(np.random.randn(40, 8))\nprint(set(np.unique(p).tolist()).issubset({0, 1, 2, 3, 4}))","expected_output":"True"},{"description":"predict gives identical results when called twice","test":"import numpy as np\nnp.random.seed(0)\nXu = np.random.randn(150, 8)\nXl = np.random.randn(20, 8); yl = np.random.randint(0, 5, 20)\nXv = np.random.randn(30, 8); yv = np.random.randint(0, 5, 30)\npredict = train(Xu, Xl, yl, Xv, yv)\nXt = np.random.randn(20, 8)\np1 = predict(Xt); p2 = predict(Xt)\nprint(np.array_equal(p1, p2))","expected_output":"True"}],"approved_user_libraries":["numpy","sklearn"],"lower_is_better":false,"data_info":"sklearn digits dataset (1797 samples of 8x8 grayscale digit images, 64 features, 10 classes). Splits: 20 labeled (2 per class, stratified) + 1300 unlabeled + 200 validation + 277 test. Features standardized using statistics computed on labeled + unlabeled data combined.","time_limits":{"test":"120 seconds","dev":"60 seconds"},"example":{"input":{"y_val":"numpy array of shape (200,) -- validation labels","X_unlabeled":"numpy array of shape (1300, 64) -- standardized 8x8 digit features, no labels","X_labeled":"numpy array of shape (20, 64) -- standardized features (2 per class)","X_val":"numpy array of shape (200, 64) -- standardized validation features","y_labeled":"numpy array of shape (20,) -- integer labels in [0, 10)"},"output":{"predict":"callable: predict(X) -> numpy array of shape (n,) of integer class labels in [0, 10)"}},"model_specs":"User's choice of clustering method + downstream classifier. Harness loads digits, creates 2-per-class stratified labeled set + 1300 unlabeled + 200 val + 277 test split, standardizes features, calls user's `train`. Reference baselines reported: naive LR on labels-only and naive K-means with K=10 centroid-to-nearest-labeled propagation.","description":"You are given a tiny labeled set (20 samples = 2 per class) and a much larger unlabeled set (1300 samples) drawn from sklearn's digits dataset. A classifier trained on the 20 labels alone gets around 65-70% accuracy -- well below the threshold. Your job is to use the unlabeled data to do meaningfully better.\n\nThe standard approach (covered in Hands-On ML) is **cluster-based label propagation**: cluster all the data, propagate labels from the labeled samples to entire clusters, and train a downstream classifier on the resulting pseudo-labeled set. The harness reports two reference baselines so you can see what fails: naive logistic regression on the 20 labels, and naive K-means with K=10. Both fall well below the threshold; a correctly designed cluster-then-label pipeline clears it by 5+ points.\n\nYou receive `X_unlabeled`, `X_labeled`, `y_labeled`, `X_val`, `y_val` (validation set for tuning) and return a `predict(X)` callable that the harness applies to a held-out test set.","id":"28","difficulty":"medium","evaluation_metric":"test_accuracy","schema":"practical_question_v1","min_eval_metric":0.75,"category":"Clustering","title":"Few-Shot Classification with Cluster-Based Label Propagation","dataset":"sklearn digits","createdAt":"2026-05-13T21:01:42.654000+00:00","memory_limit":"1 GB","time_limits_seconds":{"dev":60,"test":120},"gpu":false},{"created_at":"2026-11-01T01:51:32.741000+00:00","type":"general","test_cases":[{"test":"import numpy as np\n_r = np.random.default_rng(3)\n_X = _r.standard_normal((400, 2))\n_y = _X[:, 0] + 0.5 * _r.standard_normal(400)\n_m = train(_X, _y, 5.0)\n_w, _mu, _s = (np.asarray(a, dtype=float) for a in predict_density(_m, _r.standard_normal((50, 2))))\nprint(\"three arrays of shape (50, K):\", _w.ndim == 2 and _w.shape[0] == 50 and _w.shape == _mu.shape == _s.shape)\nprint(\"weights sum to 1:\", bool(np.all(_w >= 0) and np.all(np.abs(_w.sum(1) - 1) < 1e-6)))\nprint(\"sigmas positive:\", bool(np.all(_s > 0)))","expected_output":"three arrays of shape (50, K): True\nweights sum to 1: True\nsigmas positive: True"},{"test":"import numpy as np\n_r = np.random.default_rng(5)\n_X = _r.uniform(-2, 2, (1500, 2))\n_y = 3 * _X[:, 0] + 0.3 * _r.standard_normal(1500)\n_m = train(_X, _y, 5.0)\n_Xq = _r.uniform(-2, 2, (300, 2))\n_w, _mu, _s = (np.asarray(a, dtype=float) for a in predict_density(_m, _Xq))\n_mean = (_w * _mu).sum(1)\nprint(\"the predicted mean follows x:\", bool(np.mean(np.abs(_mean - 3 * _Xq[:, 0])) < 0.5))","expected_output":"the predicted mean follows x: True"},{"test":"import numpy as np\ndef _q(out, grid):\n    w, m, s = (np.asarray(a, dtype=float) for a in out)\n    t = (grid[None, None, :] - m[:, :, None]) / s[:, :, None]\n    return (w[:, :, None] * np.exp(-0.5 * t * t) / (s[:, :, None] * np.sqrt(2 * np.pi))).sum(1)\n_r = np.random.default_rng(7)\n_X = _r.standard_normal((1500, 2))\n_y = np.where(_r.uniform(size=1500) < 0.5, 1.0, -1.0) + 0.1 * _r.standard_normal(1500)\n_m = train(_X, _y, 5.0)\n_d = _q(predict_density(_m, _r.standard_normal((100, 2)) * 0.5), np.array([-1.0, 0.0, 1.0])).mean(0)\nprint(\"density is higher at both answers than between them:\", bool(_d[0] > 3 * _d[1] and _d[2] > 3 * _d[1]))","expected_output":"density is higher at both answers than between them: True"}],"approved_user_libraries":["numpy","scipy","sklearn","torch","xgboost","lightgbm"],"lower_is_better":true,"data_info":"Synthetic worlds generated inside the grader (no download). Each has 2,500 to 5,000 training rows, 2 to 5 input columns in arbitrary units, and a true conditional density known to the grader. Run: 5 worlds. Submit: 13 different worlds, including generators and noise shapes that Run never shows.","time_limits":{"test":540,"dev":240},"example":{"input":"train(X, y, 25.0) with X of shape (3000, 2), then predict_density(model, X_new) with X_new of shape (2000, 2)","output":"(weights, means, sigmas), each of shape (2000, K); the score is the mean KL in nats from the true conditional density (pass at 0.38 or lower)"},"gpu":false,"description":"The book warns that a model trained with a unimodal output density, \"even if the model is a flexible nonlinear model, such as neural network\", works poorly on one-to-many functions, where one input has several possible outputs. It \"will just produce a blurry average output\". The classic case is an inverse problem where the middle of the input range has two equally probable answers.\n\nHere every problem comes from a hidden generator whose true conditional density $p^*(y \\mid x)$ the grader knows. You return a Gaussian mixture for each input, and the grader measures how far it is from the truth. Any method is allowed.\n\n## Your functions\n\n```python\ndef train(X, y, budget_seconds):\n    ...\n    return model\n\ndef predict_density(model, X):\n    ...\n    return weights, means, sigmas\n```\n\n- `train` gets `X` of shape `(n, d)` and `y` of shape `(n,)`, with $n$ from 2,500 to 5,000 and $d$ from 2 to 5. `budget_seconds` is 25. `model` can be anything you like.\n- `predict_density` gets the same `model` and 2,000 new rows of `X`. It returns three float arrays of shape `(2000, K)`, where $1 \\le K \\le 32$ is your choice and may differ between worlds. Row $i$ describes\n\n$$q(y \\mid x_i) = \\sum_{k=1}^{K} w_{ik}\\, \\mathcal{N}(y \\mid \\mu_{ik}, \\sigma_{ik}^2)$$\n\n## The worlds\n\nEach world is its own generator with its own hidden parameters. Inputs and outputs are in arbitrary units: every column of `X` and `y` has its own scale and offset, and the columns of `X` are rotated together, so no single column is guaranteed to mean anything. The new rows come from the same input distribution as the training rows. The worlds include:\n\n- inverse problems in the spirit of the book's inverted-sine example, where a noisy forward map is run backwards, some with noise that grows with $|x|$ as in the book's heteroskedastic example;\n- recovering one joint angle of a two-link arm from a noisy position of its end;\n- gated branches, where the centres, widths and probabilities of the branches all depend on $x$;\n- a world with a single mode, where one Gaussian is the right answer;\n- worlds with columns that carry no information.\n\n**Run** scores 5 worlds. **Submit** scores 13 different worlds, including kinds of generator and noise that Run never shows.\n\n## Score (lower is better)\n\n$$\\text{score} = \\frac{1}{W} \\sum_{w=1}^{W} \\frac{1}{2000} \\sum_{i=1}^{2000} \\min\\left(\\mathrm{KL}\\left(p^*(\\cdot \\mid x_i)\\ \\|\\ q(\\cdot \\mid x_i)\\right),\\ 10\\right)$$\n\nThe KL divergence is in nats and is computed by numerical integration of the true density over $y$, so no sampled outcome is involved and the score has no outcome noise. It equals your expected negative log-likelihood minus that of the truth, and it does not depend on the units of $y$. A perfect model scores 0.\n\nYou pass at **0.38** or lower; below that, lower ranks higher. The report prints `best_single_gaussian`: the score of the single Gaussian with the true mean and variance at every $x$, which is the best any single Gaussian could reach on those worlds even with the generator in hand. It is 0.88 on Run and 0.99 on Submit, well above the floor. The starter, which uses one Gaussian and ignores $x$, scores 1.89 on Run and 1.69 on Submit.\n\n## Rules, budget and gates\n\n- `train` gets at most 25 s of CPU time per world, counted over all threads and worker processes, and 55 s of wall time. `predict_density` gets 10 s of CPU time. Before each world the grader sets torch, BLAS and OpenMP libraries to 1 thread and tells joblib there is 1 CPU. You may raise these, but every extra thread and worker counts toward the same budget. Machines differ in speed, so a model that stops on the clock can score differently from one run to the next.\n- Every row of `weights` must be non-negative and sum to 1 within $10^{-6}$. Every sigma must be at least 0.005 times the standard deviation of that world's `y`. NaN and infinity are refused.\n- The run fails with a score of 99 if a rule above is broken or your code raises or exits.\n- You may import numpy, scipy, scikit-learn, torch, xgboost, lightgbm, and these standard-library modules: `math`, `itertools`, `collections`, `heapq`, `bisect`, `random`, `statistics`, `time`, `warnings`, `typing`, `copy`, `dataclasses`.\n- Ordinary classes work: `self.something = ...` is allowed in any method of a class you define, so `class MDN(nn.Module)` and dataclasses are fine. Any other attribute write, such as `obj.x = 1` or `p.grad = None`, is refused; keep other state in a dict or a list. An imported module can be used only as `module.something`, so write `import torch.nn as nn` rather than `nn = torch.nn`. Files, dynamic attribute access, private attributes of other objects and a short list of names such as `os`, `sys`, `functools`, `np.load` and `torch.save` are refused, and the message names what it found. A run that changes a file under the Python installation or the system libraries is refused too.\n- Your source is limited to 30,000 characters, 500 numeric literals and 2,000 characters of strings outside docstrings.\n- Printing works on Run. On Submit, output from your functions is discarded.\n\nRun prints one line per world with its score, `best_single_gaussian` and the kind of generator. Submit prints the same lines without the kind.","tags":["mixture-density-network","mixture-of-experts","density-estimation","probabilistic-ml","open-ended","leaderboard"],"id":"28b76f38-7e5a-43fe-8b0d-f2c98168e113","dataset_id":"synthetic","img_type":"full","difficulty":"hard","evaluation_metric":"kl_nats","min_eval_metric":0.38,"category":"Machine Learning","dataset":"Synthetic one-to-many worlds with known conditional density (generated in the grader)","title":"Best Predictive Density on a One-to-Many Problem","time_limits_seconds":{"dev":240,"test":540}},{"type":"epoch","constraints":["Implement a top-level function train(model, tokenizer, train_texts, val_texts) and return the trained model.","Do NOT load the dataset yourself — train_texts and val_texts are provided.","Use the model passed to your function (or wrap/replace it inside train() — your call).","You do NOT need to print anything — the validator handles all output formatting.","Time limit: 60s for Run, 120s for Submit. Model + dataset download eat ~20-30s; train accordingly.","No outbound network beyond what transformers and datasets already do (HuggingFace Hub for model + dataset)."],"test_cases":[{"test":"print(callable(train))","expected_output":"True"},{"test":"import inspect\nprint(len(inspect.signature(train).parameters) == 4)","expected_output":"True"},{"test":"import inspect\nparams = list(inspect.signature(train).parameters)\nprint(params == ['model', 'tokenizer', 'train_texts', 'val_texts'])","expected_output":"True"}],"approved_user_libraries":["torch","transformers","peft","datasets","accelerate","torchao","numpy","pandas","scikit-learn","math","json"],"lower_is_better":true,"data_info":"TinyStories is a synthetic dataset of short children's-book-style stories (~250 tokens each), built specifically to train and study tiny language models. The validator streams a slice from the HuggingFace Hub and passes Python lists train_texts and val_texts (list[str]) to your train() function. Validator uses 50 train / 10 val. Grader uses 200 train / 30 val from a different slice.","time_limits":{"test":120,"dev":60},"example":{"input":{"val_texts":["The little dog wagged his tail and barked at the butterfly."],"train_texts":["Once upon a time, there was a little cat named Whiskers. Whiskers loved to play in the garden.","Lily was a happy girl who loved her teddy bear. Every night she hugged it tight."]},"output":{"final_val_acc":3.15}},"model_specs":"distilgpt2 — 82M params, 6 transformer layers, 768 hidden dim. Loaded in fp16 on cuda. Attention QKV is packed in a single transformers.pytorch_utils.Conv1D module named c_attn (relevant when targeting LoRA).","gpu":true,"description":"## Fine-Tune DistilGPT2 on TinyStories\n\nYou get a **distilgpt2** model loaded on a T4 GPU, a **tokenizer**, and two lists of short text samples drawn from the [TinyStories](https://huggingface.co/datasets/roneneldan/TinyStories) dataset (children's-book-simple stories that distilgpt2 has never seen). Your job is to fine-tune the model on **train_texts** so the held-out **val_loss** drops as low as possible — using **any method you like**.\n\n### Your contract\n\nImplement this function:\n\n```python\ndef train(model, tokenizer, train_texts, val_texts):\n    # ... your training logic here ...\n    return model\n```\n\nThat's it. Return the trained model. You **don't need to print anything** — the validator measures val_loss after your training and reports it automatically.\n\n### What you're optimizing\n\nYour score is **val_loss** — mean cross-entropy on a held-out TinyStories slice. **Lower is better.**\n\n- Untrained distilgpt2 baseline: ~4.5 nats\n- Well-fine-tuned: ~3.0 nats\n- **Pass threshold: val_loss ≤ 4.0**\n\n### Recommended approach\n\n**LoRA** is the highest-value method for this lab — small param count, fast on T4, and the Learn tab walks through it in detail. A reference LoRA recipe (r=8 on `c_attn`, AdamW lr=5e-4, 3 epochs, batch=4) reliably hits val_loss ~3.0 in under 90 seconds.\n\nOther viable methods (all admissible):\n\n- **Full fine-tuning** — unfreeze everything, train with lr around 1e-5 to 5e-5.\n- **DoRA** — `LoraConfig(..., use_dora=True)`. Slightly better than LoRA at the same rank.\n- **Prefix / prompt / P-tuning** — via peft.\n- **IA³** — even smaller than LoRA.\n- **Layer freezing** — train only the last block + `lm_head`.\n- **BitFit** — bias-only training (~36k params).\n- **Custom optimizer / schedule** — AdamW + cosine warmup + gradient clipping, etc.\n\n### Compute\n\n- GPU: T4 (16 GB VRAM)\n- Time budget: 60s for Run, 120s for Submit. Model download ~15–20s; dataset stream ~3–5s; training fills the rest.","tags":["llm","fine-tuning","gpu","transformers","tinystories","peft","lora"],"id":"29","difficulty":"hard","evaluation_metric":"val_loss","schema":"train_texts: list[str]  # 50 stories (dev) or 200 stories (test)\nval_texts:   list[str]  # 10 stories (dev) or 30 stories (test)\n# each story is plain UTF-8 text, ~50-400 tokens.","min_eval_metric":4.0,"category":"LLM Fine-Tuning","title":"Fine-Tune DistilGPT2 on TinyStories","dataset":"TinyStories (roneneldan/TinyStories) — streamed slice","createdAt":"2026-05-13T21:01:42.779000+00:00","memory_limit":"16 GB VRAM (T4)","time_limits_seconds":{"dev":60,"test":120}},{"created_at":"2026-11-06T15:19:41.266000+00:00","type":"general","constraints":["expert evaluations (nonzero weights) per scored forward pass at most 0.5 x trained k x layers x tokens; at most the trained k per token per layer","plan gets 5 s per model; all route calls of a model share 1 s; 15% late stops the run","route returns finite, nonnegative weights of shape (n, E), row for row; rows arrive shuffled","numpy and torch on a Tesla T4; the harness owns all data access","attribute assignment only on self inside a method of a class"],"test_cases":[{"test":"import math\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n# Byte-level mixture-of-experts LM shared by the judge (trains it, scores it) and the learner's process (a copy to\n# experiment with). Pasted into both; keep it self-contained.\n\n\n\nclass RMSNorm(nn.Module):\n    def __init__(self, d, eps=1e-6):\n        super().__init__()\n        self.eps = eps\n        self.weight = nn.Parameter(torch.ones(d))\n\n    def forward(self, x):\n        return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps) * self.weight\n\n\nclass Block(nn.Module):\n    def __init__(self, d, n_heads, n_experts, hidden):\n        super().__init__()\n        self.n_heads = n_heads\n        self.norm1 = RMSNorm(d)\n        self.qkv = nn.Linear(d, 3 * d, bias=False)\n        self.proj = nn.Linear(d, d, bias=False)\n        self.norm2 = RMSNorm(d)\n        self.router = nn.Linear(d, n_experts, bias=False)\n        s = 1.0 / math.sqrt(d)\n        self.w_gate = nn.Parameter(torch.randn(n_experts, d, hidden) * s)\n        self.w_up = nn.Parameter(torch.randn(n_experts, d, hidden) * s)\n        self.w_down = nn.Parameter(torch.randn(n_experts, hidden, d) * (1.0 / math.sqrt(hidden)))\n\n\ndef rope(x, cos, sin):\n    a, b = x[..., 0::2], x[..., 1::2]\n    return torch.stack((a * cos - b * sin, a * sin + b * cos), dim=-1).flatten(-2)\n\n\nclass MoELM(nn.Module):\n    \"\"\"Pre-norm decoder; every block's feed-forward is a routed mixture of SwiGLU experts.\n    Trained routing: softmax over all expert logits, keep the top k, divide by their sum.\"\"\"\n\n    def __init__(self, vocab, d, n_layers, n_heads, n_experts, k, hidden, max_len=256):\n        super().__init__()\n        self.cfg = dict(vocab=vocab, d=d, n_layers=n_layers, n_heads=n_heads, n_experts=n_experts, k=k, hidden=hidden,\n                        max_len=max_len)\n        self.n_layers, self.n_experts, self.trained_k = n_layers, n_experts, k\n        self.emb = nn.Embedding(vocab, d)\n        self.blocks = nn.ModuleList([Block(d, n_heads, n_experts, hidden) for _ in range(n_layers)])\n        self.norm = RMSNorm(d)\n        self.head = nn.Linear(d, vocab, bias=False)\n        hd = d // n_heads\n        inv = 1.0 / (10000 ** (torch.arange(0, hd, 2).float() / hd))\n        ang = torch.arange(max_len).float()[:, None] * inv[None, :]\n        self.register_buffer(\"cos\", ang.cos(), persistent=False)\n        self.register_buffer(\"sin\", ang.sin(), persistent=False)\n        self.register_buffer(\"mask\", torch.ones(max_len, max_len, dtype=torch.bool).triu(1), persistent=False)\n\n    def trained_weights(self, logits):\n        \"\"\"The routing the model was trained with, as dense (n, E) weights.\"\"\"\n        p = torch.softmax(logits.float(), dim=-1)\n        top, idx = p.topk(self.trained_k, dim=-1)\n        w = torch.zeros_like(p)\n        return w.scatter(-1, idx, top / top.sum(-1, keepdim=True))\n\n    def attend(self, blk, x):\n        B, T, d = x.shape\n        q, k, v = blk.qkv(blk.norm1(x)).view(B, T, 3, blk.n_heads, d // blk.n_heads).permute(2, 0, 3, 1, 4)\n        q, k = rope(q, self.cos[:T], self.sin[:T]), rope(k, self.cos[:T], self.sin[:T])\n        att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(q.shape[-1]))\n        att = att.masked_fill(self.mask[:T, :T], float(\"-inf\"))\n        y = torch.softmax(att, dim=-1) @ v\n        return blk.proj(y.transpose(1, 2).reshape(B, T, d))\n\n    @staticmethod\n    def experts(blk, h, w):\n        \"\"\"sum_e w[:, e] * expert_e(h). On a GPU every expert runs on every row (zero weights add nothing); on a CPU\n        each expert runs only on the rows that give it a nonzero weight. The two agree to float rounding.\"\"\"\n        if h.is_cuda:\n            E, d, hid = blk.w_gate.shape\n            a = h @ blk.w_gate.permute(1, 0, 2).reshape(d, E * hid)\n            b = h @ blk.w_up.permute(1, 0, 2).reshape(d, E * hid)\n            z = (F.silu(a) * b).view(-1, E, hid) * w.unsqueeze(-1)\n            return z.view(-1, E * hid) @ blk.w_down.reshape(E * hid, d)\n        out = torch.zeros_like(h)\n        nz = w != 0\n        for e in range(w.shape[1]):\n            rows = nz[:, e].nonzero().squeeze(1)\n            if rows.numel() == 0:\n                continue\n            x = h.index_select(0, rows)\n            y = (F.silu(x @ blk.w_gate[e]) * (x @ blk.w_up[e])) @ blk.w_down[e]\n            out.index_add_(0, rows, y * w.index_select(0, rows)[:, e:e + 1])\n        return out\n\n    def forward(self, ids, route=None, aux=None):\n        \"\"\"ids (B, T) int64. route(layer, logits) -> weights, numpy (n, E) both ways; None = trained routing.\n        aux: a list to append (router logits, weights) per layer to, for the training losses.\"\"\"\n        x = self.emb(ids)\n        B, T, d = x.shape\n        for li, blk in enumerate(self.blocks):\n            x = x + self.attend(blk, x)\n            h = blk.norm2(x).reshape(B * T, d)\n            logits = blk.router(h)\n            if route is None:\n                w = self.trained_weights(logits)\n            else:\n                w = torch.as_tensor(np.asarray(route(li, logits.detach().float().cpu().numpy()), dtype=np.float32),\n                                    device=h.device)\n            if aux is not None:\n                aux.append((logits, w))\n            x = x + self.experts(blk, h, w.to(h.dtype)).view(B, T, d)\n        return self.head(self.norm(x))\n\n\ndef build(cfg, seed):\n    g = torch.random.fork_rng()\n    with g:\n        torch.manual_seed(seed)\n        m = MoELM(**cfg)\n    return m\n\n\ndef train_model(cfg, data, seed, steps, batch, seq, lr=3e-3, alpha=0.01, zcoef=1e-3, log=None, device=\"cpu\"):\n    \"\"\"data: uint8 numpy array of bytes. Deterministic given seed (on one host).\"\"\"\n    with torch.random.fork_rng():\n        torch.manual_seed(seed)\n        m = MoELM(**cfg).to(device)\n        rng = np.random.default_rng(seed + 1)\n        opt = torch.optim.AdamW(m.parameters(), lr=lr, betas=(0.9, 0.95), weight_decay=0.0)\n        E = cfg[\"n_experts\"]\n        warm = max(1, steps // 10)\n        for step in range(steps):\n            frac = min(1.0, (step + 1) / warm) * (0.5 * (1 + math.cos(math.pi * step / steps)) * 0.9 + 0.1)\n            for gr in opt.param_groups:\n                gr[\"lr\"] = lr * frac\n            starts = rng.integers(0, len(data) - seq - 1, size=batch)\n            xy = torch.from_numpy(np.stack([data[s:s + seq + 1] for s in starts]).astype(np.int64)).to(device)\n            aux = []\n            logits = m(xy[:, :-1], aux=aux)\n            loss = F.cross_entropy(logits.reshape(-1, logits.shape[-1]), xy[:, 1:].reshape(-1))\n            bal = 0.0\n            for lg, w in aux:\n                p = torch.softmax(lg, -1)\n                f = (w > 0).float().mean(0) * E / cfg[\"k\"]\n                bal = bal + alpha * (f * p.mean(0)).sum() + zcoef * torch.logsumexp(lg, -1).pow(2).mean()\n            opt.zero_grad(set_to_none=True)\n            (loss + bal / len(aux)).backward()\n            torch.nn.utils.clip_grad_norm_(m.parameters(), 1.0)\n            opt.step()\n            if log is not None and (step % 50 == 0 or step == steps - 1):\n                log.append((step, float(loss)))\n    m.eval()\n    return m\n\n\ndef kl_bits(full_logits, served_logits):\n    \"\"\"Per-position KL(full || served) in bits, float64.\"\"\"\n    lp = torch.log_softmax(full_logits.double(), -1)\n    lq = torch.log_softmax(served_logits.double(), -1)\n    return ((lp.exp() * (lp - lq)).sum(-1) / math.log(2.0))\nclass _Toy(MoELM):\n    budget = 2.0\n    device = torch.device('cpu')\ndef _kl(m, c, fn):\n    with torch.no_grad():\n        return float(kl_bits(m(c), m(c, route=fn)).mean())\ndef _naive(layer, lg):\n    p = torch.softmax(torch.as_tensor(lg), -1)\n    v, i = p.topk(2, -1)\n    return torch.zeros_like(p).scatter(-1, i, v).numpy()\ntry:\n    _w\nexcept NameError:\n    torch.manual_seed(0)\n    _m = _Toy(256, 32, 2, 4, 8, 4, 32, 64).eval()\n    for _p in _m.parameters():\n        _p.requires_grad_(False)\n    _c = torch.randint(0, 256, (8, 64))\n    _pol = plan(_m, _c, 2.0)\n    _lg = np.random.default_rng(1).normal(size=(300, 8)).astype(np.float32)\n    _w = route(_pol, 0, _lg)\n    if isinstance(_w, torch.Tensor):\n        _w = _w.detach().cpu().numpy()\n    _w = np.asarray(_w, dtype=np.float32)\nprint(_w.shape)","expected_output":"(300, 8)"},{"test":"import math\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n# Byte-level mixture-of-experts LM shared by the judge (trains it, scores it) and the learner's process (a copy to\n# experiment with). Pasted into both; keep it self-contained.\n\n\n\nclass RMSNorm(nn.Module):\n    def __init__(self, d, eps=1e-6):\n        super().__init__()\n        self.eps = eps\n        self.weight = nn.Parameter(torch.ones(d))\n\n    def forward(self, x):\n        return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps) * self.weight\n\n\nclass Block(nn.Module):\n    def __init__(self, d, n_heads, n_experts, hidden):\n        super().__init__()\n        self.n_heads = n_heads\n        self.norm1 = RMSNorm(d)\n        self.qkv = nn.Linear(d, 3 * d, bias=False)\n        self.proj = nn.Linear(d, d, bias=False)\n        self.norm2 = RMSNorm(d)\n        self.router = nn.Linear(d, n_experts, bias=False)\n        s = 1.0 / math.sqrt(d)\n        self.w_gate = nn.Parameter(torch.randn(n_experts, d, hidden) * s)\n        self.w_up = nn.Parameter(torch.randn(n_experts, d, hidden) * s)\n        self.w_down = nn.Parameter(torch.randn(n_experts, hidden, d) * (1.0 / math.sqrt(hidden)))\n\n\ndef rope(x, cos, sin):\n    a, b = x[..., 0::2], x[..., 1::2]\n    return torch.stack((a * cos - b * sin, a * sin + b * cos), dim=-1).flatten(-2)\n\n\nclass MoELM(nn.Module):\n    \"\"\"Pre-norm decoder; every block's feed-forward is a routed mixture of SwiGLU experts.\n    Trained routing: softmax over all expert logits, keep the top k, divide by their sum.\"\"\"\n\n    def __init__(self, vocab, d, n_layers, n_heads, n_experts, k, hidden, max_len=256):\n        super().__init__()\n        self.cfg = dict(vocab=vocab, d=d, n_layers=n_layers, n_heads=n_heads, n_experts=n_experts, k=k, hidden=hidden,\n                        max_len=max_len)\n        self.n_layers, self.n_experts, self.trained_k = n_layers, n_experts, k\n        self.emb = nn.Embedding(vocab, d)\n        self.blocks = nn.ModuleList([Block(d, n_heads, n_experts, hidden) for _ in range(n_layers)])\n        self.norm = RMSNorm(d)\n        self.head = nn.Linear(d, vocab, bias=False)\n        hd = d // n_heads\n        inv = 1.0 / (10000 ** (torch.arange(0, hd, 2).float() / hd))\n        ang = torch.arange(max_len).float()[:, None] * inv[None, :]\n        self.register_buffer(\"cos\", ang.cos(), persistent=False)\n        self.register_buffer(\"sin\", ang.sin(), persistent=False)\n        self.register_buffer(\"mask\", torch.ones(max_len, max_len, dtype=torch.bool).triu(1), persistent=False)\n\n    def trained_weights(self, logits):\n        \"\"\"The routing the model was trained with, as dense (n, E) weights.\"\"\"\n        p = torch.softmax(logits.float(), dim=-1)\n        top, idx = p.topk(self.trained_k, dim=-1)\n        w = torch.zeros_like(p)\n        return w.scatter(-1, idx, top / top.sum(-1, keepdim=True))\n\n    def attend(self, blk, x):\n        B, T, d = x.shape\n        q, k, v = blk.qkv(blk.norm1(x)).view(B, T, 3, blk.n_heads, d // blk.n_heads).permute(2, 0, 3, 1, 4)\n        q, k = rope(q, self.cos[:T], self.sin[:T]), rope(k, self.cos[:T], self.sin[:T])\n        att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(q.shape[-1]))\n        att = att.masked_fill(self.mask[:T, :T], float(\"-inf\"))\n        y = torch.softmax(att, dim=-1) @ v\n        return blk.proj(y.transpose(1, 2).reshape(B, T, d))\n\n    @staticmethod\n    def experts(blk, h, w):\n        \"\"\"sum_e w[:, e] * expert_e(h). On a GPU every expert runs on every row (zero weights add nothing); on a CPU\n        each expert runs only on the rows that give it a nonzero weight. The two agree to float rounding.\"\"\"\n        if h.is_cuda:\n            E, d, hid = blk.w_gate.shape\n            a = h @ blk.w_gate.permute(1, 0, 2).reshape(d, E * hid)\n            b = h @ blk.w_up.permute(1, 0, 2).reshape(d, E * hid)\n            z = (F.silu(a) * b).view(-1, E, hid) * w.unsqueeze(-1)\n            return z.view(-1, E * hid) @ blk.w_down.reshape(E * hid, d)\n        out = torch.zeros_like(h)\n        nz = w != 0\n        for e in range(w.shape[1]):\n            rows = nz[:, e].nonzero().squeeze(1)\n            if rows.numel() == 0:\n                continue\n            x = h.index_select(0, rows)\n            y = (F.silu(x @ blk.w_gate[e]) * (x @ blk.w_up[e])) @ blk.w_down[e]\n            out.index_add_(0, rows, y * w.index_select(0, rows)[:, e:e + 1])\n        return out\n\n    def forward(self, ids, route=None, aux=None):\n        \"\"\"ids (B, T) int64. route(layer, logits) -> weights, numpy (n, E) both ways; None = trained routing.\n        aux: a list to append (router logits, weights) per layer to, for the training losses.\"\"\"\n        x = self.emb(ids)\n        B, T, d = x.shape\n        for li, blk in enumerate(self.blocks):\n            x = x + self.attend(blk, x)\n            h = blk.norm2(x).reshape(B * T, d)\n            logits = blk.router(h)\n            if route is None:\n                w = self.trained_weights(logits)\n            else:\n                w = torch.as_tensor(np.asarray(route(li, logits.detach().float().cpu().numpy()), dtype=np.float32),\n                                    device=h.device)\n            if aux is not None:\n                aux.append((logits, w))\n            x = x + self.experts(blk, h, w.to(h.dtype)).view(B, T, d)\n        return self.head(self.norm(x))\n\n\ndef build(cfg, seed):\n    g = torch.random.fork_rng()\n    with g:\n        torch.manual_seed(seed)\n        m = MoELM(**cfg)\n    return m\n\n\ndef train_model(cfg, data, seed, steps, batch, seq, lr=3e-3, alpha=0.01, zcoef=1e-3, log=None, device=\"cpu\"):\n    \"\"\"data: uint8 numpy array of bytes. Deterministic given seed (on one host).\"\"\"\n    with torch.random.fork_rng():\n        torch.manual_seed(seed)\n        m = MoELM(**cfg).to(device)\n        rng = np.random.default_rng(seed + 1)\n        opt = torch.optim.AdamW(m.parameters(), lr=lr, betas=(0.9, 0.95), weight_decay=0.0)\n        E = cfg[\"n_experts\"]\n        warm = max(1, steps // 10)\n        for step in range(steps):\n            frac = min(1.0, (step + 1) / warm) * (0.5 * (1 + math.cos(math.pi * step / steps)) * 0.9 + 0.1)\n            for gr in opt.param_groups:\n                gr[\"lr\"] = lr * frac\n            starts = rng.integers(0, len(data) - seq - 1, size=batch)\n            xy = torch.from_numpy(np.stack([data[s:s + seq + 1] for s in starts]).astype(np.int64)).to(device)\n            aux = []\n            logits = m(xy[:, :-1], aux=aux)\n            loss = F.cross_entropy(logits.reshape(-1, logits.shape[-1]), xy[:, 1:].reshape(-1))\n            bal = 0.0\n            for lg, w in aux:\n                p = torch.softmax(lg, -1)\n                f = (w > 0).float().mean(0) * E / cfg[\"k\"]\n                bal = bal + alpha * (f * p.mean(0)).sum() + zcoef * torch.logsumexp(lg, -1).pow(2).mean()\n            opt.zero_grad(set_to_none=True)\n            (loss + bal / len(aux)).backward()\n            torch.nn.utils.clip_grad_norm_(m.parameters(), 1.0)\n            opt.step()\n            if log is not None and (step % 50 == 0 or step == steps - 1):\n                log.append((step, float(loss)))\n    m.eval()\n    return m\n\n\ndef kl_bits(full_logits, served_logits):\n    \"\"\"Per-position KL(full || served) in bits, float64.\"\"\"\n    lp = torch.log_softmax(full_logits.double(), -1)\n    lq = torch.log_softmax(served_logits.double(), -1)\n    return ((lp.exp() * (lp - lq)).sum(-1) / math.log(2.0))\nclass _Toy(MoELM):\n    budget = 2.0\n    device = torch.device('cpu')\ndef _kl(m, c, fn):\n    with torch.no_grad():\n        return float(kl_bits(m(c), m(c, route=fn)).mean())\ndef _naive(layer, lg):\n    p = torch.softmax(torch.as_tensor(lg), -1)\n    v, i = p.topk(2, -1)\n    return torch.zeros_like(p).scatter(-1, i, v).numpy()\ntry:\n    _w\nexcept NameError:\n    torch.manual_seed(0)\n    _m = _Toy(256, 32, 2, 4, 8, 4, 32, 64).eval()\n    for _p in _m.parameters():\n        _p.requires_grad_(False)\n    _c = torch.randint(0, 256, (8, 64))\n    _pol = plan(_m, _c, 2.0)\n    _lg = np.random.default_rng(1).normal(size=(300, 8)).astype(np.float32)\n    _w = route(_pol, 0, _lg)\n    if isinstance(_w, torch.Tensor):\n        _w = _w.detach().cpu().numpy()\n    _w = np.asarray(_w, dtype=np.float32)\n_ws = [np.asarray(route(_pol, _l, _lg), dtype=np.float32) for _l in range(2)]\nprint(bool(all(np.all(np.isfinite(_x)) and np.all(_x >= 0) and (_x != 0).sum(1).max() <= 4 for _x in _ws) and sum((_x != 0).sum() for _x in _ws) <= 2 * 2 * 300))","expected_output":"True"},{"test":"import math\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n# Byte-level mixture-of-experts LM shared by the judge (trains it, scores it) and the learner's process (a copy to\n# experiment with). Pasted into both; keep it self-contained.\n\n\n\nclass RMSNorm(nn.Module):\n    def __init__(self, d, eps=1e-6):\n        super().__init__()\n        self.eps = eps\n        self.weight = nn.Parameter(torch.ones(d))\n\n    def forward(self, x):\n        return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps) * self.weight\n\n\nclass Block(nn.Module):\n    def __init__(self, d, n_heads, n_experts, hidden):\n        super().__init__()\n        self.n_heads = n_heads\n        self.norm1 = RMSNorm(d)\n        self.qkv = nn.Linear(d, 3 * d, bias=False)\n        self.proj = nn.Linear(d, d, bias=False)\n        self.norm2 = RMSNorm(d)\n        self.router = nn.Linear(d, n_experts, bias=False)\n        s = 1.0 / math.sqrt(d)\n        self.w_gate = nn.Parameter(torch.randn(n_experts, d, hidden) * s)\n        self.w_up = nn.Parameter(torch.randn(n_experts, d, hidden) * s)\n        self.w_down = nn.Parameter(torch.randn(n_experts, hidden, d) * (1.0 / math.sqrt(hidden)))\n\n\ndef rope(x, cos, sin):\n    a, b = x[..., 0::2], x[..., 1::2]\n    return torch.stack((a * cos - b * sin, a * sin + b * cos), dim=-1).flatten(-2)\n\n\nclass MoELM(nn.Module):\n    \"\"\"Pre-norm decoder; every block's feed-forward is a routed mixture of SwiGLU experts.\n    Trained routing: softmax over all expert logits, keep the top k, divide by their sum.\"\"\"\n\n    def __init__(self, vocab, d, n_layers, n_heads, n_experts, k, hidden, max_len=256):\n        super().__init__()\n        self.cfg = dict(vocab=vocab, d=d, n_layers=n_layers, n_heads=n_heads, n_experts=n_experts, k=k, hidden=hidden,\n                        max_len=max_len)\n        self.n_layers, self.n_experts, self.trained_k = n_layers, n_experts, k\n        self.emb = nn.Embedding(vocab, d)\n        self.blocks = nn.ModuleList([Block(d, n_heads, n_experts, hidden) for _ in range(n_layers)])\n        self.norm = RMSNorm(d)\n        self.head = nn.Linear(d, vocab, bias=False)\n        hd = d // n_heads\n        inv = 1.0 / (10000 ** (torch.arange(0, hd, 2).float() / hd))\n        ang = torch.arange(max_len).float()[:, None] * inv[None, :]\n        self.register_buffer(\"cos\", ang.cos(), persistent=False)\n        self.register_buffer(\"sin\", ang.sin(), persistent=False)\n        self.register_buffer(\"mask\", torch.ones(max_len, max_len, dtype=torch.bool).triu(1), persistent=False)\n\n    def trained_weights(self, logits):\n        \"\"\"The routing the model was trained with, as dense (n, E) weights.\"\"\"\n        p = torch.softmax(logits.float(), dim=-1)\n        top, idx = p.topk(self.trained_k, dim=-1)\n        w = torch.zeros_like(p)\n        return w.scatter(-1, idx, top / top.sum(-1, keepdim=True))\n\n    def attend(self, blk, x):\n        B, T, d = x.shape\n        q, k, v = blk.qkv(blk.norm1(x)).view(B, T, 3, blk.n_heads, d // blk.n_heads).permute(2, 0, 3, 1, 4)\n        q, k = rope(q, self.cos[:T], self.sin[:T]), rope(k, self.cos[:T], self.sin[:T])\n        att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(q.shape[-1]))\n        att = att.masked_fill(self.mask[:T, :T], float(\"-inf\"))\n        y = torch.softmax(att, dim=-1) @ v\n        return blk.proj(y.transpose(1, 2).reshape(B, T, d))\n\n    @staticmethod\n    def experts(blk, h, w):\n        \"\"\"sum_e w[:, e] * expert_e(h). On a GPU every expert runs on every row (zero weights add nothing); on a CPU\n        each expert runs only on the rows that give it a nonzero weight. The two agree to float rounding.\"\"\"\n        if h.is_cuda:\n            E, d, hid = blk.w_gate.shape\n            a = h @ blk.w_gate.permute(1, 0, 2).reshape(d, E * hid)\n            b = h @ blk.w_up.permute(1, 0, 2).reshape(d, E * hid)\n            z = (F.silu(a) * b).view(-1, E, hid) * w.unsqueeze(-1)\n            return z.view(-1, E * hid) @ blk.w_down.reshape(E * hid, d)\n        out = torch.zeros_like(h)\n        nz = w != 0\n        for e in range(w.shape[1]):\n            rows = nz[:, e].nonzero().squeeze(1)\n            if rows.numel() == 0:\n                continue\n            x = h.index_select(0, rows)\n            y = (F.silu(x @ blk.w_gate[e]) * (x @ blk.w_up[e])) @ blk.w_down[e]\n            out.index_add_(0, rows, y * w.index_select(0, rows)[:, e:e + 1])\n        return out\n\n    def forward(self, ids, route=None, aux=None):\n        \"\"\"ids (B, T) int64. route(layer, logits) -> weights, numpy (n, E) both ways; None = trained routing.\n        aux: a list to append (router logits, weights) per layer to, for the training losses.\"\"\"\n        x = self.emb(ids)\n        B, T, d = x.shape\n        for li, blk in enumerate(self.blocks):\n            x = x + self.attend(blk, x)\n            h = blk.norm2(x).reshape(B * T, d)\n            logits = blk.router(h)\n            if route is None:\n                w = self.trained_weights(logits)\n            else:\n                w = torch.as_tensor(np.asarray(route(li, logits.detach().float().cpu().numpy()), dtype=np.float32),\n                                    device=h.device)\n            if aux is not None:\n                aux.append((logits, w))\n            x = x + self.experts(blk, h, w.to(h.dtype)).view(B, T, d)\n        return self.head(self.norm(x))\n\n\ndef build(cfg, seed):\n    g = torch.random.fork_rng()\n    with g:\n        torch.manual_seed(seed)\n        m = MoELM(**cfg)\n    return m\n\n\ndef train_model(cfg, data, seed, steps, batch, seq, lr=3e-3, alpha=0.01, zcoef=1e-3, log=None, device=\"cpu\"):\n    \"\"\"data: uint8 numpy array of bytes. Deterministic given seed (on one host).\"\"\"\n    with torch.random.fork_rng():\n        torch.manual_seed(seed)\n        m = MoELM(**cfg).to(device)\n        rng = np.random.default_rng(seed + 1)\n        opt = torch.optim.AdamW(m.parameters(), lr=lr, betas=(0.9, 0.95), weight_decay=0.0)\n        E = cfg[\"n_experts\"]\n        warm = max(1, steps // 10)\n        for step in range(steps):\n            frac = min(1.0, (step + 1) / warm) * (0.5 * (1 + math.cos(math.pi * step / steps)) * 0.9 + 0.1)\n            for gr in opt.param_groups:\n                gr[\"lr\"] = lr * frac\n            starts = rng.integers(0, len(data) - seq - 1, size=batch)\n            xy = torch.from_numpy(np.stack([data[s:s + seq + 1] for s in starts]).astype(np.int64)).to(device)\n            aux = []\n            logits = m(xy[:, :-1], aux=aux)\n            loss = F.cross_entropy(logits.reshape(-1, logits.shape[-1]), xy[:, 1:].reshape(-1))\n            bal = 0.0\n            for lg, w in aux:\n                p = torch.softmax(lg, -1)\n                f = (w > 0).float().mean(0) * E / cfg[\"k\"]\n                bal = bal + alpha * (f * p.mean(0)).sum() + zcoef * torch.logsumexp(lg, -1).pow(2).mean()\n            opt.zero_grad(set_to_none=True)\n            (loss + bal / len(aux)).backward()\n            torch.nn.utils.clip_grad_norm_(m.parameters(), 1.0)\n            opt.step()\n            if log is not None and (step % 50 == 0 or step == steps - 1):\n                log.append((step, float(loss)))\n    m.eval()\n    return m\n\n\ndef kl_bits(full_logits, served_logits):\n    \"\"\"Per-position KL(full || served) in bits, float64.\"\"\"\n    lp = torch.log_softmax(full_logits.double(), -1)\n    lq = torch.log_softmax(served_logits.double(), -1)\n    return ((lp.exp() * (lp - lq)).sum(-1) / math.log(2.0))\nclass _Toy(MoELM):\n    budget = 2.0\n    device = torch.device('cpu')\ndef _kl(m, c, fn):\n    with torch.no_grad():\n        return float(kl_bits(m(c), m(c, route=fn)).mean())\ndef _naive(layer, lg):\n    p = torch.softmax(torch.as_tensor(lg), -1)\n    v, i = p.topk(2, -1)\n    return torch.zeros_like(p).scatter(-1, i, v).numpy()\ntry:\n    _w\nexcept NameError:\n    torch.manual_seed(0)\n    _m = _Toy(256, 32, 2, 4, 8, 4, 32, 64).eval()\n    for _p in _m.parameters():\n        _p.requires_grad_(False)\n    _c = torch.randint(0, 256, (8, 64))\n    _pol = plan(_m, _c, 2.0)\n    _lg = np.random.default_rng(1).normal(size=(300, 8)).astype(np.float32)\n    _w = route(_pol, 0, _lg)\n    if isinstance(_w, torch.Tensor):\n        _w = _w.detach().cpu().numpy()\n    _w = np.asarray(_w, dtype=np.float32)\nprint(bool(_kl(_m, _c, lambda l, z: route(_pol, l, z)) < 0.95 * _kl(_m, _c, _naive)))","expected_output":"True"}],"lower_is_better":true,"approved_user_libraries":["numpy","torch"],"data_info":"TinyStories (validation split) as raw UTF-8 bytes, read by the grader. The grader trains each model on the first 8,000,000 bytes (300 steps of 32 random windows of 128 bytes). plan() receives 64 consecutive windows of 128 bytes from a later part of the file as calibration text; the scored text is 64 more windows of 128 bytes from another part, different for every model and for Run and Submit. Your code never sees the scored bytes: route() gets only one layer's router logits for 2,048 tokens at a time, rows shuffled.","time_limits":{"test":180,"dev":150},"gpu":true,"description":"## Best Serving Top-k\n\nA mixture-of-experts model was trained with every token using its top $k$ experts in every layer. You must serve it with **half the expert compute**, without retraining it, and stay as close as you can to what the full model says.\n\nThe grader trains small mixture-of-experts language models, then hands you each one. You write the serving policy: for every token in every layer, which experts run and with what weights. Your served model is compared with the full model, byte by byte, on text you never see. The smaller the gap, the better.\n\nAny policy is allowed: one $k$ for every layer or a different one per layer, a different number of experts per token, any rule for the weights. Only the score and the budget count.\n\n### The models\n\nEach model is a byte-level decoder (vocabulary of 256 byte values) trained by the grader on TinyStories text. Every block is pre-norm: RMSNorm, causal self-attention with rotary positions, then RMSNorm and a mixture of SwiGLU experts. The router of a block is a linear map from the hidden state $h$ to one logit per expert, with no bias. During training a token's weights were\n\n$$\np = \\mathrm{softmax}(\\text{logits}), \\qquad w_e = \\frac{p_e}{\\sum_{j \\in \\mathrm{top}k} p_j} \\ \\text{for the top } k \\text{ experts}, \\qquad w_e = 0 \\ \\text{otherwise},\n$$\n\nand the block adds $\\sum_e w_e \\, \\mathrm{expert}_e(h)$ to the residual stream. Training used a load-balancing loss and a router z-loss, 300 steps of 32 windows of 128 bytes.\n\n- **Run** scores 2 models: 16 experts with top-4 routing in 4 layers of width 64, and 32 narrower experts with top-8.\n- **Submit** scores 3 models: one built like Run's first (another seed) and two designs Run never shows, with a different number of experts, trained top-$k$, width and depth. Read them from the model object; do not hard-code them.\n\n### What you write\n\n```python\ndef plan(model, calib, budget_seconds):\n    ...\n    return policy                     # anything you like\n\ndef route(policy, layer, logits):\n    ...\n    return weights                    # (n, E) numpy array\n```\n\n`plan` runs once per model. You get:\n\n- `model`: the trained model as a PyTorch module on the GPU, frozen. `model.n_layers`, `model.n_experts`, `model.trained_k`, and `model.budget`, the expert evaluations you may spend per token per layer on average (0.5 times the trained $k$). `model(ids, route=fn)` runs it on a `(B, T)` int64 tensor of byte ids and returns next-byte logits `(B, T, 256)`; `fn(layer, logits)` is called once per layer and returns weights exactly like `route` below, and `route=None` uses the trained routing. The weights live in `model.blocks[i]` (`router`, `w_gate`, `w_up`, `w_down`, `norm1`, `norm2`, `qkv`, `proj`), plus `model.emb`, `model.norm` and `model.head`; `model.trained_weights(logits)`, `model.attend(blk, x)` and `model.experts(blk, h, w)` are the torch pieces the forward pass is built from, if you want to write your own.\n- `calib`: a `(64, 128)` int64 tensor on the same device, 64 windows of text that is never scored.\n- `budget_seconds`: how long `plan` may run (5 s).\n\n`route` is called during scoring, once per layer per forward pass:\n\n- `logits`: float32 numpy array `(n, E)`, the router logits of `n` tokens at block `layer` of the served model. The rows come in a random order that changes on every call, so a row is a token you know only by its logits.\n- Return float `weights` of shape `(n, E)`, row for row: zero or positive and finite. A nonzero weight runs that expert for that token, and the block adds $\\sum_e w_e \\, \\mathrm{expert}_e(h)$, so the size of the weights matters as well as which ones are nonzero. A torch tensor is accepted too.\n\n### The budget\n\nThe grader counts every nonzero weight as one expert evaluation.\n\n- In each forward pass the grader scores 2,048 tokens (16 windows of 128 bytes), and the evaluations over all layers of that pass may not exceed **0.5 x trained $k$ x layers x tokens**: half of what the trained routing spends. Within that, you may give one layer more than another and one token more than another.\n- No token may use more than the trained $k$ experts in one layer.\n- `plan` gets 5 seconds per model. All `route` calls of one model share 1 second in total, including handing each call over (a few milliseconds); a 4-layer model gets 16 calls.\n- The grader stops a `plan` or `route` that runs 15% past its budget. Importing and loading your file are free, but a file that takes over 30 s to load is stopped.\n\nA pass over the expert budget, too many experts for one token, a negative, NaN or infinite weight, a wrong shape or a missed time budget stops the run, and it is **not scored**.\n\n### How it is graded\n\nFor every scored byte position the grader compares the full model's next-byte distribution $P$ with your served model's $Q$:\n\n$$\n\\mathrm{KL}(P \\,\\|\\, Q) = \\sum_{b=0}^{255} P(b) \\log_2 \\frac{P(b)}{Q(b)} \\ \\text{bits},\n$$\n\naveraged over 64 windows of 128 bytes (8,192 positions) per model. In the same run it also serves the model the way an engine does when you only lower its top-$k$ setting: each token keeps its top $k/2$ experts and divides their probabilities by their own sum. Your score is your KL as a **percentage of that default's KL**, averaged over the models:\n\n$$\n\\text{score} = \\frac{100}{M} \\sum_{m=1}^{M} \\frac{\\mathrm{KL}_m(\\text{yours})}{\\mathrm{KL}_m(\\text{default})}.\n$$\n\nThe default scores exactly 100. **Lower is better**, and the lab is passed at **90 or below**. The report also prints each model's KL in millibits per byte, the default's KL, the experts you used per token in each layer, and your `plan` and `route` times.\n\nRun and Submit use different models and different text. The grader trains the models from fixed seeds, and training is repeatable, so the same code gets the same score up to its own randomness and timing.\n\n### Rules\n\n- Libraries: numpy and torch, plus small standard-library helpers (math, random, time, collections, itertools, copy, heapq, bisect, statistics, warnings, typing, enum, abc).\n- The harness owns the data: reading or writing files, dataset loaders, network access and serialization (`torch.save`, `torch.load`, `np.load`, `pickle`) are refused.\n- Write classes the ordinary way: `self.x = ...` inside a method is fine. Outside a method, assigning to an attribute is refused, so keep other state in local variables, lists or dicts.\n- Dynamic access is refused (`getattr`, `setattr`, `vars`, `globals`, `exec`, `compile`, names starting with two underscores other than the usual methods such as `__init__`), and so are `os`, `sys`, `def f(**kwargs)`, `dict(name=value)` and text or byte decoders (`ord`, `chr`, `tobytes`, `encode`, `decode`).\n- A file can carry at most 12,000 characters of code (comments and docstrings do not count), 300 numbers, 400 characters of strings and 200 names you define.\n","tags":["mixture-of-experts","moe","serving","top-k","routing","renormalization","kl-divergence","inference","competitive"],"id":"2d577d54-6bb4-4707-bcb6-0b4955f14de5","img_type":"pytorch","dataset_id":"tinystories","evaluation_metric":"relative_kl","difficulty":"hard","min_eval_metric":90.0,"category":"Mixture of Experts","title":"Best Serving Top-k","dataset":"TinyStories (raw bytes), small MoE language models trained by the grader","time_limits_seconds":{"dev":150,"test":180}},{"description":"In this open-ended challenge, you will implement your own optimizer in PyTorch. The optimizer can be inspired by existing ones (SGD, RMSProp, Adam, etc.) or be completely new — your design choice.\n\nYou must subclass `torch.optim.Optimizer` and implement the `step()` method. Your optimizer will be tested on a small CNN trained on the MNIST dataset. The goal is to achieve good accuracy (≥80%) within a few epochs.\n\nYou are free to use any update rule, momentum terms, normalization tricks, or bias corrections you like. Creativity is encouraged — as long as the optimizer works and converges on MNIST.","constraints":["Subclass torch.optim.Optimizer.","Implement your own `step()` method that updates parameters.","Dense gradients only (no sparse support required).","The optimizer must be stable enough to train a small CNN on MNIST.","Creativity is encouraged: implement any rule you believe can converge."],"id":"3","test_cases":[{"test":"import torch, torch.nn as nn\nlin = nn.Linear(4,3)\nopt = MyOptimizer(lin.parameters(), lr=1e-2)\nx = torch.randn(8,4); y = torch.randint(0,3,(8,))\nloss = nn.CrossEntropyLoss()(lin(x), y)\nloss.backward();\nwith torch.no_grad():\n    w_before = lin.weight.clone()\nopt.step()\nchanged = (lin.weight - w_before).abs().sum().item()\nprint(changed > 0)\n","expected_output":"True"},{"test":"import torch\nimport torch.nn as nn\nfrom copy import deepcopy\n\ntorch.manual_seed(0)\n\n# --- Model & loss ---\nlin = nn.Linear(4, 3, bias=True)\ncriterion = nn.CrossEntropyLoss()\n\n# Save identical starting weights for both cases\ninit_state = deepcopy(lin.state_dict())\n\ndef param_l1_delta(model, before_params):\n    \"\"\"Sum of L1 deltas across ALL params (weights and biases).\"\"\"\n    delta = 0.0\n    for p, b in zip(model.parameters(), before_params):\n        delta += (p.detach() - b).abs().sum().item()\n    return delta\n\ndef snapshot_params(model):\n    return [p.detach().clone() for p in model.parameters()]\n\ndef restore_init(model, state):\n    model.load_state_dict(deepcopy(state))\n\n# --- Case A: Very wrong & large-magnitude inputs (expect LARGE step) ---\nrestore_init(lin, init_state)\nopt_bad = MyOptimizer(lin.parameters(), lr=1e-2)\n\n# Large-norm inputs amplify gradients through the linear layer\nx_bad = torch.randn(32, 4) * 10.0\nwith torch.no_grad():\n    logits_bad = lin(x_bad)\n# Force WRONG targets: shift the argmax by 1 mod 3\ny_bad = (logits_bad.argmax(dim=1) + 1) % 3\n\nopt_bad.zero_grad(set_to_none=True)\nloss_bad = criterion(lin(x_bad), y_bad)\nloss_bad.backward()\n\nbefore_bad = snapshot_params(lin)\nopt_bad.step()\ndiff_bad = param_l1_delta(lin, before_bad)\n\n# --- Case B: Close/correct & small-magnitude inputs (expect SMALLER step) ---\nrestore_init(lin, init_state)\nopt_good = MyOptimizer(lin.parameters(), lr=1e-2)\n\n# Small-norm inputs reduce gradient magnitudes\nx_good = torch.randn(32, 4) * 0.01\nwith torch.no_grad():\n    logits_good = lin(x_good)\n# Choose targets that match current predictions (closer to correct)\ny_good = logits_good.argmax(dim=1)\n\nopt_good.zero_grad(set_to_none=True)\nloss_good = criterion(lin(x_good), y_good)\nloss_good.backward()\n\nbefore_good = snapshot_params(lin)\nopt_good.step()\ndiff_good = param_l1_delta(lin, before_good)\n\nprint(diff_good < diff_bad)\n","expected_output":"True"}],"approved_user_libraries":["torch","numpy"],"difficulty":"medium","evaluation_metric":"Accuracy","time_limits":{"test":"300 seconds","dev":"120 seconds"},"schema":"practical_question_v1","min_eval_metric":0.8,"example":{"input":{"y_sample":7,"X_sample":[{"0":[0.0,0.05,0.1,0.0],"3":[0.0,0.0,0.0,0.0],"1":[0.0,0.12,0.25,0.02],"2":[0.01,0.2,0.6,0.15]}]},"output":{"note":"Example of a small crop from a (1,28,28) MNIST image with label 7. Your optimizer should work on this dataset when training a CNN classifier."}},"category":"Optimizers","title":"MNIST: Design Your Own Pytorch Optimizer","dataset":"MNIST","memory_limit":"2 GB","createdAt":"2026-05-13T21:01:42.922000+00:00","time_limits_seconds":{"dev":120,"test":300},"type":"epoch","lower_is_better":false,"gpu":false},{"description":"Implement a custom transformation class `MyTransform` to modify each input tinygrad image tensor used during training. The harness will iterate over MNIST samples one at a time, call your transform on each image, and stack the results into a batch.\n\nTinygrad has no PyTorch-style `DataLoader` class - the framework prefers explicit batching with `Tensor.randint` over `X_train`. This problem teaches the same per-sample transform lesson using a plain Python loop the harness provides.","constraints":["Implement ONLY `MyTransform`.","You MUST return a tinygrad Tensor of the SAME shape and dtype.","The transform must NOT be the identity function.","It must be deterministic under a fixed random seed set via Tensor.manual_seed."],"id":"30","img_type":"tinygrad","test_cases":[{"test":"from tinygrad import Tensor\nx = Tensor.rand(1, 28, 28)\nT = MyTransform()\ny = T(x)\nprint(y.shape == x.shape)","expected_output":"True"}],"approved_user_libraries":["tinygrad","numpy"],"difficulty":"medium","evaluation_metric":"Accuracy","time_limits":{"test":"240 seconds","dev":"90 seconds"},"data_info":"MNIST 28x28 grayscale digits (10 classes). Inputs scaled to [0,1] and shaped (N,1,28,28). Loaded from the Keras MNIST .npz dataset and wrapped as tinygrad Tensors.","schema":"practical_question_v1","min_eval_metric":0.8,"example":{"input":{"y_sample":7,"x_sample":"tinygrad Tensor shape (1, 28, 28), values in [0,1]"},"output":{"note":"Returns a tinygrad Tensor of shape (1, 28, 28) and the same dtype, with statistics measurably different from the input."}},"category":"Data Pipelines","title":"MNIST: Tinygrad Data Transform","model_specs":"Small CNN built as a plain tinygrad class: two Conv2d->ReLU->MaxPool2d stages, then Linear->ReLU->Linear(10). Batch size 128, Adam lr=1e-3, 2 epochs.","memory_limit":"2 GB","dataset":"MNIST","createdAt":"2026-05-13T21:01:43.050000+00:00","time_limits_seconds":{"dev":90,"test":240},"type":"epoch","lower_is_better":false,"gpu":false},{"description":"Implement a function `build_model()` that returns a tinygrad model (any plain Python class with `__call__`) to classify MNIST digits. You may use ANY tinygrad ops, but if your model has more than **2048 trainable parameters**, your reported accuracy will be **0**. Keep it tiny and clever (e.g., global pooling, grouped/depthwise convs, shared weights, etc.).\n\nTinygrad does **not** use an `nn.Module` base class - your model is just a regular Python class with `__init__` storing submodules as attributes and a `__call__` method that runs the forward pass. Parameters are discovered by walking the class with `tinygrad.nn.state.get_parameters`.","constraints":["Implement ONLY `build_model()`; return any callable Python object that has a `__call__(x) -> Tensor` method.","All trainable Tensor attributes (anything found by `get_parameters`) count toward the 2048 limit.","If param_count > 2048, the grader sets accuracy to 0.","Use only tinygrad APIs (no torch)."],"id":"31","img_type":"tinygrad","test_cases":[{"test":"from tinygrad import Tensor\nm = build_model()\nprint(callable(m))","expected_output":"True"},{"test":"from tinygrad.nn.state import get_parameters\nm = build_model()\nparams = sum(p.numel() for p in get_parameters(m))\nprint(params <= 2048)","expected_output":"True"}],"approved_user_libraries":["tinygrad","numpy"],"difficulty":"medium","evaluation_metric":"Accuracy","time_limits":{"test":"240 seconds","dev":"90 seconds"},"data_info":"MNIST 28x28 grayscale digits (10 classes). Inputs scaled to [0,1] and shaped (N,1,28,28). Loaded from the Keras MNIST .npz dataset and wrapped as tinygrad Tensors.","schema":"practical_question_v1","min_eval_metric":0.85,"example":{"input":{"X":"tinygrad Tensor shape (N, 1, 28, 28), values in [0, 1]","y":"5"},"output":{"note":"If param_count > 2048 -> accuracy is set to 0 in the final JSON.","param_count":"<= 2048"}},"category":"Model Architecture","title":"MNIST: Design-Your-Own Tiny Tinygrad Model","model_specs":"You choose the architecture. Training: Adam lr=0.01, batch size=128, epochs=10. Hard cap: 2048 trainable parameters.","memory_limit":"2 GB","dataset":"MNIST","createdAt":"2026-05-13T21:01:43.176000+00:00","time_limits_seconds":{"dev":90,"test":240},"type":"epoch","lower_is_better":false,"gpu":false},{"created_at":"2026-11-01T00:10:49.005000+00:00","type":"general","constraints":["embed <= 40 s per map on Run and <= 90 s per map on Submit","embed returns a finite array of shape (len(X), 2) with at least 90% of its points distinct","numpy, scipy, scikit-learn and torch on CPU; the harness owns all data access","source capped at 24000 characters, 400 numeric literals, 200 characters per string literal"],"test_cases":[{"test":"import numpy as np\n_r = np.random.default_rng(0)\n_t = 1.5 * np.pi * (1 + 2 * _r.random(400))\n_X = np.column_stack((_t * np.cos(_t), 21 * _r.random(400), _t * np.sin(_t)))\n_X = (_X - _X.min(0)) / (_X.max(0) - _X.min(0))\n_Z = np.asarray(embed(_X.copy()), dtype=float)\nprint(_Z.shape)","expected_output":"(400, 2)"},{"test":"import numpy as np\n_r = np.random.default_rng(0)\n_t = 1.5 * np.pi * (1 + 2 * _r.random(400))\n_X = np.column_stack((_t * np.cos(_t), 21 * _r.random(400), _t * np.sin(_t)))\n_X = (_X - _X.min(0)) / (_X.max(0) - _X.min(0))\n_Z = np.asarray(embed(_X.copy()), dtype=float)\nprint(bool(np.isfinite(_Z).all()) and bool(_Z.std() > 0))","expected_output":"True"},{"test":"import numpy as np\n_r = np.random.default_rng(0)\n_t = 1.5 * np.pi * (1 + 2 * _r.random(400))\n_X = np.column_stack((_t * np.cos(_t), 21 * _r.random(400), _t * np.sin(_t)))\n_X = (_X - _X.min(0)) / (_X.max(0) - _X.min(0))\n_Z = np.asarray(embed(_X.copy()), dtype=float)\n_D = ((_X[:, None] - _X[None]) ** 2).sum(-1)\nnp.fill_diagonal(_D, np.inf)\n_R = np.argsort(np.argsort(_D, axis=1), axis=1) + 1\n_E = ((_Z[:, None] - _Z[None]) ** 2).sum(-1)\nnp.fill_diagonal(_E, np.inf)\n_N, _k = 400, 10\n_nn = np.argsort(_E, axis=1)[:, :_k]\n_pen = np.maximum(_R[np.arange(_N)[:, None], _nn] - _k, 0).sum()\n_T = 1 - 2 * _pen / (_N * _k * (2 * _N - 3 * _k - 1))\nprint(bool(_T > 0.97))","expected_output":"True"}],"lower_is_better":false,"approved_user_libraries":["numpy","scipy","sklearn","torch"],"data_info":"Images only, one flattened image per row, pixel values scaled to [0, 1], rows in random order, no labels passed to your code.\n\nRun (validation), 40 s per embed call:\n1. sklearn-digits: all 1,797 images, 8x8, D = 64\n2. fashion-mnist test split: 2,000 images, 28x28, D = 784\n3. cifar10 test split: 2,000 images, 32x32 RGB, D = 3,072\n\nSubmit (test), 90 s per embed call: three hidden maps of 5,000 images each, drawn from image collections in the dataset registry, none of them images used in Run, and one collection that Run does not use. D is between 784 and 3,072.\n\nNeighbours in X are measured by Euclidean distance on X exactly as it is passed to embed.","time_limits":{"test":420,"dev":240},"gpu":false,"description":"## Most Faithful 2-D Map\n\nYou get a pile of images and no labels. Draw each image as a single point on a 2-D map, so that points that land close together on the map really are close in the original pixel space, and keep that true whether someone looks at the nearest handful of points or at a whole neighbourhood. The most faithful map wins.\n\n### What you write\n\n```python\ndef embed(X):\n    ...\n    return Z                        # np.ndarray, shape (len(X), 2)\n```\n\n- `X`: float64 array of shape `(N, D)`, one flattened image per row, pixel values in `[0, 1]`, in random order. There are no labels and no metadata.\n- `Z`: one 2-D point per row of `X`, in the same order. Only the distances between your points matter, so scale, rotation and translation are yours to choose.\n\n### How it is graded\n\nThe grader measures **trustworthiness**. Take a neighbourhood size $k$. Let $r(i, j)$ be the rank of point $j$ among the neighbours of point $i$ in `X` by Euclidean distance (nearest is rank 1), and let $U_k(i)$ be the points among the $k$ nearest to $i$ on your map that are not among its $k$ nearest in `X`. Those are the false neighbours your map invents, and each one costs more the farther away it really is:\n\n$$\nT(k) = 1 - \\frac{2}{N k (2N - 3k - 1)} \\sum_{i=1}^{N} \\sum_{j \\in U_k(i)} \\left( r(i, j) - k \\right)\n$$\n\n$T(k) = 1$ means no false neighbours at all, and a map with no relation to the data scores about $0.5$.\n\nThe score of one map is the mean of T(10), T(30) and T(100). Your score is the mean over all maps. **Higher is better**, and the lab is passed at **0.90 or above**. The grader prints each $T(k)$ for each map, plus the 10-nearest-neighbour class accuracy of your map as a secondary number. That accuracy uses labels your code never sees and does not count toward the score.\n\n- **Run**: three maps of at most 2,000 images each (listed under Data), with 40 s for each `embed` call.\n- **Submit**: three hidden maps of 5,000 images each, drawn from image collections in the dataset registry, with 90 s for each `embed` call. The images differ from the ones in Run, and one collection does not appear in Run at all.\n\n### Budgets and rules\n\n- The budget is wall-clock time for one `embed` call, including any conversion of what you return into an array. Machines vary, so read the clock in your own code and leave yourself a margin: a map delivered late scores zero.\n- CPU only. Libraries: numpy, scipy, scikit-learn and torch.\n- The harness owns the data. Code that imports `dml_data`, `os`, `sys`, file or serialisation modules or dataset loaders, reads files, or names a dataset in a string is refused.\n- Your source is capped at 24,000 characters, 400 numeric literals and 200 characters per string literal.\n- A wrong shape, a NaN or infinity, a collapsed map (fewer than 90% of its points distinct), an exception, or a broken budget or cap sets the score to 0 and fails the run.\n","tags":["manifold-learning","dimensionality-reduction","t-sne","trustworthiness","competitive","pml-book"],"id":"3181f54f-1354-4fcc-8bef-d7591289e3d1","dataset_id":"fashion-mnist","img_type":"full","difficulty":"hard","evaluation_metric":"trustworthiness","min_eval_metric":0.9,"category":"Machine Learning","dataset":"Fashion-MNIST and other registry image sets","title":"Most Faithful 2-D Map","time_limits_seconds":{"dev":240,"test":420}},{"description":"In this open-ended challenge, you will implement your own optimizer in tinygrad. The optimizer can be inspired by existing ones (SGD, RMSProp, Adam, etc.) or be completely new - your design choice.\n\nYou must subclass `tinygrad.nn.optim.Optimizer` and implement the `schedule_step()` method (the base class's `step()` realizes its returned tensors for you). Your optimizer will be tested on a small CNN trained on MNIST. The goal is to achieve good accuracy (>= 80%) within a few epochs.\n\nYou are free to use any update rule, momentum terms, normalization tricks, or bias corrections you like. Creativity is encouraged - as long as the optimizer works and converges on MNIST.","constraints":["Subclass `tinygrad.nn.optim.Optimizer`.","Implement `schedule_step()` returning the list of Tensors the base class will realize.","Dense gradients only.","The optimizer must be stable enough to train a small CNN on MNIST.","Creativity is encouraged: implement any rule you believe can converge."],"id":"32","img_type":"tinygrad","test_cases":[{"test":"from tinygrad import Tensor, nn\nfrom tinygrad.nn.state import get_parameters\nlin = nn.Linear(4, 3)\nopt = MyOptimizer(get_parameters(lin), lr=1e-2)\nx = Tensor.randn(8, 4)\ny = Tensor.randint(8, high=3)\nTensor.training = True\nw_before = lin.weight.numpy().copy()\nloss = lin(x).sparse_categorical_crossentropy(y)\nloss.backward()\nopt.step()\nimport numpy as np\nchanged = float(np.abs(lin.weight.numpy() - w_before).sum())\nprint(changed > 0)\n","expected_output":"True"},{"test":"from tinygrad import Tensor, nn\nfrom tinygrad.nn.state import get_parameters\nimport numpy as np\n\nTensor.manual_seed(0)\nTensor.training = True\n\n# Same starting weights for both cases.\nlin_init = nn.Linear(4, 3, bias=True)\ninit_w = lin_init.weight.numpy().copy()\ninit_b = lin_init.bias.numpy().copy()\n\ndef param_l1_delta(params, before):\n    return sum(np.abs(p.numpy() - b).sum() for p, b in zip(params, before))\n\ndef snapshot(params):\n    return [p.numpy().copy() for p in params]\n\ndef restore(model, w, b):\n    model.weight = Tensor(w, requires_grad=True)\n    model.bias = Tensor(b, requires_grad=True)\n\n# --- Case A: large-magnitude inputs, wrong labels (expect LARGE step) ---\nlin = nn.Linear(4, 3, bias=True)\nrestore(lin, init_w, init_b)\nopt_bad = MyOptimizer(get_parameters(lin), lr=1e-2)\nx_bad = Tensor.randn(32, 4) * 10.0\nTensor.training = False\nlogits_bad = lin(x_bad)\ny_bad_np = (logits_bad.argmax(axis=1).numpy() + 1) % 3\ny_bad = Tensor(y_bad_np.astype('int64'))\nTensor.training = True\nopt_bad.zero_grad()\nloss_bad = lin(x_bad).sparse_categorical_crossentropy(y_bad)\nloss_bad.backward()\nbefore_bad = snapshot(get_parameters(lin))\nopt_bad.step()\ndiff_bad = param_l1_delta(get_parameters(lin), before_bad)\n\n# --- Case B: small-magnitude inputs, near-correct labels (expect SMALL step) ---\nlin = nn.Linear(4, 3, bias=True)\nrestore(lin, init_w, init_b)\nopt_good = MyOptimizer(get_parameters(lin), lr=1e-2)\nx_good = Tensor.randn(32, 4) * 0.01\nTensor.training = False\nlogits_good = lin(x_good)\ny_good_np = logits_good.argmax(axis=1).numpy()\ny_good = Tensor(y_good_np.astype('int64'))\nTensor.training = True\nopt_good.zero_grad()\nloss_good = lin(x_good).sparse_categorical_crossentropy(y_good)\nloss_good.backward()\nbefore_good = snapshot(get_parameters(lin))\nopt_good.step()\ndiff_good = param_l1_delta(get_parameters(lin), before_good)\n\nprint(diff_good < diff_bad)\n","expected_output":"True"}],"approved_user_libraries":["tinygrad","numpy"],"difficulty":"medium","evaluation_metric":"Accuracy","time_limits":{"test":"300 seconds","dev":"120 seconds"},"schema":"practical_question_v1","min_eval_metric":0.8,"example":{"input":{"y_sample":7,"X_sample":[{"0":[0.0,0.05,0.1,0.0],"3":[0.0,0.0,0.0,0.0],"1":[0.0,0.12,0.25,0.02],"2":[0.01,0.2,0.6,0.15]}]},"output":{"note":"Example of a small crop from a (1,28,28) MNIST image with label 7. Your optimizer should work on this dataset when training a tinygrad CNN classifier."}},"category":"Optimizers","title":"MNIST: Design Your Own Tinygrad Optimizer","dataset":"MNIST","memory_limit":"2 GB","createdAt":"2026-05-13T21:01:43.320000+00:00","time_limits_seconds":{"dev":120,"test":300},"type":"epoch","lower_is_better":false,"gpu":false},{"description":"Implement a function `train_step(model, x_batch, y_batch, lr)` that performs ONE step of gradient descent training. You must manually: (1) compute the forward pass, (2) compute the loss, (3) compute gradients using backpropagation, and (4) update the model parameters. Do NOT use `tinygrad.nn.optim` - update weights yourself using the gradients. This teaches how gradient descent actually works in tinygrad.\n\nTinygrad's lazy evaluation means assignments to parameters do not run until you ask for them to be realized. You'll need to call `Tensor.realize(*params)` (or rely on a subsequent `.item()` / `.numpy()` call) to actually materialize the updates.","constraints":["Must compute the forward pass through the model.","Must compute sparse categorical cross-entropy loss.","Must call `loss.backward()` to compute gradients.","Must clear gradients before the backward pass (set `p.grad = None`).","Must update parameters using `p.assign(...)` and realize the updates.","Must return the loss value as a Python float.","Do NOT use `tinygrad.nn.optim` (no SGD, Adam, AdamW, LARS, LAMB, Muon)."],"id":"33","img_type":"tinygrad","test_cases":[{"test":"from tinygrad import Tensor, nn\nmodel = nn.Linear(10, 2)\nx = Tensor.randn(4, 10)\ny = Tensor([0, 1, 0, 1])\nloss = train_step(model, x, y, lr=0.1)\nprint(isinstance(loss, float) and loss > 0)\n","expected_output":"True"},{"test":"from tinygrad import Tensor, nn\nclass TinyMLP:\n    def __init__(self):\n        self.l1 = nn.Linear(10, 5)\n        self.l2 = nn.Linear(5, 2)\n    def __call__(self, x):\n        return self.l2(self.l1(x).relu())\nmodel = TinyMLP()\nx = Tensor.randn(4, 10)\ny = Tensor([0, 1, 0, 1])\nloss = train_step(model, x, y, lr=0.1)\nprint(isinstance(loss, float))\n","expected_output":"True"},{"test":"from tinygrad import Tensor, nn\nfrom tinygrad import nn as _nn\n\n# Detect if tinygrad.nn.optim is used.\n_optim_used = [False]\n_originals = {}\nfor _name in ['SGD', 'Adam', 'AdamW', 'LARS', 'LAMB', 'Muon']:\n    if hasattr(_nn.optim, _name):\n        _originals[_name] = getattr(_nn.optim, _name)\n        def _make_fake(orig, name):\n            def _fake(*a, **kw):\n                _optim_used[0] = True\n                return orig(*a, **kw)\n            return _fake\n        setattr(_nn.optim, _name, _make_fake(_originals[_name], _name))\n\nmodel = nn.Linear(10, 2)\nx = Tensor.randn(4, 10)\ny = Tensor([0, 1, 0, 1])\ntrain_step(model, x, y, lr=0.1)\n\nfor _name, _orig in _originals.items():\n    setattr(_nn.optim, _name, _orig)\nprint(not _optim_used[0])\n","expected_output":"True"}],"approved_user_libraries":["tinygrad","numpy"],"difficulty":"medium","evaluation_metric":"Accuracy","data_info":"MNIST 28x28 grayscale digits flattened to 784-dim vectors, scaled to [0,1]. Trained with a 3-layer MLP (784 -> 128 -> 128 -> 10) defined as a plain tinygrad class with `__call__`.","time_limits":{"test":"120 seconds","dev":"60 seconds"},"schema":"practical_question_v1","min_eval_metric":0.85,"example":{"input":{"x_batch":"tinygrad Tensor of shape (batch_size, features)","model":"plain tinygrad class with __call__","y_batch":"tinygrad Tensor of shape (batch_size,) with class labels (int64)","lr":"float, learning rate (e.g. 0.1)"},"output":{"loss":"float, the loss value for this batch"}},"category":"Tinygrad Fundamentals","title":"Tinygrad: Implement Your Own Gradient Descent Training Step","dataset":"MNIST","memory_limit":"2 GB","createdAt":"2026-05-13T21:01:43.531000+00:00","time_limits_seconds":{"dev":60,"test":120},"type":"epoch","lower_is_better":false,"gpu":false},{"description":"Implement a function `train_model(model, X_train, y_train, X_val, y_val, epochs, batch_size, lr)` that trains a tinygrad model. Use `tinygrad.nn.optim` for optimization and implement proper batching, shuffling, and validation. Return a list of dictionaries containing training metrics for each epoch.","constraints":["Must use `tinygrad.nn.optim` (e.g. `SGD`, `Adam`, `AdamW`) for optimization.","Must implement mini-batch training with the specified batch_size.","Must shuffle training data each epoch.","Must compute validation accuracy and loss after each epoch.","Must return a list of dicts with keys: 'epoch', 'train_loss', 'val_loss', 'val_accuracy'.","Must use `sparse_categorical_crossentropy` for the loss."],"id":"34","img_type":"tinygrad","test_cases":[{"test":"from tinygrad import Tensor, nn\nmodel = nn.Linear(10, 2)\nX_train = Tensor.randn(100, 10)\ny_train = Tensor.randint(100, high=2)\nX_val = Tensor.randn(20, 10)\ny_val = Tensor.randint(20, high=2)\nhistory = train_model(model, X_train, y_train, X_val, y_val, epochs=2, batch_size=16, lr=0.01)\nprint(isinstance(history, list) and len(history) == 2)\n","expected_output":"True"},{"test":"from tinygrad import Tensor, nn\nmodel = nn.Linear(10, 2)\nX_train = Tensor.randn(100, 10)\ny_train = Tensor.randint(100, high=2)\nX_val = Tensor.randn(20, 10)\ny_val = Tensor.randint(20, high=2)\nhistory = train_model(model, X_train, y_train, X_val, y_val, epochs=2, batch_size=16, lr=0.01)\nprint(all('epoch' in h and 'train_loss' in h and 'val_loss' in h and 'val_accuracy' in h for h in history))\n","expected_output":"True"},{"test":"from tinygrad import Tensor, nn\nmodel = nn.Linear(10, 2)\nX_train = Tensor.randn(100, 10)\ny_train = Tensor.randint(100, high=2)\nX_val = Tensor.randn(20, 10)\ny_val = Tensor.randint(20, high=2)\nhistory = train_model(model, X_train, y_train, X_val, y_val, epochs=3, batch_size=16, lr=0.01)\nprint(history[0]['epoch'] == 1 and history[-1]['epoch'] == 3)\n","expected_output":"True"},{"test":"from tinygrad import Tensor, nn\nimport numpy as np\nclass TinyMLP:\n    def __init__(self):\n        self.l1 = nn.Linear(10, 5)\n        self.l2 = nn.Linear(5, 2)\n    def __call__(self, x):\n        return self.l2(self.l1(x).relu())\nmodel = TinyMLP()\nX_train = Tensor.randn(80, 10)\ny_train = Tensor.randint(80, high=2)\nX_val = Tensor.randn(20, 10)\ny_val = Tensor.randint(20, high=2)\nw_before = model.l1.weight.numpy().copy()\nhistory = train_model(model, X_train, y_train, X_val, y_val, epochs=5, batch_size=16, lr=0.1)\nw_after = model.l1.weight.numpy()\nprint(not np.allclose(w_before, w_after))\n","expected_output":"True"}],"approved_user_libraries":["tinygrad","numpy"],"difficulty":"easy","evaluation_metric":"Accuracy","data_info":"MNIST 28x28 grayscale digits flattened to 784-dim vectors, scaled to [0,1]. Trained with a 3-layer MLP (784 -> 128 -> 128 -> 10) defined as a plain tinygrad class with `__call__`.","time_limits":{"test":"120 seconds","dev":"60 seconds"},"schema":"practical_question_v1","min_eval_metric":0.85,"example":{"input":{"X_train":"tinygrad Tensor (N, features)","batch_size":"int","y_val":"tinygrad Tensor (M,) int64","epochs":"int","lr":"float","X_val":"tinygrad Tensor (M, features)","model":"plain tinygrad class with __call__","y_train":"tinygrad Tensor (N,) int64"},"output":{"history":"List[Dict] with keys 'epoch', 'train_loss', 'val_loss', 'val_accuracy'"}},"category":"Tinygrad Fundamentals","title":"Tinygrad: Build a Complete Training Loop","dataset":"MNIST","memory_limit":"2 GB","createdAt":"2026-05-13T21:01:43.657000+00:00","time_limits_seconds":{"dev":60,"test":120},"type":"epoch","lower_is_better":false,"gpu":false},{"created_at":"2026-07-29T03:03:59.726000+00:00","type":"general","constraints":["CPU only: no .cuda(), no .to(device), no GPU assumptions","Only numpy and torch may be imported by learner code","Must use nn.BatchNorm1d and nn.Dropout in the model","Binary logits + BCEWithLogitsLoss (single output unit)","No internet, no sklearn, no file I/O required","Deterministic under harness seeding; keep runtime well under 120s CPU"],"lower_is_better":false,"approved_user_libraries":["numpy","torch"],"time_limits":{"test":200,"dev":60},"data_info":"Harness synthesizes data on the fly (no files, no download). With seed 42: X ~ N(0,1) of shape (500, 10); labels from a fixed random 2-layer tanh projection of X plus Gaussian noise (std 0.35), thresholded at 0. An 80/20 train/test split is made with a seeded randperm. Validation harness uses 200 samples and fewer epochs.","example":{"input":"model = RegularizedMLP(input_dim=10, hidden_dim=64, dropout_p=0.3)\nlogits = model(torch.randn(16, 10))  # train mode or eval mode","output":"logits.shape == torch.Size([16])  # one logit per sample"},"pytorch_starter_code":"import torch\nimport torch.nn as nn\n\n\nclass RegularizedMLP(nn.Module):\n    \"\"\"MLP with BatchNorm1d and Dropout for binary classification.\"\"\"\n\n    def __init__(self, input_dim: int, hidden_dim: int = 64, dropout_p: float = 0.3):\n        super().__init__()\n        # TODO: Build at least two hidden blocks:\n        #   Linear -> BatchNorm1d -> ReLU (or similar) -> Dropout\n        # Final layer: Linear to 1 logit.\n        # Store layers on self (Sequential is fine).\n        pass\n\n    def forward(self, x: torch.Tensor) -> torch.Tensor:\n        \"\"\"Return shape (N,) logits for batch x of shape (N, input_dim).\"\"\"\n        # TODO: run x through your network and squeeze the last dim if needed\n        raise NotImplementedError\n\n\ndef train_model(model, X_train, y_train, epochs=150, lr=1e-2):\n    \"\"\"Train model in-place with BCEWithLogitsLoss + Adam. Return model.\"\"\"\n    # TODO:\n    # - criterion = nn.BCEWithLogitsLoss()\n    # - optimizer = torch.optim.Adam(model.parameters(), lr=lr)\n    # - loop epochs: zero_grad -> forward -> loss -> backward -> step\n    # - y_train is float 0/1 with shape (N,)\n    raise NotImplementedError\n","model_specs":"RegularizedMLP: >=2 hidden blocks, each Linear -> BatchNorm1d -> nonlinearity -> Dropout; final Linear to 1 logit; forward returns (N,) logits. train_model: BCEWithLogitsLoss + Adam, full-batch CPU training for `epochs` steps at learning rate `lr`, return the trained model. Module graph must contain nn.BatchNorm1d and nn.Dropout (harness asserts this).","gpu":false,"description":"# MLP with Dropout and BatchNorm\n\nBuild and train a multi-layer perceptron (MLP) for **binary classification** that uses `nn.BatchNorm1d` and `nn.Dropout` for stable training and regularization.\n\n## Goals\n1. Implement `RegularizedMLP` with **at least two hidden blocks**. Each hidden block must contain, in order: `nn.Linear` -> `nn.BatchNorm1d` -> nonlinearity -> `nn.Dropout`.\n2. The final layer must map to a **single logit** (shape `(N,)` after squeeze) for binary classification.\n3. Implement `train_model` using `nn.BCEWithLogitsLoss` and an Adam optimizer. Train on the tensors the harness provides.\n4. Stay on **CPU only**. Do not call `.cuda()` or `.to(device)`.\n\n## What the harness does\n- Synthesizes a seeded noisy binary-classification dataset (~500 samples, 10 features).\n- Splits into train / held-out test.\n- Instantiates your model, calls `train_model`, then measures test accuracy.\n- Checks that your module graph actually contains `BatchNorm1d` and `Dropout`.\n\n## API you must implement\n```text\nRegularizedMLP(input_dim, hidden_dim=64, dropout_p=0.3) -> nn.Module\nforward(x): x is (N, input_dim) float tensor -> (N,) logits\ntrain_model(model, X_train, y_train, epochs=150, lr=1e-2) -> trained model\n```\n`y_train` is a float tensor of 0/1 labels with shape `(N,)`.","tags":["pytorch","mlp","dropout","batchnorm","regularization","binary-classification"],"id":"3480fd6b-ee7a-4afd-ba4b-5c934aeab10b","evaluation_metric":"accuracy","difficulty":"medium","schema":"Learner receives tensors only via train_model args:\n- X_train: float tensor (N_train, 10)\n- y_train: float tensor (N_train,) with values in {0.0, 1.0}\nModel forward must accept (batch, 10) and return (batch,) logits.\nHarness builds RegularizedMLP(input_dim=10, hidden_dim=64, dropout_p=0.3) in the graded test.","min_eval_metric":0.78,"category":"PyTorch Fundamentals","title":"MLP with Dropout and BatchNorm","time_limits_seconds":{"dev":60,"test":200}},{"description":"Design **your own tabular binary classifier** on the real **Adult Census Income** dataset (UCI / OpenML).\n\nPredict whether a person earns **>50K** (class 1, minority). You receive **pandas DataFrames** with **mixed numeric and categorical** columns — raw, with missing values. Build any **classical** pipeline: imputation, encoding, scaling, imbalance handling, model choice, calibration.\n\nReturn `predict_proba(X)` scoring the positive class. Graded on **PR-AUC** (average precision) on a held-out split. Majority-class dummies fail; a careful classical pipeline passes.\n\n**No deep learning.** NumPy / pandas / scikit-learn only.\n","type":"practical","constraints":["Use only numpy, pandas, scipy, and sklearn — no PyTorch, TensorFlow, JAX, or other DL frameworks","Signature: train(X_train, y_train, X_val, y_val) -> predict_proba","X_train / X_val / X for predict_proba are pandas DataFrames with the same columns (mixed numeric + categorical)","predict_proba(X) must return a 1-D numpy array of shape (n_samples,) with finite positive-class scores","y is binary {0, 1} with 1 = income >50K (minority)","Must be deterministic under a fixed numpy random seed","Any classical strategy is valid — creativity encouraged"],"id":"35","test_cases":[{"test":"import numpy as np\nimport pandas as pd\nX_tr = pd.DataFrame({\n    'age': [25, 40, 60, 30, 45, 50, 22, 35, 55, 28, 33, 48],\n    'job': ['a','b','a','b','a','b','a','b','a','b','a','b'],\n    'hrs': [40, 50, 30, 45, 60, 20, 40, 50, 35, 40, 45, 55],\n})\ny_tr = np.array([0,1,1,0,1,0,0,1,1,0,0,1])\nX_v = X_tr.iloc[:4].copy()\ny_v = y_tr[:4]\npp = train(X_tr, y_tr, X_v, y_v)\nprint(callable(pp))\n","description":"Returns a callable on a tiny mixed-type frame","expected_output":"True"},{"test":"import numpy as np\nimport pandas as pd\nrng = np.random.RandomState(0)\nX_tr = pd.DataFrame({\n    'age': rng.randint(18, 80, 40),\n    'job': rng.choice(['a','b','c'], 40),\n    'hrs': rng.randint(10, 80, 40),\n})\ny_tr = (X_tr['age'] > 40).astype(int).to_numpy()\nX_v = X_tr.iloc[:10].copy()\ny_v = y_tr[:10]\npp = train(X_tr, y_tr, X_v, y_v)\ns = np.asarray(pp(X_v), dtype=float).reshape(-1)\nprint(s.shape == (10,) and np.all(np.isfinite(s)))\n","description":"predict_proba shape and finite","expected_output":"True"},{"test":"import numpy as np\nimport pandas as pd\nrng = np.random.RandomState(1)\nn = 60\nX_tr = pd.DataFrame({\n    'age': rng.randint(18, 80, n),\n    'job': rng.choice(['x','y'], n),\n    'hrs': rng.randint(10, 80, n),\n})\ny_tr = ((X_tr['age'] + X_tr['hrs']) > 100).astype(int).to_numpy()\nX_v = X_tr.iloc[:15].copy()\ny_v = y_tr[:15]\npp = train(X_tr, y_tr, X_v, y_v)\ns = np.asarray(pp(X_v), dtype=float).reshape(-1)\nprint(float(np.std(s)) > 1e-8)\n","description":"Scores vary with the input","expected_output":"True"}],"approved_user_libraries":["numpy","pandas","scipy","sklearn"],"evaluation_metric":"PR-AUC","difficulty":"medium","time_limits":{"test":"120 seconds","dev":"90 seconds"},"data_info":"Real UCI Adult Census Income via OpenML (name='adult', version=2). Predict income >50K (minority, ~24%). Mixed numeric + categorical columns with missing values. Dev (Run): stratified subsample of 8000 rows, seed=42. Submit: stratified subsample of 12000 rows, seed=99. Stratified train/val/holdout splits. X is a pandas DataFrame (not pre-encoded).","schema":"practical_question_v1","min_eval_metric":0.55,"example":{"input":{"X_train":"pandas DataFrame — Adult features (age, workclass, education, occupation, ...)","y_val":"numpy array (n_val,)","y_train":"numpy array (n_train,) — 1 if income >50K else 0","X_val":"pandas DataFrame — same columns as X_train"},"output":{"predict_proba":"callable: predict_proba(X: DataFrame) -> numpy array (n,) positive-class scores"}},"category":"Machine Learning","dataset":"Adult Census Income (UCI / OpenML adult v2)","title":"Design Your Own Tabular Classifier","memory_limit":"2 GB","createdAt":"2026-08-05 16:18:09.164988+00:00","model_specs":"Open-ended classical classifier on a real tabular dataset. User implements train(...) -> predict_proba. Harness scores PR-AUC (average precision) on held-out labels. Logistic, SVM, trees, forests, boosting, ensembles all allowed.","time_limits_seconds":{"dev":90,"test":120},"lower_is_better":false,"gpu":false},{"description":"Design **your own post-training quantization (PTQ)** scheme for an MLP trained on real **MNIST**.\n\nMNIST is loaded from the same Google TF/Keras host used by other Deep-ML labs (`storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz`). You get the trained FP32 weights and a calibration batch of real flattened digits in `[0, 1]`.\n\nApply any classical PTQ idea (bit-width, symmetric/asymmetric, per-tensor or per-channel, calibration, GPTQ-style compensation…), then return **dequantized** weights.\n\n**Graded on** mean **cosine similarity** of logits vs the FP32 model on a held-out MNIST split (higher is better).\n\n**PTQ gate:** each tensor must lie on a uniform 4- or 8-bit grid (per-tensor / per-row / per-column) and must not be an FP32 identity copy.\n\n**NumPy only.**\n","type":"practical","constraints":["Use only numpy — no PyTorch, TensorFlow, JAX, or other DL frameworks","Signature: ptq(weights, calib_X) -> dequant_weights dict","Same keys and shapes as input weights; finite floats","Must look like 4/8-bit uniform PTQ (identity FP32 fails)","Must be deterministic under a fixed numpy seed","Any classical PTQ strategy is valid — creativity encouraged"],"id":"36","test_cases":[{"test":"import numpy as np\nrng=np.random.RandomState(0)\nweights={\n 'W1':rng.randn(128,784)*0.02,'b1':rng.randn(128)*0.01,\n 'W2':rng.randn(64,128)*0.05,'b2':rng.randn(64)*0.01,\n 'W3':rng.randn(10,64)*0.05,'b3':rng.randn(10)*0.01,\n}\ndq=ptq(weights, rng.rand(12,784))\nprint(isinstance(dq,dict) and set(dq.keys())==set(weights.keys()) and all(np.asarray(dq[k]).shape==weights[k].shape for k in weights))\n","description":"Correct keys and shapes for MNIST MLP","expected_output":"True"},{"test":"import numpy as np\nrng=np.random.RandomState(1)\nweights={\n 'W1':rng.randn(128,784)*0.05,'b1':rng.randn(128),\n 'W2':rng.randn(64,128)*0.05,'b2':rng.randn(64),\n 'W3':rng.randn(10,64)*0.05,'b3':rng.randn(10),\n}\ndq=ptq(weights, rng.rand(8,784))\nchanged=any(not np.allclose(np.asarray(dq[k]), weights[k]) for k in weights if weights[k].size>=8)\nprint(bool(changed))\n","description":"Not FP32 identity","expected_output":"True"},{"test":"import numpy as np\nrng=np.random.RandomState(2)\nweights={\n 'W1':rng.randn(128,784)*0.03,'b1':rng.randn(128)*0.02,\n 'W2':rng.randn(64,128)*0.05,'b2':rng.randn(64)*0.02,\n 'W3':rng.randn(10,64)*0.05,'b3':rng.randn(10)*0.02,\n}\nX=rng.rand(30,784)\ndq=ptq(weights,X)\n\ndef fwd(w,X):\n    h=np.maximum(X@w['W1'].T+w['b1'],0)\n    h=np.maximum(h@w['W2'].T+w['b2'],0)\n    return h@w['W3'].T+w['b3']\ny1,y2=fwd(weights,X),fwd(dq,X)\nnum=np.sum(y1*y2,axis=1)\nden=np.linalg.norm(y1,axis=1)*np.linalg.norm(y2,axis=1)+1e-12\nprint(bool(np.all(np.isfinite(y2)) and float(np.mean(num/den))>0.95))\n","description":"High cosine on a random batch","expected_output":"True"}],"evaluation_metric":"mean_output_cosine","approved_user_libraries":["numpy"],"data_info":"Real MNIST from https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz (same as other Deep-ML labs). Pixels flattened to 784 and scaled to [0,1]. Harness trains MLPClassifier(hidden=(128,64), relu) on a stratified 8k-subset. Dev seed=42; Submit seed=99. User receives FP32 weights + train calibration batch; graded on held-out test logits cosine vs FP32.","time_limits":{"test":"180 seconds","dev":"120 seconds"},"difficulty":"medium","schema":"practical_question_v1","min_eval_metric":0.98,"example":{"input":{"calib_X":"(n_calib, 784) real MNIST train pixels in [0,1]","weights":"dict W1(128,784), b1(128,), W2(64,128), b2(64,), W3(10,64), b3(10,) from MNIST MLP"},"output":{"dequant_weights":"same keys/shapes, low-bit reconstructions as float"}},"category":"Deep Learning","model_specs":"Open-ended weight-only PTQ on an MNIST MLP (784→128→64→10). ptq(weights, calib_X)->dequant_weights. Metric: mean logit cosine vs FP32.","title":"Design Your Own PTQ","dataset":"MNIST","memory_limit":"2 GB","createdAt":"2026-08-05 18:02:12.102041+00:00","time_limits_seconds":{"dev":120,"test":180},"lower_is_better":false,"gpu":false},{"type":"epoch","constraints":["Implement train(train_chosen, train_rejected, n_items, beta=0.5) and return a callable score(indices).","score(indices) must accept a 1D numpy int array and return a 1D float array of the same shape.","Higher score means more preferred — preference accuracy counts score(chosen) > score(rejected).","No external data downloads. Pure synthetic pairs are provided by the harness.","Time limit: 30s Run, 60s Submit."],"test_cases":[{"test":"import numpy as np\nsc=train(np.array([0,1,2]), np.array([1,2,0]), 3, beta=0.5)\nout=sc(np.array([0,1,2]))\nprint(len(out), int(np.all(np.isfinite(out))))","expected_output":"3 1"}],"lower_is_better":false,"approved_user_libraries":["numpy","torch","scipy","scikit-learn","math","json"],"data_info":"train() receives integer index pairs (chosen, rejected). A hidden latent quality vector generates labels with light noise. Held-out pairs use the same latent qualities.","time_limits":{"test":60,"dev":30},"example":{"input":"n_items=50, 1500 train pairs, beta=0.5","reasoning":"Fit tabular log-probabilities with the DPO logistic loss. The learned scores correlate with the hidden item qualities, so held-out pairs are ranked correctly well above chance (0.5).","output":"preference_accuracy >= 0.75 on held-out pairs"},"model_specs":"Any model is fine (tabular logits, embeddings, etc.). Score must be comparable across items so that higher score = more preferred.","gpu":false,"description":"## Train a Tabular Policy with DPO\n\nYou will align a **discrete policy** to pairwise human (synthetic) preferences using **Direct Preference Optimization** — no separate reward model and no PPO loop.\n\n### Setup\n\nThere is a catalog of `n_items` items. Each training example is a pair of indices `(chosen, rejected)` where the chosen item was preferred. Preferences were generated from a hidden Bradley–Terry quality vector with a little label noise.\n\nA frozen **uniform reference** over the catalog is assumed:\n\n$$\\pi_{\\rm ref}(i) = 1/n_{\\rm items}$$\n\nYour job is to learn a policy $\\pi_\\theta$ (or any scoring function) so that preferred items get higher scores on **held-out** pairs.\n\n### What to implement\n\n```python\ndef train(train_chosen, train_rejected, n_items, beta=0.5) -> score\n```\n\n`score(indices)` returns a float array; the grader computes\n\n$$\\mathrm{preference\\_accuracy} = \\mathbb{E}\\big[\\mathbf{1}\\{\\mathrm{score}(y_w) > \\mathrm{score}(y_l)\\}\\big]$$\n\nPass threshold: **0.75**.\n\n### Suggested approach (DPO)\n\nParameterize $\\log\\pi_\\theta$ with logits + log-softmax. Minimize\n\n$$\\mathcal{L}=-\\log\\sigma\\Big(\\beta\\big(\\log\\pi_\\theta(y_w)-\\log\\pi_\\theta(y_l)\\big)\\Big)$$\n\n(the uniform reference cancels in the difference). Gradient descent for a few hundred steps is enough.\n\n### Tips\n\n- Vectorize over the batch of pairs.\n- Clip DPO logits before `exp` for stability.\n- You may use PyTorch if you prefer; numpy is enough.\n","tags":["dpo","rlhf","preference","alignment","numpy"],"id":"37","evaluation_metric":"preference_accuracy","difficulty":"medium","min_eval_metric":0.75,"category":"Reinforcement Learning","title":"Train a Tabular Policy with DPO","dataset":"Synthetic pairwise preferences over a discrete item catalog (Bradley-Terry latent qualities)","memory_limit":"4 GB","time_limits_seconds":{"dev":30,"test":60}},{"created_at":"2026-10-26T20:49:35.927000+00:00","description":"# Best Inference Engine Controller\n\nOne GPU replica serves a 32B model to three kinds of traffic at once: code completions with tight latency targets, long-context chat, and offline batch jobs that only need to finish. Inference engines expose many knobs, and the right setting changes with the traffic. Write the controller that sets them, one engine iteration at a time. The grader replays a hidden traffic trace through a simulated engine driven by your controller and scores the work served within each request's latency targets.\n\n```python\nclass Controller:\n    def __init__(self, engine):\n        ...\n\n    def step(self, state):\n        ...\n        return {\"admit\": [...], \"prefill_tokens\": 2048, \"spec_k\": 2}\n```\n\n## The engine\n\n`engine` is a dict of the replica's constants: `hbm_bandwidth` (bytes/s), `fp8_flops` (FLOP/s), `weight_bytes`, `flops_per_token`, `attn_flops_per_pair`, `kv_bytes_per_token_fp16`, `kv_capacity_bytes`, `draft_weight_bytes`, `draft_flops_per_token`, `draft_launch_ms`, `step_overhead_ms`, `max_running` (256), `max_spec_k` (8), `max_prefill_tokens` (32768).\n\n`step` is called before every engine iteration. `state` holds:\n\n- `t`: simulated time in seconds; `step`: iteration count; `kv_free_bytes`: unreserved KV cache.\n- `waiting`: a numpy structured array, one row per arrived request that is not on the replica; `running`: one row per request on the replica, in admission order.\n- Row fields: `id`, `arrival`, `prompt_len`, `max_new` (output tokens it will generate), `temperature`, `domain` (0 code completion, 1 chat, 2 offline batch), `strict` (1 if quality-sensitive), `ttft_slo` and `itl_slo` (seconds), `status` (1 waiting, 2 prefilling, 3 decoding), `kv_fp8`, `prefilled`, `prefill_target`, `generated`, `admitted_at`, `first_token_at`, `drafted`, `accepted`, `slow_tokens`, `preemptions`.\n\nReturn a dict:\n\n- `admit`: ids from `waiting`, each either a bare id (FP16 KV cache) or a pair `(id, \"fp8\")` / `(id, \"fp16\")`. Admission reserves KV for the request's prompt plus any tokens it already generated. An admission that does not fit in free KV, or would exceed `max_running`, is skipped.\n- `prefill_tokens`: the most prompt tokens the iteration may prefill, from 0 to 32768. They go to prefilling requests in the order of the optional `prefill_first` list of ids, then in admission order. A request whose prefill completes emits its first token.\n- `spec_k`: draft length from 0 to 8. With `k > 0`, a draft model proposes `k` tokens for every decoding request and the target verifies `k + 1` positions; each request emits its accepted drafts plus one token. How often a draft token is accepted depends on the request and is not disclosed; `drafted` and `accepted` count what happened.\n\nEvery decoding request decodes in every iteration. If the KV cache cannot hold `k + 1` new tokens for every decoder, the engine preempts the most recently admitted decoders: their cache is freed, they go back to `waiting`, and once readmitted they must prefill their prompt and generated tokens again. A request admitted with `\"fp8\"` stores its KV cache in half the bytes.\n\nAn iteration takes, in milliseconds,\n\n`step_overhead_ms + 1000 * max(bytes / hbm_bandwidth, flops / fp8_flops)`\n\nplus, when `k > 0` and anything is decoding, `k * (draft_launch_ms + 1000 * max(draft_weight_bytes / hbm_bandwidth, decoders * draft_flops_per_token / fp8_flops))`. Here `bytes` is the weights plus the KV cache read by every decoder (its prompt plus generated tokens times its KV bytes per token) plus the cached prefix each prefill chunk attends to. `flops` is `(decoders * (k + 1) + prefill tokens) * flops_per_token`, plus `attn_flops_per_pair` times `k + 1` times every decoder's cached length, plus `attn_flops_per_pair * c * (offset + c / 2)` for a prefill chunk of `c` tokens starting at `offset`. An iteration with nothing to compute takes 5 ms.\n\n## How it is graded\n\nA request meets its objectives when all of these hold:\n\n- It finishes before the trace ends.\n- Its time from arrival to first token is at most `ttft_slo`.\n- At most 10% of its tokens after the first are slow. A token is slow when the time since the request's previous emission, divided by the tokens it emitted in that iteration, exceeds `itl_slo`.\n- If it is `strict`, it never held its KV cache in FP8.\n\nThe score is **goodput**: the prompt plus output tokens of every request that met its objectives, divided by the trace duration, in tokens per second. Higher is better; the floor is `4000`.\n\nRun replays a 480-second trace. Submit replays a held-out 900-second trace with a different seed and a different, busier sequence of traffic phases. Your controller only ever sees the present. The report also gives the offered load (the goodput if every request met its objectives) and a per-domain breakdown.\n\n## Rules\n\n- Your controller may use at most 40 s of compute on Run and 80 s on Submit.\n- Allowed imports: numpy, math, collections, heapq, itertools, functools, random, dataclasses, typing, bisect, statistics, operator, copy, enum and abc.\n- These zero the score and fail the run:\n  - an exception;\n  - an invalid return value, or an id that is not waiting or is named twice;\n  - going over the compute budget;\n  - other imports, introspection (frames, `globals`, `getattr`, `gc`, `inspect`), `atexit` or `__del__` hooks, or patching numpy or builtins.\n","tags":["inference","serving","continuous-batching","chunked-prefill","speculative-decoding","kv-cache","slo","goodput","open-ended","leaderboard"],"type":"general","id":"37abee47-7133-4ecc-8a83-df898d0691e2","dataset_id":"synthetic","test_cases":[{"test":"import numpy as np\nENGINE = {\"hbm_bandwidth\": 3.35e12 * 0.85, \"fp8_flops\": 1979e12 * 0.55, \"weight_bytes\": 32e9, \"flops_per_token\": 6.4e10,\n          \"attn_flops_per_pair\": 1.31e6, \"kv_bytes_per_token_fp16\": 262144, \"kv_capacity_bytes\": 40e9,\n          \"draft_weight_bytes\": 1.6e9, \"draft_flops_per_token\": 3.2e9, \"draft_launch_ms\": 0.25, \"step_overhead_ms\": 1.5,\n          \"max_running\": 256, \"max_spec_k\": 8, \"max_prefill_tokens\": 32768}\nDT = [(\"id\", \"i4\"), (\"arrival\", \"f8\"), (\"prompt_len\", \"i4\"), (\"max_new\", \"i4\"), (\"temperature\", \"f4\"), (\"domain\", \"i1\"),\n      (\"strict\", \"i1\"), (\"ttft_slo\", \"f4\"), (\"itl_slo\", \"f4\"), (\"status\", \"i1\"), (\"kv_fp8\", \"i1\"), (\"prefilled\", \"i4\"),\n      (\"prefill_target\", \"i4\"), (\"generated\", \"i4\"), (\"admitted_at\", \"f8\"), (\"first_token_at\", \"f8\"), (\"drafted\", \"i4\"),\n      (\"accepted\", \"i4\"), (\"slow_tokens\", \"i4\"), (\"preemptions\", \"i2\")]\ndef rows(n, **kw):\n    a = np.zeros(n, dtype=DT)\n    for k, v in kw.items():\n        a[k] = v\n    return a\nc = Controller(dict(ENGINE))\nout = c.step({\"t\": 0.0, \"step\": 0, \"kv_free_bytes\": 40e9, \"waiting\": rows(0), \"running\": rows(0)})\nprint(isinstance(out, dict) and set(out) <= {\"admit\", \"prefill_tokens\", \"spec_k\", \"prefill_first\"})","expected_output":"True"},{"test":"import numpy as np\nENGINE = {\"hbm_bandwidth\": 3.35e12 * 0.85, \"fp8_flops\": 1979e12 * 0.55, \"weight_bytes\": 32e9, \"flops_per_token\": 6.4e10,\n          \"attn_flops_per_pair\": 1.31e6, \"kv_bytes_per_token_fp16\": 262144, \"kv_capacity_bytes\": 40e9,\n          \"draft_weight_bytes\": 1.6e9, \"draft_flops_per_token\": 3.2e9, \"draft_launch_ms\": 0.25, \"step_overhead_ms\": 1.5,\n          \"max_running\": 256, \"max_spec_k\": 8, \"max_prefill_tokens\": 32768}\nDT = [(\"id\", \"i4\"), (\"arrival\", \"f8\"), (\"prompt_len\", \"i4\"), (\"max_new\", \"i4\"), (\"temperature\", \"f4\"), (\"domain\", \"i1\"),\n      (\"strict\", \"i1\"), (\"ttft_slo\", \"f4\"), (\"itl_slo\", \"f4\"), (\"status\", \"i1\"), (\"kv_fp8\", \"i1\"), (\"prefilled\", \"i4\"),\n      (\"prefill_target\", \"i4\"), (\"generated\", \"i4\"), (\"admitted_at\", \"f8\"), (\"first_token_at\", \"f8\"), (\"drafted\", \"i4\"),\n      (\"accepted\", \"i4\"), (\"slow_tokens\", \"i4\"), (\"preemptions\", \"i2\")]\ndef rows(n, **kw):\n    a = np.zeros(n, dtype=DT)\n    for k, v in kw.items():\n        a[k] = v\n    return a\nc = Controller(dict(ENGINE))\nw = rows(1, id=1000, arrival=0.0, prompt_len=1200, max_new=40, temperature=0.1, domain=0, ttft_slo=0.5, itl_slo=0.03, status=1)\nout = c.step({\"t\": 0.01, \"step\": 0, \"kv_free_bytes\": 40e9, \"waiting\": w, \"running\": rows(0)})\nids = [a[0] if isinstance(a, (tuple, list)) else a for a in out.get(\"admit\", [])]\nk, p = out.get(\"spec_k\", 0), out.get(\"prefill_tokens\", 0)\nprint([int(i) for i in ids] == [1000] and 0 <= int(k) <= 8 and 0 < int(p) <= 32768)","expected_output":"True"},{"test":"import numpy as np\nENGINE = {\"hbm_bandwidth\": 3.35e12 * 0.85, \"fp8_flops\": 1979e12 * 0.55, \"weight_bytes\": 32e9, \"flops_per_token\": 6.4e10,\n          \"attn_flops_per_pair\": 1.31e6, \"kv_bytes_per_token_fp16\": 262144, \"kv_capacity_bytes\": 40e9,\n          \"draft_weight_bytes\": 1.6e9, \"draft_flops_per_token\": 3.2e9, \"draft_launch_ms\": 0.25, \"step_overhead_ms\": 1.5,\n          \"max_running\": 256, \"max_spec_k\": 8, \"max_prefill_tokens\": 32768}\nDT = [(\"id\", \"i4\"), (\"arrival\", \"f8\"), (\"prompt_len\", \"i4\"), (\"max_new\", \"i4\"), (\"temperature\", \"f4\"), (\"domain\", \"i1\"),\n      (\"strict\", \"i1\"), (\"ttft_slo\", \"f4\"), (\"itl_slo\", \"f4\"), (\"status\", \"i1\"), (\"kv_fp8\", \"i1\"), (\"prefilled\", \"i4\"),\n      (\"prefill_target\", \"i4\"), (\"generated\", \"i4\"), (\"admitted_at\", \"f8\"), (\"first_token_at\", \"f8\"), (\"drafted\", \"i4\"),\n      (\"accepted\", \"i4\"), (\"slow_tokens\", \"i4\"), (\"preemptions\", \"i2\")]\ndef rows(n, **kw):\n    a = np.zeros(n, dtype=DT)\n    for k, v in kw.items():\n        a[k] = v\n    return a\nc = Controller(dict(ENGINE))\nw = rows(1, id=1000, arrival=0.0, prompt_len=1200, max_new=40, temperature=0.1, domain=0, ttft_slo=0.5, itl_slo=0.03, status=1)\nquiet = c.step({\"t\": 0.01, \"step\": 0, \"kv_free_bytes\": 40e9, \"waiting\": w, \"running\": rows(0)})\nn = 120\nr = rows(n, id=np.arange(2000, 2000 + n), arrival=1.0, prompt_len=2000, max_new=500, temperature=1.0, domain=2,\n         ttft_slo=600.0, itl_slo=1.0, status=3, prefilled=2000, prefill_target=2000, generated=200, admitted_at=1.0,\n         first_token_at=2.0, drafted=800, accepted=200)\nbusy = c.step({\"t\": 60.0, \"step\": 5000, \"kv_free_bytes\": 5e9, \"waiting\": rows(0), \"running\": r})\nprint((quiet.get(\"spec_k\"), quiet.get(\"prefill_tokens\")) != (busy.get(\"spec_k\"), busy.get(\"prefill_tokens\")))","expected_output":"True"}],"img_type":"full","approved_user_libraries":["numpy"],"difficulty":"hard","evaluation_metric":"goodput_tps","lower_is_better":false,"data_info":"Synthetic serving traces generated inside the grader from a fixed seed: Poisson arrivals of three request domains whose rates change across phases, plus bursts of offline batch requests. Run: 480 s, seed 42. Submit: 900 s, a different seed and phase sequence. Nothing is downloaded.","time_limits":{"test":240,"dev":120},"min_eval_metric":4000.0,"category":"Inference","dataset":"Synthetic serving traces","title":"Best Inference Engine Controller","gpu":false,"time_limits_seconds":{"dev":120,"test":240}},{"created_at":"2026-10-27T19:55:44.802000+00:00","type":"general","test_cases":[{"test":"nest = {\"name\": \"gemm_32\", \"loops\": [{\"name\": \"i\", \"extent\": 32}, {\"name\": \"j\", \"extent\": 32}, {\"name\": \"k\", \"extent\": 32}], \"reduction\": [\"k\"], \"arrays\": {\"C\": {\"shape\": [32, 32], \"elem_bytes\": 4, \"base\": 1048576}, \"A\": {\"shape\": [32, 32], \"elem_bytes\": 4, \"base\": 1052672}, \"B\": {\"shape\": [32, 32], \"elem_bytes\": 4, \"base\": 1056768}}, \"accesses\": [{\"array\": \"C\", \"mode\": \"r\", \"index\": [{\"i\": 1}, {\"j\": 1}], \"offset\": [0, 0]}, {\"array\": \"A\", \"mode\": \"r\", \"index\": [{\"i\": 1}, {\"k\": 1}], \"offset\": [0, 0]}, {\"array\": \"B\", \"mode\": \"r\", \"index\": [{\"k\": 1}, {\"j\": 1}], \"offset\": [0, 0]}, {\"array\": \"C\", \"mode\": \"w\", \"index\": [{\"i\": 1}, {\"j\": 1}], \"offset\": [0, 0]}], \"cache\": {\"line_bytes\": 64, \"levels\": [{\"name\": \"L1\", \"sets\": 16, \"ways\": 4}, {\"name\": \"L2\", \"sets\": 64, \"ways\": 8}], \"miss_cost\": {\"L1\": 1, \"L2\": 8}}}\ns = schedule(nest)\nprint(isinstance(s, (list, tuple)) and len(s) >= 1 and all(len(p) == 2 for p in s))","expected_output":"True"},{"test":"nest = {\"name\": \"gemm_32\", \"loops\": [{\"name\": \"i\", \"extent\": 32}, {\"name\": \"j\", \"extent\": 32}, {\"name\": \"k\", \"extent\": 32}], \"reduction\": [\"k\"], \"arrays\": {\"C\": {\"shape\": [32, 32], \"elem_bytes\": 4, \"base\": 1048576}, \"A\": {\"shape\": [32, 32], \"elem_bytes\": 4, \"base\": 1052672}, \"B\": {\"shape\": [32, 32], \"elem_bytes\": 4, \"base\": 1056768}}, \"accesses\": [{\"array\": \"C\", \"mode\": \"r\", \"index\": [{\"i\": 1}, {\"j\": 1}], \"offset\": [0, 0]}, {\"array\": \"A\", \"mode\": \"r\", \"index\": [{\"i\": 1}, {\"k\": 1}], \"offset\": [0, 0]}, {\"array\": \"B\", \"mode\": \"r\", \"index\": [{\"k\": 1}, {\"j\": 1}], \"offset\": [0, 0]}, {\"array\": \"C\", \"mode\": \"w\", \"index\": [{\"i\": 1}, {\"j\": 1}], \"offset\": [0, 0]}], \"cache\": {\"line_bytes\": 64, \"levels\": [{\"name\": \"L1\", \"sets\": 16, \"ways\": 4}, {\"name\": \"L2\", \"sets\": 64, \"ways\": 8}], \"miss_cost\": {\"L1\": 1, \"L2\": 8}}}\ns = schedule(nest)\nprint(sorted(set(str(n) for n, _ in s)))","expected_output":"['i', 'j', 'k']"},{"test":"nest = {\"name\": \"gemm_32\", \"loops\": [{\"name\": \"i\", \"extent\": 32}, {\"name\": \"j\", \"extent\": 32}, {\"name\": \"k\", \"extent\": 32}], \"reduction\": [\"k\"], \"arrays\": {\"C\": {\"shape\": [32, 32], \"elem_bytes\": 4, \"base\": 1048576}, \"A\": {\"shape\": [32, 32], \"elem_bytes\": 4, \"base\": 1052672}, \"B\": {\"shape\": [32, 32], \"elem_bytes\": 4, \"base\": 1056768}}, \"accesses\": [{\"array\": \"C\", \"mode\": \"r\", \"index\": [{\"i\": 1}, {\"j\": 1}], \"offset\": [0, 0]}, {\"array\": \"A\", \"mode\": \"r\", \"index\": [{\"i\": 1}, {\"k\": 1}], \"offset\": [0, 0]}, {\"array\": \"B\", \"mode\": \"r\", \"index\": [{\"k\": 1}, {\"j\": 1}], \"offset\": [0, 0]}, {\"array\": \"C\", \"mode\": \"w\", \"index\": [{\"i\": 1}, {\"j\": 1}], \"offset\": [0, 0]}], \"cache\": {\"line_bytes\": 64, \"levels\": [{\"name\": \"L1\", \"sets\": 16, \"ways\": 4}, {\"name\": \"L2\", \"sets\": 64, \"ways\": 8}], \"miss_cost\": {\"L1\": 1, \"L2\": 8}}}\ns = [(str(n), int(t)) for n, t in schedule(nest)]\nok = all([t for m, t in s if m == l][-1] == 1 for l in 'ijk')\nprint(ok)","expected_output":"True"},{"test":"nest = {\"name\": \"gemm_32\", \"loops\": [{\"name\": \"i\", \"extent\": 32}, {\"name\": \"j\", \"extent\": 32}, {\"name\": \"k\", \"extent\": 32}], \"reduction\": [\"k\"], \"arrays\": {\"C\": {\"shape\": [32, 32], \"elem_bytes\": 4, \"base\": 1048576}, \"A\": {\"shape\": [32, 32], \"elem_bytes\": 4, \"base\": 1052672}, \"B\": {\"shape\": [32, 32], \"elem_bytes\": 4, \"base\": 1056768}}, \"accesses\": [{\"array\": \"C\", \"mode\": \"r\", \"index\": [{\"i\": 1}, {\"j\": 1}], \"offset\": [0, 0]}, {\"array\": \"A\", \"mode\": \"r\", \"index\": [{\"i\": 1}, {\"k\": 1}], \"offset\": [0, 0]}, {\"array\": \"B\", \"mode\": \"r\", \"index\": [{\"k\": 1}, {\"j\": 1}], \"offset\": [0, 0]}, {\"array\": \"C\", \"mode\": \"w\", \"index\": [{\"i\": 1}, {\"j\": 1}], \"offset\": [0, 0]}], \"cache\": {\"line_bytes\": 64, \"levels\": [{\"name\": \"L1\", \"sets\": 16, \"ways\": 4}, {\"name\": \"L2\", \"sets\": 64, \"ways\": 8}], \"miss_cost\": {\"L1\": 1, \"L2\": 8}}}\ns = [(str(n), int(t)) for n, t in schedule(nest)]\nprint(s[-1][0] != 'k' or any(t > 1 for _, t in s))","expected_output":"True"}],"lower_is_better":true,"approved_user_libraries":["numpy","math","time","random","collections","itertools","functools"],"data_info":"Synthetic loop nests generated inside the grader. Run: six fixed nests (GEMM 64x64x64, 3x3 conv, transpose, 5-point stencil, attention scores, transposed matvec). Submit: 24 nests drawn fresh every run from a random seed (GEMM in three layouts, batched attention scores and attention x values, 3x3 conv, transpose, stencil, transposed matvec, tensor contraction). A two-level LRU cache simulator (written in C, compiled in the sandbox) replays every schedule.","time_limits":{"test":300,"dev":150},"example":{"input":"schedule({'loops': [{'name': 'i', 'extent': 64}, {'name': 'j', 'extent': 64}, {'name': 'k', 'extent': 64}], 'reduction': ['k'], 'arrays': {...}, 'accesses': [...], 'cache': {...}})","output":"[('i', 16), ('j', 16), ('k', 16), ('i', 1), ('k', 1), ('j', 1)]  -> the grader reports, e.g., 16,384 L1 + 768 L2 misses for this GEMM against 266,880 + 768 as written"},"gpu":false,"description":"You are writing the loop scheduler of a compiler. It receives loop nests like the GEMMs, convolutions and transposes of week 3, written as plain `RANGE` loops, and decides in which order, and in which tiles, their iterations run. The arithmetic never changes, only the order of iterations. The order decides how often data has to come back from memory. Every schedule is replayed through a simulated two-level cache, and you are scored on its misses. The leaderboard ranks by **cost relative to the compulsory misses, lower is better**.\n\n**Contract.** Define `schedule(nest) -> list of (loop_name, step)`, called once per loop nest. `nest` is a dict:\n\n- `loops`: the loops in their written order, e.g. `[{\"name\": \"i\", \"extent\": 64}, ...]`. A loop `l` takes the values `0 .. extent-1`.\n- `reduction`: the loops that carry an associative sum. Every other loop is fully parallel, so any order of the iterations is allowed.\n- `arrays`: `name -> {\"shape\", \"elem_bytes\", \"base\"}`. Arrays are row-major and `base` is the byte address of element 0; every array starts on a 4 KiB boundary.\n- `accesses`: what one iteration touches, in this order, e.g. `{\"array\": \"inp\", \"mode\": \"r\", \"index\": [{\"ci\": 1}, {\"y\": 1, \"ky\": 1}, {\"x\": 1, \"kx\": 1}], \"offset\": [0, 0, 0]}`. Dimension `d` of the element is `offset[d] + sum(coeff * loop_value)`. Mode `r` is a read and `w` a write.\n- `cache`: the simulated cache (below), and `name`.\n\nThe schedule lists levels outermost first.\n- Each loop appears 1 to 4 times, its steps strictly decreasing and ending at 1.\n- A level `(l, s)` with `s > 1` walks the current range of `l` in blocks of `s` (the last block may be shorter); the level with step 1 walks single values.\n- The order of the levels is the loop order. At most 16 levels.\n\nSo for a GEMM, `[(\"i\", 16), (\"j\", 16), (\"k\", 16), (\"i\", 1), (\"k\", 1), (\"j\", 1)]` runs 16 x 16 x 16 tiles and walks `i, k, j` inside each tile, and `[(l[\"name\"], 1) for l in nest[\"loops\"]]` is the nest exactly as written. Every iteration runs exactly once, whatever you return.\n\n**The cache.**\n- Two levels with 64-byte lines: L1 has 16 sets x 4 ways (4 KiB) and L2 has 64 sets x 8 ways (32 KiB).\n- Both are LRU, a line goes to set `line mod sets`, and writes behave like reads.\n- L2 is looked up only on an L1 miss, and both start empty for each nest.\n- The cost of a nest is `L1 misses + 8 * L2 misses`.\n\n**Score.** For each nest, `cost / compulsory_cost`, where the compulsory cost charges each distinct line touched one miss in both levels (`9` per line). No schedule goes below 1.0, and most nests cannot reach it. The score is the geometric mean over the nests. The report shows misses for the written order and for your schedule on every nest. A score of at most **2.7** counts as solved; everything below that is leaderboard.\n\n**Nests.**\n- **Run:** six fixed nests: GEMM 64x64x64, a 3x3 convolution, a transpose, a 5-point stencil, attention scores and a transposed matrix-vector product.\n- **Submit:** 24 nests drawn fresh every run from a random seed (printed in the report). The draw varies the shapes and includes families that are not in Run: other GEMM layouts, attention probabilities times values, and a tensor contraction. Scores therefore vary a little between Submits.\n\n**Budget and rules.**\n- The total time inside `schedule` is capped at 30 s on Run and 90 s on Submit; module-level code counts toward the run's overall time limit.\n- Your code may import only `numpy`, `math`, `time`, `random`, `collections`, `heapq`, `bisect`, `itertools`, `functools`, `typing` and `dataclasses`, and may use an imported module only as `module.name`.\n\n**Gates.** The score is set to 99 and the run fails if any of these happen:\n- A schedule breaks the rules above (unknown loop, a loop missing, steps not strictly decreasing to 1, more than 16 levels, a non-int step).\n- `schedule` raises or exits.\n- The time budget runs out.\n- Your code reads files, uses introspection (`globals`, `vars`, `getattr`/`setattr`, frames, `eval`/`exec`), touches `atexit` or `__del__`, or assigns to, aliases or reaches into the internals of an imported module.","tags":["compilers","loops","tiling","loop-interchange","cache","gemm","convolution","autotuning","open-ended","leaderboard"],"id":"385dea44-160b-487c-bdae-d24a071d467e","dataset_id":"synthetic","img_type":"full","difficulty":"hard","evaluation_metric":"cost_vs_compulsory","min_eval_metric":2.7,"category":"Compilers","dataset":"Synthetic loop nests (GEMM, conv, transpose, stencil, attention, contraction) and a simulated cache","title":"Fewest Cache Misses","time_limits_seconds":{"dev":150,"test":300}},{"created_at":"2026-11-01T02:18:38.173000+00:00","type":"general","constraints":["at most max_leaves leaves in total across all trees; 30 s of CPU per fit over all threads and workers; a fresh process per task","fit returns plain data: {'bias': number, 'trees': [[node, ...], ...]}","numpy, pandas, scipy, sklearn, lightgbm, xgboost, math, itertools, collections, heapq, bisect, random, statistics, time, warnings, typing, copy only; attributes may be assigned only on self, inside a method defined in a class body","source capped at 30000 characters, 200 numeric literals, 1500 characters of string constants"],"test_cases":[{"test":"import numpy as np\nimport pandas as pd\n_r = np.random.RandomState(0)\n_n = 2000\n_a = _r.normal(size=_n)\n_b = _r.randint(0, 4, _n)\n_c = _r.normal(size=_n)\n_lv = ['v1', 'v2', 'v3', 'v4']\n_X = pd.DataFrame({'f0': _a, 'f1': pd.Categorical.from_codes(_b, categories=_lv), 'f2': _c})\n_y = (_r.rand(_n) < 1 / (1 + np.exp(-(2 * _a + (_b >= 2) * 2.0 - 1.0)))).astype(int)\n_m = fit(_X, _y, 16)\ndef _val(n, x):\n    i = 0\n    while 'value' not in n[i]:\n        s = n[i]\n        go = x[s['feature']] in s['in'] if 'in' in s else x[s['feature']] <= s['threshold']\n        i = s['left'] if go else s['right']\n    return n[i]['value']\n_rows = _X.iloc[:400].to_dict('records')\n_F = np.array([_m['bias'] + sum(_val(t, x) for t in _m['trees']) for x in _rows])\n_p = np.clip(1 / (1 + np.exp(-_F)), 1e-4, 1 - 1e-4)\n_ll = float(-np.mean(_y[:400] * np.log(_p) + (1 - _y[:400]) * np.log(1 - _p)))\n_leaves = sum(1 for t in _m['trees'] for nd in t if 'value' in nd)\nprint(sorted(_m.keys()))","expected_output":"['bias', 'trees']"},{"test":"import numpy as np\nimport pandas as pd\n_r = np.random.RandomState(0)\n_n = 2000\n_a = _r.normal(size=_n)\n_b = _r.randint(0, 4, _n)\n_c = _r.normal(size=_n)\n_lv = ['v1', 'v2', 'v3', 'v4']\n_X = pd.DataFrame({'f0': _a, 'f1': pd.Categorical.from_codes(_b, categories=_lv), 'f2': _c})\n_y = (_r.rand(_n) < 1 / (1 + np.exp(-(2 * _a + (_b >= 2) * 2.0 - 1.0)))).astype(int)\n_m = fit(_X, _y, 16)\ndef _val(n, x):\n    i = 0\n    while 'value' not in n[i]:\n        s = n[i]\n        go = x[s['feature']] in s['in'] if 'in' in s else x[s['feature']] <= s['threshold']\n        i = s['left'] if go else s['right']\n    return n[i]['value']\n_rows = _X.iloc[:400].to_dict('records')\n_F = np.array([_m['bias'] + sum(_val(t, x) for t in _m['trees']) for x in _rows])\n_p = np.clip(1 / (1 + np.exp(-_F)), 1e-4, 1 - 1e-4)\n_ll = float(-np.mean(_y[:400] * np.log(_p) + (1 - _y[:400]) * np.log(1 - _p)))\n_leaves = sum(1 for t in _m['trees'] for nd in t if 'value' in nd)\nprint(_leaves <= 16)","expected_output":"True"},{"test":"import numpy as np\nimport pandas as pd\n_r = np.random.RandomState(0)\n_n = 2000\n_a = _r.normal(size=_n)\n_b = _r.randint(0, 4, _n)\n_c = _r.normal(size=_n)\n_lv = ['v1', 'v2', 'v3', 'v4']\n_X = pd.DataFrame({'f0': _a, 'f1': pd.Categorical.from_codes(_b, categories=_lv), 'f2': _c})\n_y = (_r.rand(_n) < 1 / (1 + np.exp(-(2 * _a + (_b >= 2) * 2.0 - 1.0)))).astype(int)\n_m = fit(_X, _y, 16)\ndef _val(n, x):\n    i = 0\n    while 'value' not in n[i]:\n        s = n[i]\n        go = x[s['feature']] in s['in'] if 'in' in s else x[s['feature']] <= s['threshold']\n        i = s['left'] if go else s['right']\n    return n[i]['value']\n_rows = _X.iloc[:400].to_dict('records')\n_F = np.array([_m['bias'] + sum(_val(t, x) for t in _m['trees']) for x in _rows])\n_p = np.clip(1 / (1 + np.exp(-_F)), 1e-4, 1 - 1e-4)\n_ll = float(-np.mean(_y[:400] * np.log(_p) + (1 - _y[:400]) * np.log(1 - _p)))\n_leaves = sum(1 for t in _m['trees'] for nd in t if 'value' in nd)\nprint(_ll < 0.55)","expected_output":"True"},{"test":"import numpy as np\nimport pandas as pd\n_r = np.random.RandomState(0)\n_n = 2000\n_a = _r.normal(size=_n)\n_b = _r.randint(0, 4, _n)\n_c = _r.normal(size=_n)\n_lv = ['v1', 'v2', 'v3', 'v4']\n_X = pd.DataFrame({'f0': _a, 'f1': pd.Categorical.from_codes(_b, categories=_lv), 'f2': _c})\n_y = (_r.rand(_n) < 1 / (1 + np.exp(-(2 * _a + (_b >= 2) * 2.0 - 1.0)))).astype(int)\n_m = fit(_X, _y, 16)\ndef _val(n, x):\n    i = 0\n    while 'value' not in n[i]:\n        s = n[i]\n        go = x[s['feature']] in s['in'] if 'in' in s else x[s['feature']] <= s['threshold']\n        i = s['left'] if go else s['right']\n    return n[i]['value']\n_rows = _X.iloc[:400].to_dict('records')\n_F = np.array([_m['bias'] + sum(_val(t, x) for t in _m['trees']) for x in _rows])\n_p = np.clip(1 / (1 + np.exp(-_F)), 1e-4, 1 - 1e-4)\n_ll = float(-np.mean(_y[:400] * np.log(_p) + (1 - _y[:400]) * np.log(1 - _p)))\n_leaves = sum(1 for t in _m['trees'] for nd in t if 'value' in nd)\nprint(_ll < 0.45)","expected_output":"True"}],"approved_user_libraries":["numpy","pandas","scipy","sklearn","lightgbm","xgboost"],"lower_is_better":true,"data_info":"Adult Census Income (registry id `adult-income`, UCI via OpenML): 48,842 rows, 14 columns, about 24% of people earn over $50K.\n\n`fit` receives only the training rows of one task:\n\n- `X_train`: a pandas DataFrame of 20,000 rows and 14 columns. Column names are `f0` to `f13`, in an order that changes per task.\n- Numeric columns are `float64`, with a hidden shift and rescaling that changes per task. There are 6 of them.\n- Categorical columns have dtype `category`, with level names such as `v417` that change per task. There are 8 of them. A missing value is already coded as one more level.\n- `y_train`: a NumPy array of 0 and 1, where 1 means income above $50K.\n\nColumn names and level names are consistent between the training rows and the hidden rows of the same task, and change between tasks, so anything your code needs to know about a column has to come from the rows it receives.","time_limits":{"test":420,"dev":240},"gpu":false,"description":"## Lowest Log Loss on Adult Income with a Leaf Budget\n\nGive gradient boosting as many trees as it wants on Adult Income and most sensible setups land on nearly the same log loss. A size limit changes that. Here you hand over a tree ensemble with a fixed total number of leaves, however you built it, and its log loss on rows your code never sees is your score. Single trees, forests, boosting and anything else you can express as trees all compete on the same budget.\n\n### What you write\n\n```python\ndef fit(X_train, y_train, max_leaves):\n    ...\n    return model\n```\n\n`fit` runs once per task, each time in a fresh process, so nothing carries over from one task to the next. It returns the model as plain data (numbers, strings, lists and dicts):\n\n```python\n{\n    \"bias\": -1.1,\n    \"trees\": [\n        [\n            {\"feature\": \"f3\", \"threshold\": 12.5, \"left\": 1, \"right\": 2},\n            {\"value\": -0.4},\n            {\"feature\": \"f7\", \"in\": [\"v12\", \"v40\"], \"left\": 3, \"right\": 4},\n            {\"value\": 0.2},\n            {\"value\": 0.9},\n        ],\n    ],\n}\n```\n\n- A tree is a list of nodes and its first node is the root. `left` and `right` are indices of later nodes in the same tree, and every node except the root has exactly one parent.\n- A split on a numeric column sends a row left when `x <= threshold`. A split on a categorical column sends a row left when `x` is in the `in` list, and right otherwise, including for a level the list does not mention or the training rows never showed.\n- With $F(x)$ the sum of `bias` and the leaf `value` each tree routes $x$ to, the predicted probability is\n\n$$\np(y = 1 \\mid x) = \\frac{1}{1 + e^{-F(x)}}\n$$\n\n- **The budget:** the total number of leaves across all trees may not exceed `max_leaves`. The bias is free, and there is no limit on the number of trees other than that.\n- `bias`, and every `value`, must be finite with absolute value at most 1e+06.\n\n### How it is graded\n\nEach task draws a new random split of the 48,842 rows of Adult Income: 20,000 go to `fit` and the other 28,842 stay in a separate process that never loads your code. Your model is scored there on those hidden rows, by mean binary cross-entropy in nats with $p$ clipped to $[10^{-4}, 1 - 10^{-4}]$. Your score is the mean over tasks. **Lower is better**, and the lab is passed at **0.309 or below**.\n\n- **Run**: 3 tasks with budgets 32, 64, 128, with per-task results and your printed output shown.\n- **Submit**: 8 tasks with new splits and budgets from 24 to 256, none of which Run uses. Submit reports the mean only and hides your printed output.\n\n### Budgets and rules\n\n- `fit` gets 30 seconds of CPU per task, counted over all threads and worker processes, so more threads or a larger `n_jobs` do not buy more compute. It also has to return within 45 seconds of wall-clock time. Libraries start with one thread per task. Loading your code before that gets 40 seconds.\n- Libraries: numpy, pandas, scipy, sklearn, lightgbm, xgboost, math, itertools, collections, heapq, bisect, random, statistics, time, warnings, typing, copy. Everything else, including file access and any dataset, is refused.\n- Write classes as usual: `self.x = ...` works inside a method defined in a class body. Assigning to or deleting an attribute of anything else (`x.y = ...`) is refused, and so are names that reach modules or object internals (`getattr`, `__dict__` and so on).\n- Anything that reads or writes files is refused too, including library calls such as `to_string`, `export_graphviz`, `save_model` and everything in `feature_extraction`. A run that changes a file under the Python installation fails.\n- Your source is capped at 30,000 characters, 200 numeric literals and 1,500 characters of string constants.\n- An exception out of `fit`, a model that breaks the format or the budget, or a broken cap or time limit fails the run with a score of 9.99.\n","tags":["trees","boosting","random-forest","log-loss","competitive","pml-book"],"id":"39da9139-0981-4b9b-94d9-b088a4d41804","img_type":"full","dataset_id":"adult-income","difficulty":"hard","evaluation_metric":"log_loss","min_eval_metric":0.309,"category":"Machine Learning","dataset":"Adult Census Income, a new hidden split per task","title":"Lowest Log Loss on Adult Income with a Leaf Budget","time_limits_seconds":{"dev":240,"test":420}},{"created_at":"2026-10-28T18:54:19.994000+00:00","description":"## Goal\n\nYou get 10,000 unlabeled Fashion-MNIST images and one labeled example of each of the 10 classes. Each round you may ask an oracle for the labels of **10** more pool images; there are **9** rounds, so you end with 100 labels. After every round the harness retrains **its own** classifier on everything labeled so far and measures accuracy on held-out images. You control only which images get labeled. Choose queries that make that classifier accurate as early as possible.\n\n## What you write\n\n```python\ndef select(X_pool, labeled_idx, y_labeled, k, round_idx, pool_proba):\n    return [...]  # k distinct pool indices, none of them already labeled\n```\n\n- `X_pool`: float32 array of shape (10000, 784), pixels in [0, 1], read-only. The same array object is passed in every round of a draw, so you can cache work that depends only on the pool.\n- `labeled_idx`: int array of the pool indices labeled so far (10 in round 1, 20 in round 2, ...); `y_labeled`: their labels 0-9, in the same order.\n- `k`: always 10. `round_idx`: 1 to 9.\n- `pool_proba`: array of shape (10000, 10), the harness classifier's current predicted class probabilities for every pool image.\n\nInside `select` you may do anything: fit your own models, ensembles or posterior samples, cluster, embed, score. You may use numpy, scikit-learn or torch.\n\n## The harness's classifier (fixed, the same for everyone)\n\nThe pool is projected onto its first 50 principal components (pool mean removed, scaled so the first component has unit variance). On top of that sits multinomial logistic regression with an L2 penalty (lambda/2)·||W||² on the weights (lambda = 0.3; intercepts are almost unpenalised), fitted to its unique optimum by Newton's method with a line search. Because the model is fixed, the score measures only your queries.\n\n## Score\n\nThe score is the area under the learning curve: the mean test accuracy after 20, 40, 60, 80 and 100 labels, averaged over independent draws. Each draw has a fresh 10,000-image pool, fresh seed labels and a 5,000-image evaluation set. Higher is better. **Floor: 0.652.** Uniform random queries score about 0.62 on Submit (single random runs range from about 0.605 to 0.635).\n\n- **Run:** 2 draws. Pool and evaluation images both come from the training split.\n- **Submit:** 6 other draws, evaluated on the held-out test split.\n\nThe report shows your curve, the score of a fixed-seed random query sequence on the same draws (`random_reference_aulc`), your gain over it, accuracy with only the 10 seed labels, your `select` time per draw, and the smallest and largest per-class label counts you collected.\n\n## Rules (breaking one sets the score to 0)\n\n- Return exactly `k` distinct integer indices in [0, 10000) that are not already labeled.\n- `select` may use at most 75 seconds per draw, summed over its 9 calls.\n- Labels reach you only through `y_labeled`. Your code may not load data (`dml_data`, files, the network, `np.load`, scikit-learn dataset fetchers) and may not use introspection (`getattr`, `globals`, `vars`, `sys`, `os`).\n","type":"general","tags":["active-learning","bald","pool-based","fashion-mnist","competitive","pml-book"],"id":"3cb4725b-cb25-47d9-a2d7-a1acf9865e93","img_type":"full","test_cases":[{"test":"\nimport numpy as np\n_r = np.random.default_rng(5)\n_A = np.clip(0.3 + 0.05 * _r.standard_normal((290, 784)), 0, 1)\n_B = np.clip(0.9 + 0.05 * _r.standard_normal((10, 784)), 0, 1)\n_B[:, :392] = 0.0\n_X = np.vstack([_A, _B]).astype(np.float32)\n_X.flags.writeable = False\n_P = np.full((300, 10), 0.1)\n_P[:290] = 0.01\n_P[np.arange(290), np.arange(290) % 10] = 0.91\n_li = np.arange(10)\n_out = [int(i) for i in np.asarray(select(_X, _li, np.arange(10), 10, 1, _P)).reshape(-1)]\nprint(len(_out) == 10 and len(set(_out)) == 10 and min(_out) >= 0 and max(_out) < 300)","expected_output":"True"},{"test":"\nimport numpy as np\n_r = np.random.default_rng(5)\n_A = np.clip(0.3 + 0.05 * _r.standard_normal((290, 784)), 0, 1)\n_B = np.clip(0.9 + 0.05 * _r.standard_normal((10, 784)), 0, 1)\n_B[:, :392] = 0.0\n_X = np.vstack([_A, _B]).astype(np.float32)\n_X.flags.writeable = False\n_P = np.full((300, 10), 0.1)\n_P[:290] = 0.01\n_P[np.arange(290), np.arange(290) % 10] = 0.91\n_li = np.arange(0, 40, 2)\n_out = [int(i) for i in np.asarray(select(_X, _li, np.arange(20) % 10, 5, 2, _P)).reshape(-1)]\nprint(len(_out) == 5 and not (set(_out) & set(_li.tolist())))","expected_output":"True"},{"test":"\nimport numpy as np\n_r = np.random.default_rng(5)\n_A = np.clip(0.3 + 0.05 * _r.standard_normal((290, 784)), 0, 1)\n_B = np.clip(0.9 + 0.05 * _r.standard_normal((10, 784)), 0, 1)\n_B[:, :392] = 0.0\n_X = np.vstack([_A, _B]).astype(np.float32)\n_X.flags.writeable = False\n_P = np.full((300, 10), 0.1)\n_P[:290] = 0.01\n_P[np.arange(290), np.arange(290) % 10] = 0.91\n# all 10 labels sit in region A, where the classifier is confident; region B (indices 290-299)\n# is a separate group of 10 images that nobody has labeled and the classifier knows nothing about\n_li = np.arange(10)\n_out = [int(i) for i in np.asarray(select(_X, _li, np.arange(10), 5, 1, _P)).reshape(-1)]\nprint(any(i >= 290 for i in _out))","expected_output":"True"}],"dataset_id":"fashion-mnist","lower_is_better":false,"evaluation_metric":"AULC (mean test accuracy at 20-100 labels)","data_info":"Fashion-MNIST from the dml_data registry (id fashion-mnist), read only by the harness. Per draw: 10,000 pool images (float32 (10000, 784) in [0, 1]), one seed label per class, 5,000 evaluation images. Run: 2 draws from the training split. Submit: 6 draws, pools from the training split and evaluation images from the test split.","time_limits":{"test":600,"dev":240},"difficulty":"hard","approved_user_libraries":["numpy","sklearn","torch","math","random","collections","itertools","functools","time","copy"],"min_eval_metric":0.652,"category":"Machine Learning","title":"Best Learning Curve on a 100-Label Budget","dataset":"Fashion-MNIST","gpu":false,"time_limits_seconds":{"dev":240,"test":600}},{"created_at":"2026-10-26T15:20:01.954000+00:00","description":"Write the fastest CUDA kernel you can for the most basic reduction there is: add up 67 million floats. The yardstick is NVIDIA's own CUB library, whose `cub::DeviceReduce::Sum` is timed against yours on the same GPU, on the same data, in the same run. The leaderboard ranks by **speedup** = CUB's time / your time, higher is better. Matching CUB scores 1.0; beating it scores more.\n\n**Contract.** Your file must define\n\n```cpp\nextern \"C\" void array_sum(const float* x, int n, float* out);\n```\n\n`x` and `out` are **device** pointers that the harness already allocated: `x` holds `n` floats, `out` one float. When every piece of work your function launched has finished, `out[0]` must hold the sum. You may launch any number of kernels, on any streams, with any grid you like, allocate scratch memory (and keep it in a `static` between calls), and use anything in the CUDA runtime and the CUDA C++ language. `out` holds garbage when you are called, so set it yourself if your method accumulates into it.\n\n**Data.** $n = 2^{26}$ (256 MB of float32). Before every timed call the harness refills `x` on the device with new pseudo-random values in $[0, s)$, with a scale $s$ that changes every round, so each call has a different answer.\n\n**Score.** Each round times one CUB call and one call to your function with a host clock around the call and a full `cudaDeviceSynchronize()`, so all work on every stream counts. The score is the median CUB time over the median of yours. Run: 10 rounds. Submit: 30 rounds with different data. Clearing a speedup of 0.1 counts as solved; everything above that is leaderboard. The provided starter is correct but scores about 0.01.\n\n**Gates.** The score is 0 (a failed run) if any round's result is off from the exact (float64) sum by a relative error above $10^{-4}$, is NaN, or raises a CUDA error; if your source contains `cub/`, `cub::`, `thrust`, `cublas`, `cutlass`, `dlopen` or `dlsym` anywhere (comments included), or an `#include` that names its header through a macro; if there is no `extern \"C\" array_sum`; or if the timing loop runs past its budget. The reduction has to be your own kernel code.","tags":["cuda","reduction","memory-bandwidth","performance","open-ended","leaderboard"],"type":"general","id":"3d1f81c4-9b98-42cb-ad0c-10506c378bd4","dataset_id":"synthetic","img_type":"cuda","evaluation_metric":"speedup","difficulty":"medium","data_info":"No dataset: the harness allocates 2^26 floats (256 MB) on the T4 and refills them on the device before every round with hashed uniform values in [0, s), s changing per round. Run: 10 timed rounds; Submit: 30 rounds with different seeds. Both compile a small helper library with nvcc (about 7 s) besides your file.","lower_is_better":false,"time_limits":{"test":300,"dev":180},"min_eval_metric":0.1,"example":{"input":"array_sum(x, n, out) with x a device array of n = 2^26 floats and out a device float, called once per round on fresh data","output":"speedup = median CUB time / median array_sum time: about 0.01 for the one-block starter, about 1.0 for a kernel that matches CUB"},"category":"GPU Kernels","dataset":"2^26 float32 values generated on the GPU each round","title":"Fastest Array Sum","gpu":true,"time_limits_seconds":{"dev":180,"test":300}},{"created_at":"2026-07-26T16:11:10.364000+00:00","type":"general","constraints":["numpy only (no sklearn, pandas, scipy, torch, or network access)","Whatever you fit must use only the training fold","Return (test_predictions, train_idx, val_idx, test_idx); the index arrays must partition the rows"],"last_updated":"2026-09-17T01:57:44.472729+00:00","test_cases":[{"test":"print(callable(split_and_baseline))","expected_output":"True"},{"test":"import numpy as np\nX = np.arange(20.0).reshape(10, 2)\ny = np.arange(10.0)\nout = split_and_baseline(X, y, 0.6, 0.2, 0.2, 0)\nidx = np.concatenate([np.asarray(out[1]), np.asarray(out[2]), np.asarray(out[3])])\nprint(sorted(idx.tolist()) == list(range(10)))","expected_output":"True"},{"test":"import numpy as np\nX = np.arange(20.0).reshape(10, 2)\ny = np.arange(10.0)\nout = split_and_baseline(X, y, 0.6, 0.2, 0.2, 0)\nprint(len(np.asarray(out[0])) == len(np.asarray(out[3])))","expected_output":"True"}],"approved_user_libraries":["numpy"],"lower_is_better":true,"time_limits":{"test":120,"dev":60},"data_info":"Synthetic linear regression data generated inside the grader with numpy only (no downloads): X ~ N(0,1), y = X w + 3 + Gaussian noise; (2000, 8) on Submit, (400, 4) on Run.","example":{"input":"X.shape=(10, 2), y=np.arange(10.0), train_frac=0.6, val_frac=0.2, test_frac=0.2, seed=0","output":"test_predictions of length 2, and three index arrays of sizes about 6, 2 and 2 that together cover 0..9 exactly once"},"model_specs":"Your choice. Any predictor fitted on the training fold only; the grader compares its test-fold MAE with a train-mean baseline.","gpu":false,"description":"# Split the Data Honestly and Beat a Baseline\n\nYou are handed a regression dataset `X` (rows are examples) and targets `y`. Divide it into training, validation and test folds, fit any predictor you like on the training fold only, and return its predictions for the test fold together with the three folds.\n\n```python\ndef split_and_baseline(X, y, train_frac, val_frac, test_frac, seed):\n    ...\n    return test_predictions, train_idx, val_idx, test_idx\n```\n\n- `test_predictions`: a 1-D array with one prediction per row of the test fold, in the order of `test_idx`.\n- `train_idx`, `val_idx`, `test_idx`: 1-D integer arrays that together contain every row index exactly once.\n- `seed` is yours to use however you want, so that the same call gives the same folds twice.\n\nHow you shuffle, how you round the fold sizes, and what you fit are all your decisions. A constant predictor, a least-squares line, a nearest-neighbor average: anything goes, as long as it only ever sees the training rows.\n\n## How it is graded\n\nThe grader builds its own data, calls your function, and checks three things:\n\n- the three folds are a partition of the rows, and each fold's size is within a few rows of the requested fraction;\n- the mean absolute error of your test predictions against the test targets is no worse than that of a predictor that always outputs the mean of the training targets (with a small margin);\n- the reported metric is that mean absolute error, so lower is better.\n\nOnly numpy is available. There is no network access.\n","tags":["numpy","train-test-split","baseline","mae","supervised-learning","evaluation"],"id":"3d26c3f9-cb73-4ab1-bc4d-86cfab2af6d1","difficulty":"easy","evaluation_metric":"mae","schema":"split_and_baseline(X: np.ndarray (n_samples, n_features), y: np.ndarray (n_samples,), train_frac: float, val_frac: float, test_frac: float, seed: int) -> (test_predictions: np.ndarray (n_test,), train_idx, val_idx, test_idx: 1-D int arrays partitioning range(n_samples))","min_eval_metric":2.3,"category":"Machine Learning","title":"Split the Data Honestly and Beat a Baseline","time_limits_seconds":{"dev":60,"test":120}},{"description":"Implement a NumPy-based `loss_function` that operates on class **probabilities** (softmax outputs) and integer class targets, returning **both** the loss value and the gradient with respect to the probabilities. You may use **any differentiable classification loss** you like.","constraints":["Return both loss and gradient w.r.t. probabilities (same shape as preds)."],"id":"4","test_cases":[{"test":"import numpy as np\npreds = np.array([[0.7, 0.2, 0.1]])\ntarget = np.array([0])\nloss, grad = loss_function(preds, target)\nprint(loss > 0 and grad.shape == preds.shape)","expected_output":"True"},{"test":"import numpy as np\npreds = np.array([[0.9, 0.05, 0.05]])\ntarget = np.array([0])\nloss, grad = loss_function(preds, target)\nwrong_preds = np.array([[0.9, 0.05, 0.05]])\nwrong_target = np.array([1])\nloss, grad = loss_function(preds, target)\nloss_wrong, grad_wrong = loss_function(wrong_preds, wrong_target)\n\nloss_close = loss < loss_wrong\nprint(loss_close)","expected_output":"True"},{"test":"import numpy as np\n# Grad should not be the same for all classes\npreds = np.array([[0.25,0.25,0.25,0.25]])\ntarget = np.array([1])\nloss, grad = loss_function(preds, target)\nprint(np.allclose(grad[0], grad[0,0]))","expected_output":"False"},{"test":"import numpy as np\n# Loss should decrease when prediction confidence for true class increases\npreds_low = np.array([[0.4,0.3,0.3]])\npreds_high = np.array([[0.9,0.05,0.05]])\ntarget = np.array([0])\nloss_low, _ = loss_function(preds_low, target)\nloss_high, _ = loss_function(preds_high, target)\nprint(loss_high < loss_low)\n","expected_output":"True"}],"approved_user_libraries":["numpy"],"difficulty":"hard","evaluation_metric":"Accuracy","data_info":"MNIST 28x28 grayscale digits (10 classes). Inputs scaled to [0,1] and reshaped to (N,1,28,28).","time_limits":{"test":"200 seconds","dev":"60 seconds"},"schema":"practical_question_v1","min_eval_metric":0.8,"example":{"input":{"target":[1,0,2,2],"preds":{"0":[0.1,0.7,0.2],"3":[0.05,0.05,0.9],"1":[0.8,0.1,0.1],"2":[0.2,0.3,0.5]}},"output":{"loss_mean":"≈ 0.43","d_preds":{"0":[0.0,-0.3571,0.0],"3":[0.0,0.0,-0.2778],"1":[-0.3125,0.0,0.0],"2":[0.0,0.0,-0.5]}}},"category":"Loss Functions","dataset":"MNIST","title":"MNIST: Classification Loss (with Gradient)","model_specs":"Small CNN: two Conv→ReLU→MaxPool blocks, then Linear→ReLU→Linear(10). Batch size: 128, Optimizer: Adam lr=1e-3, epochs: 2.","memory_limit":"2 GB","createdAt":"2026-05-13T21:01:43.828000+00:00","time_limits_seconds":{"dev":60,"test":200},"type":"epoch","lower_is_better":false,"gpu":false},{"created_at":"2026-11-06T15:24:25.374000+00:00","type":"general","constraints":["class Router with __init__(n_experts, k), route(logits (M, n, E), training) -> (expert_ids, gates) of shape (M, n, k), backward(grad_gates) -> grad_logits (M, n, E)","each task has 480 units of training time; a step costs 1 + MaxVio/2","mean training MaxVio (second half) <= 0.75 and mean validation MaxVio <= 0.1 in every task, else the run is not scored","score: mean validation KL to the exact next-token distribution (nats/token), lower is better, pass at <= 0.16","route + backward at most 20 s per task; numpy only","attribute assignment only on self inside a method of a class"],"test_cases":[{"description":"route returns ids and gates of shape (M, n, k), k different experts per token, gates in [0, 4]","test":"import numpy as np\n_rng = np.random.default_rng(0)\n_R = Router(16, 2)\n_z = _rng.standard_normal((32, 16, 16)).astype(np.float32)\n_ids, _g = _R.route(_z, True)\n_ids, _g = np.asarray(_ids), np.asarray(_g, dtype=float)\n_s = np.sort(_ids.reshape(-1, 2), axis=1)\nprint(_ids.shape == (32, 16, 2) and _g.shape == (32, 16, 2) and bool(np.all(_s[:, 0] != _s[:, 1])) and int(_ids.min()) >= 0 and int(_ids.max()) <= 15 and bool(np.all(np.isfinite(_g))) and float(_g.min()) >= 0 and float(_g.max()) <= 4)","expected_output":"True"},{"description":"backward returns a finite gradient of shape (M, n, E)","test":"import numpy as np\n_rng = np.random.default_rng(0)\n_R = Router(16, 2)\n_z = _rng.standard_normal((32, 16, 16)).astype(np.float32)\n_ids, _g = _R.route(_z, True)\n_ids, _g = np.asarray(_ids), np.asarray(_g, dtype=float)\n_d = np.asarray(_R.backward(_rng.standard_normal((32, 16, 2)).astype(np.float32)))\nprint(_d.shape == (32, 16, 16) and bool(np.all(np.isfinite(_d))))","expected_output":"True"},{"description":"on its own (logits that never learn), a stream of steps where 4 experts are strongly favoured ends up with a mean MaxVio of at most 0.75 over the last 50 of 300 steps. An aux-loss-only router fails this check, because an aux loss only acts through training.","test":"import numpy as np\n_rng = np.random.default_rng(1)\n_R = Router(16, 2)\n_b = np.zeros(16, dtype=np.float32)\n_b[:4] = 2.0\n_mv = []\nfor _s in range(300):\n    _z = (_rng.standard_normal((32, 16, 16)) + _b).astype(np.float32)\n    _ids, _g = _R.route(_z, True)\n    _R.backward(np.zeros((32, 16, 2), dtype=np.float32))\n    _c = np.bincount(np.asarray(_ids).reshape(-1), minlength=16)\n    _mv.append(_c.max() / _c.mean() - 1)\nprint(bool(np.mean(_mv[-50:]) <= 0.75))","expected_output":"True"}],"lower_is_better":true,"approved_user_libraries":["numpy"],"data_info":"No dataset: the grader generates everything from seeds only it holds. 16 domains, each a sparse Markov chain over a shared 96-token vocabulary favouring its own tokens; windows of 8 tokens, each from a fresh text. A training step is 32 single-domain micro-batches of 16 windows; the domain of each micro-batch is drawn from the task's mix. Your Router sees only the router logits (float32, shape (M, n, E)) and, after each training step, the gradient of the loss with respect to its gates. Run: 2 tasks (even mix, mild skew). Submit: 3 tasks with new worlds and skewed mixes (steep Zipf, one domain at 40%, half the domains arriving after 40% of the budget). Validation: 8,192 new windows per task, scored by KL to the exact next-token distribution.","time_limits":{"test":150,"dev":120},"gpu":false,"description":"## Best Balanced Router\n\nWrite the router of a mixture-of-experts layer. The grader trains a small MoE language model on text from 16 domains, and your `Router` decides, at every training step, which 2 of the 16 experts each token goes to and how much weight each one gets. The lowest validation loss wins, as long as you keep the experts' load balanced: an uneven load slows training down, and a load that stays too uneven is not scored at all.\n\nAny routing and balancing policy is allowed: an auxiliary loss, a loss-free bias, quantile or capacity-based assignment, your own idea, or a mix.\n\n### The model and the data\n\n- **Text.** A vocabulary of 96 tokens shared by 16 domains. Each domain writes with its own rules (its own Markov chain, favouring its own subset of tokens), so a few tokens of context say which domain you are in, and the domain says what comes next.\n- **The model** (the grader owns it): the last 8 tokens are embedded and mixed into a hidden vector $h$ of size 64. One MoE layer adds $\\sum_i g_i \\, \\mathrm{expert}_i(h)$ over the 2 chosen experts, each a small 64 to 16 to 64 GELU network, and a linear head predicts the next token. The router's logits are $z = W_r h$, one per expert. The grader trains everything, including $W_r$, with Adam, and $W_r$ learns from the gradient your `backward` returns.\n- **Steps.** A training step is 32 micro-batches of 16 token windows (512 tokens). Every micro-batch comes from **one** domain, drawn from the task's domain mix, and every window from a fresh text, so no window holds another window's next token.\n\n### What you write\n\n```python\nclass Router:\n    def __init__(self, n_experts, k):                # 16 and 2\n        ...\n\n    def route(self, logits, training):\n        # logits: float32 array (M, n, E) = (32, 16, 16), one step's router logits\n        ...\n        return expert_ids, gates                     # each of shape (M, n, k)\n\n    def backward(self, grad_gates):\n        # grad_gates: float32 (M, n, k), d(training loss) / d(gates) for the last route() call\n        ...\n        return grad_logits                           # (M, n, E): the gradient to apply to the logits\n```\n\n- `expert_ids` are whole numbers from 0 to 15, and each token's 2 experts must be different. `gates` are finite numbers from 0 to 4, used as given.\n- On every training step the grader calls `route(logits, True)`, runs the layer with your choices, and calls `backward` once. `grad_logits` is whatever you want the router to learn: the LM loss's gradient through your gating function, plus any balancing loss you add. Return zeros to freeze $W_r$.\n- On validation steps it calls `route(logits, False)` only.\n- Each task gets a fresh `Router`, so state you keep on `self` lasts for one task. Your class runs in its own process and only ever sees logits and gate gradients: no tokens, no targets, no model.\n\n### Time and balance\n\n- **MaxVio** of a step is $\\max_e c_e / \\bar c - 1$, where $c_e$ counts the assignments expert $e$ got over the whole step (all 32 micro-batches, which are dispatched to the experts together) and $\\bar c$ is the mean. 0 is perfectly even.\n- **Each task has 480 units of training time, and a step costs $1 + \\mathrm{MaxVio}/2$ units**: half of a step is fixed work and half is expert work, which the busiest expert sets. Training stops when the time is spent (at most 480 steps), so a router at MaxVio 1 gets about two thirds of the steps of an even one.\n- **Ceilings.** The mean MaxVio over the training steps in the second half of the budget must be at most **0.75**, and the mean over the validation steps at most **0.1**, in every task. A run that breaks either ceiling is not scored and fails; the report still shows the KL it would have had (`kl_unscored`) and which task broke which ceiling.\n\n### How it is graded\n\nThe score is the **validation KL**, in nats per token, averaged over the tasks. For each task the grader trains a fresh model with your router, then scores 8,192 new windows from the task's final domain mix, packed the same way as training. Because the grader knows every domain's rules, it computes the exact next-token distribution of each window, $p$, and the score is $\\mathrm{KL}(p \\,\\|\\, q)$ against the model's prediction $q$: no sampled labels, so no luck in it. 0 would be a perfect model. **Lower is better**, and the lab is passed at **0.16 or below**.\n\n- **Run**: 2 tasks: even mix (every domain equally common) and mild skew (a gentle Zipf skew).\n- **Submit**: 3 tasks with worlds (domain rules) Run never uses and domain mixes Run never shows: a steep Zipf skew, one domain making up 40% of the text, and a run where only half the domains exist for the first 40% of the budget and all 16 follow, in a skewed mix.\n\nThe report lists, per task, the KL, both MaxVio means, the steps the budget bought, the last training loss and the seconds your Router used.\n\n**The score barely moves between runs.** Every seed is fixed and the model trains on one CPU thread, so on the same machine the same code gets the same score. Different machines can round a few floating-point operations differently, and training amplifies that: in calibration, four Submits of the same router usually agreed to every printed decimal, and when the machine changed, a score moved by up to about 0.004 (on a Windows laptop, one router moved by 0.006). Compare ideas by more than the third decimal.\n\n### Budgets and rules\n\n- Your `route` and `backward` together may use 20 seconds per task, and no single call more than 10 seconds. The reference solution uses about 1.5 seconds per task. A Submit takes about 40 seconds.\n- Libraries: numpy, plus small standard-library helpers (math, random, collections, itertools, heapq, bisect, statistics, typing, enum, abc, copy).\n- Write classes the ordinary way: assigning to `self.anything` inside a method is fine. Outside a method, assigning to an attribute is refused, so keep other state in local variables, lists or dicts.\n- Refused: reading or writing files, `os`, `sys`, dynamic access (`getattr`, `setattr`, `vars`, `globals`, `exec`, names starting with two underscores other than the usual methods, private attributes such as `np._core`), and text or byte converters. A file can carry at most 10,000 characters of code (comments and docstrings do not count), 300 numbers, 400 characters of strings and 200 names you define.\n\nA refused file, an exception, a malformed result, a ceiling broken or a budget missed fails the run.\n","tags":["mixture-of-experts","moe","router","load-balancing","maxvio","aux-loss","loss-free-bias","quantile-balancing","expert-parallelism","competitive"],"id":"42c9e12c-3e60-4e90-bc35-7f7fe6f0fb32","img_type":"pytorch","dataset_id":"synthetic","evaluation_metric":"kl","difficulty":"hard","min_eval_metric":0.16,"category":"Mixture of Experts","title":"Best Balanced Router","dataset":"Multi-domain token streams generated by the grader","time_limits_seconds":{"dev":120,"test":150}},{"created_at":"2026-10-28T19:05:56.137000+00:00","type":"general","test_cases":[{"test":"import numpy as np\ndef _inst(seed, N, D, k, sigma=0.001, scales=None):\n    r = np.random.default_rng(seed)\n    X = r.standard_normal((N, D)) / np.sqrt(N)\n    if scales is not None:\n        X = X * np.exp(r.uniform(-np.log(scales), np.log(scales), D))\n    w = np.zeros(D)\n    S = r.choice(D, k, replace=False)\n    w[S] = r.choice([-1.0, 1.0], k) * r.uniform(0.5, 1.5, k)\n    return X, X @ w + sigma * r.standard_normal(N), w, S\nX, y, w, S = _inst(1, 80, 200, 5)\nout = np.asarray(recover(X.copy(), y.copy(), np.arange(200)), dtype=float)\nprint(out.shape == (200,), bool(np.all(np.isfinite(out))))","expected_output":"True True"},{"test":"import numpy as np\ndef _inst(seed, N, D, k, sigma=0.001, scales=None):\n    r = np.random.default_rng(seed)\n    X = r.standard_normal((N, D)) / np.sqrt(N)\n    if scales is not None:\n        X = X * np.exp(r.uniform(-np.log(scales), np.log(scales), D))\n    w = np.zeros(D)\n    S = r.choice(D, k, replace=False)\n    w[S] = r.choice([-1.0, 1.0], k) * r.uniform(0.5, 1.5, k)\n    return X, X @ w + sigma * r.standard_normal(N), w, S\nX, y, w, S = _inst(2, 60, 400, 8)\nout = np.asarray(recover(X.copy(), y.copy(), np.arange(400)), dtype=float).ravel()\nprint(\"largest 8 coefficients are the true support:\", set(np.argsort(-np.abs(out))[:8].tolist()) == set(S.tolist()))","expected_output":"largest 8 coefficients are the true support: True"},{"test":"import numpy as np\ndef _inst(seed, N, D, k, sigma=0.001, scales=None):\n    r = np.random.default_rng(seed)\n    X = r.standard_normal((N, D)) / np.sqrt(N)\n    if scales is not None:\n        X = X * np.exp(r.uniform(-np.log(scales), np.log(scales), D))\n    w = np.zeros(D)\n    S = r.choice(D, k, replace=False)\n    w[S] = r.choice([-1.0, 1.0], k) * r.uniform(0.5, 1.5, k)\n    return X, X @ w + sigma * r.standard_normal(N), w, S\nX, y, w, S = _inst(3, 120, 400, 10)\nout = np.asarray(recover(X.copy(), y.copy(), np.arange(400)), dtype=float).ravel()\nsnr = 10 * np.log10(np.sum(w ** 2) / np.sum((out - w) ** 2))\nprint(\"recovery SNR above 30 dB:\", bool(snr > 30))","expected_output":"recovery SNR above 30 dB: True"},{"test":"import numpy as np\ndef _inst(seed, N, D, k, sigma=0.001, scales=None):\n    r = np.random.default_rng(seed)\n    X = r.standard_normal((N, D)) / np.sqrt(N)\n    if scales is not None:\n        X = X * np.exp(r.uniform(-np.log(scales), np.log(scales), D))\n    w = np.zeros(D)\n    S = r.choice(D, k, replace=False)\n    w[S] = r.choice([-1.0, 1.0], k) * r.uniform(0.5, 1.5, k)\n    return X, X @ w + sigma * r.standard_normal(N), w, S\nX, y, w, S = _inst(4, 150, 400, 10, scales=5.0)\nout = np.asarray(recover(X.copy(), y.copy(), np.arange(400)), dtype=float).ravel()\nsnr = 10 * np.log10(np.sum(w ** 2) / np.sum((out - w) ** 2))\nprint(\"unequal column scales, SNR above 20 dB:\", bool(snr > 20))","expected_output":"unequal column scales, SNR above 20 dB: True"}],"lower_is_better":false,"approved_user_libraries":["numpy","scipy","sklearn"],"data_info":"Synthetic compressed-sensing instances generated inside the grader (no dataset): y = X w* + noise with N < D (D in {2048, 4096}, N from 250 to 1024). Families: Gaussian sensing (the book's Fig 11.13 setting and harder), very few measurements, correlated columns (AR(1) neighbours or shared factors), +-1 sensing with unequal column scales, sparse groups, heavy noise, compressible power-law signals. Run: 7 instances; Submit: 8 different instances with other seeds and sizes, including two families Run does not show.","time_limits":{"test":400,"dev":300},"example":{"input":"recover(X (500 x 2048 sensing matrix), y (500 measurements), groups (np.arange(2048)))","output":"w_hat, an array of 2048 coefficients; Submit mean recovery SNR about 1 dB for the minimum-norm starter and 7 dB for the book's Figure 11.13 recipe (lasso at 0.1 lambda_max, then least squares on its support); the floor is 16 dB"},"gpu":false,"description":"The book measures a sparse signal of $D = 4096$ coefficients with only $N = 1024$ random linear measurements: 160 spikes, a little noise, and the question of how to get $w^*$ back from $y = Xw^* + \\epsilon$ when there are four times more unknowns than equations. The minimum-norm solution is hopeless (MSE 0.0292), the lasso finds the spikes but shrinks them (0.0027), and least squares on the lasso's support nails it (3.3e-5). That setting turns out to be easy. Your job is to recover sparse signals in harder ones, as accurately as you can.\n\n## The instances\n\nEvery instance is $y = X w^* + \\epsilon$ with $N < D$: $D$ is 2048 or 4096 and $N$ is between 250 and 1024. The noise is Gaussian, at a measurement signal-to-noise ratio between 12 and 40 dB. The instances come from these families:\n\n- **Random Gaussian sensing**, the book's setting, with anywhere from a few dozen to a few hundred non-zero coefficients.\n- **Very few measurements**: $N$ is a small fraction of $D$.\n- **Correlated columns**: neighbouring columns of $X$ are strongly correlated, or every column shares a few hidden factors.\n- **Unequal column scales**: a $\\pm 1$ sensing matrix whose columns have very different norms.\n- **Sparse groups**: the coefficients come in contiguous groups; only a few groups are active, and only part of each active group is non-zero.\n- **Heavy noise**: a measurement SNR of about 12 dB.\n- **Compressible**: no coefficient is exactly zero; the magnitudes decay like a power law.\n\nNon-zero values have a random sign and random magnitude. You are never told the number of non-zeros, the noise level or the family.\n\n## Your function\n\n```python\ndef recover(X, y, groups):\n    ...\n    return w_hat   # numpy array, shape (D,)\n```\n\n- `X`: float array of shape (N, D), the sensing matrix.\n- `y`: float array of shape (N,), the measurements.\n- `groups`: int array of shape (D,); `groups[j]` is the group of coefficient `j`. Group-structured instances have contiguous groups of equal size. On every other instance each coefficient is its own group (`groups = np.arange(D)`).\n- Return your estimate of $w^*$: `D` finite numbers.\n\nApproved libraries: numpy, scipy, scikit-learn. CPU only.\n\n## Score (higher is better)\n\nFor each instance the grader computes the **recovery SNR** in decibels,\n\n$$\\text{SNR} = 10 \\log_{10} \\frac{\\lVert w^* \\rVert_2^2}{\\lVert \\hat{w} - w^* \\rVert_2^2},$$\n\nclipped to the range 0 to 60 dB. The score is the mean over the instances. Returning all zeros scores 0 dB, the minimum-norm solution about 1 dB, and every 10 dB more is ten times less squared error. **Run** scores 7 practice instances. **Submit** scores 8 other instances (other sizes and seeds, and two families that Run does not include), and that mean is your score. You pass at a mean recovery SNR of **16 dB** or higher; above that, higher ranks higher.\n\n## Budget and gates\n\n`recover` gets 30 seconds per instance. The run fails with score 0 if `recover` raises, goes over the budget on any instance, returns the wrong number of coefficients, or returns a value that is not finite.\n\nThe report shows, per instance: your recovery SNR, the minimum-norm solution's, the **support oracle's** (least squares on the true non-zero coefficients, or on the $N/4$ largest ones for the compressible instance; a practical ceiling), how many non-zeros you returned, and your time.","tags":["lasso","sparsity","compressed-sensing","debiasing","group-lasso","linear-regression","open-ended","leaderboard"],"id":"436dd6c5-4f42-4b18-a955-6b0ac91af13f","img_type":"full","dataset_id":"synthetic","evaluation_metric":"recovery_snr_db","difficulty":"hard","min_eval_metric":16.0,"category":"Regression","title":"Recover the Sparse Signal","dataset":"Synthetic compressed-sensing instances (generated in the grader)","time_limits_seconds":{"dev":300,"test":400}},{"created_at":"2026-09-06T15:22:20.373240+00:00","type":"general","constraints":["Implement exactly three top-level functions: init_aux_params(d_model, vocab_size, seed), latent_objective(h, x, mask, params, aux), latent_transition(h, x_emb, aux)","Do not modify the transformer, the optimizer, the data, or the decoding procedure; the harness owns them","latent_objective must return a finite 0-dim torch tensor; it is added to the cross-entropy every step","latent_transition must be deterministic and accept inputs of shape (..., d_model); the harness verifies speculative output equals greedy output","If you use params['head_w'] / params['head_b'] inside the objective, detach them; the output head trains only through the harness cross-entropy","The score counts only if validation cross-entropy stays <= 2.05 nats per character on Submit (2.5 on Run); degrading the language model to inflate acceptance scores 0","CPU-only tensors; only numpy and torch may be imported; keep the objective cheap (dev budget 120s, submit budget 300s including training)"],"test_cases":[{"test":"import torch, torch.nn.functional as F, numpy as np\ntorch.manual_seed(0)\nd, V = 64, 79\nparams = {'wte': torch.randn(V, d) * 0.02, 'head_w': (torch.randn(d, V) * 0.02).requires_grad_(True), 'head_b': torch.zeros(V, requires_grad=True)}\ndef output_head(h, p):\n    return h @ p['head_w'] + p['head_b']\naux = init_aux_params(d, V, 0)\nprint(isinstance(aux, dict) and len(aux) > 0 and all(torch.is_tensor(v) and v.dtype == torch.float32 and v.requires_grad for v in aux.values()))","expected_output":"True"},{"test":"import torch, torch.nn.functional as F, numpy as np\ntorch.manual_seed(0)\nd, V = 64, 79\nparams = {'wte': torch.randn(V, d) * 0.02, 'head_w': (torch.randn(d, V) * 0.02).requires_grad_(True), 'head_b': torch.zeros(V, requires_grad=True)}\ndef output_head(h, p):\n    return h @ p['head_w'] + p['head_b']\naux = init_aux_params(d, V, 0)\nh = torch.randn(5, d); e = torch.randn(5, d)\nout = latent_transition(h, e, aux)\nprint(tuple(out.shape) == (5, d), tuple(latent_transition(torch.randn(2, 7, d), torch.randn(2, 7, d), aux).shape) == (2, 7, d))","expected_output":"True True"},{"test":"import torch, torch.nn.functional as F, numpy as np\ntorch.manual_seed(0)\nd, V = 64, 79\nparams = {'wte': torch.randn(V, d) * 0.02, 'head_w': (torch.randn(d, V) * 0.02).requires_grad_(True), 'head_b': torch.zeros(V, requires_grad=True)}\ndef output_head(h, p):\n    return h @ p['head_w'] + p['head_b']\naux = init_aux_params(d, V, 0)\nh = torch.randn(4, d); e = torch.randn(4, d)\nprint(torch.equal(latent_transition(h, e, aux), latent_transition(h, e, aux)))","expected_output":"True"},{"test":"import torch, torch.nn.functional as F, numpy as np\ntorch.manual_seed(0)\nd, V = 64, 79\nparams = {'wte': torch.randn(V, d) * 0.02, 'head_w': (torch.randn(d, V) * 0.02).requires_grad_(True), 'head_b': torch.zeros(V, requires_grad=True)}\ndef output_head(h, p):\n    return h @ p['head_w'] + p['head_b']\naux = init_aux_params(d, V, 0)\nh = torch.randn(4, d); e = torch.randn(4, d)\nprint(not torch.allclose(latent_transition(h, e, aux), h))","expected_output":"True"},{"test":"import torch, torch.nn.functional as F, numpy as np\ntorch.manual_seed(0)\nd, V = 64, 79\nparams = {'wte': torch.randn(V, d) * 0.02, 'head_w': (torch.randn(d, V) * 0.02).requires_grad_(True), 'head_b': torch.zeros(V, requires_grad=True)}\ndef output_head(h, p):\n    return h @ p['head_w'] + p['head_b']\naux = init_aux_params(d, V, 0)\nh = torch.randn(2, 16, d, requires_grad=True); x = torch.randint(0, V, (2, 16)); mask = torch.ones(2, 16, dtype=torch.bool)\nloss = latent_objective(h, x, mask, params, aux)\nprint(torch.is_tensor(loss) and loss.dim() == 0 and bool(torch.isfinite(loss)))","expected_output":"True"},{"test":"import torch, torch.nn.functional as F, numpy as np\ntorch.manual_seed(0)\nd, V = 64, 79\nparams = {'wte': torch.randn(V, d) * 0.02, 'head_w': (torch.randn(d, V) * 0.02).requires_grad_(True), 'head_b': torch.zeros(V, requires_grad=True)}\ndef output_head(h, p):\n    return h @ p['head_w'] + p['head_b']\naux = init_aux_params(d, V, 0)\nh = torch.randn(2, 16, d, requires_grad=True); x = torch.randint(0, V, (2, 16)); mask = torch.ones(2, 16, dtype=torch.bool)\nloss = latent_objective(h, x, mask, params, aux)\nloss.backward()\nprint(any(v.grad is not None and bool(v.grad.abs().sum() > 0) for v in aux.values()))","expected_output":"True"},{"test":"import torch, torch.nn.functional as F, numpy as np\ntorch.manual_seed(0)\nd, V = 64, 79\nparams = {'wte': torch.randn(V, d) * 0.02, 'head_w': (torch.randn(d, V) * 0.02).requires_grad_(True), 'head_b': torch.zeros(V, requires_grad=True)}\ndef output_head(h, p):\n    return h @ p['head_w'] + p['head_b']\naux = init_aux_params(d, V, 0)\nh = torch.randn(2, 16, d, requires_grad=True); x = torch.randint(0, V, (2, 16)); mask = torch.ones(2, 16, dtype=torch.bool)\nloss = latent_objective(h, x, mask, params, aux)\nloss.backward()\nprint(params['head_w'].grad is None or bool(params['head_w'].grad.abs().sum() == 0))","expected_output":"True"}],"approved_user_libraries":["numpy","torch"],"lower_is_better":false,"data_info":"TinyStories (Eldan & Li, 2023): short children's-book-style stories, streamed as raw text from the HuggingFace Hub (TinyStories-valid.txt) and tokenized at the character level (about 90 symbols). Run uses a 300k-character slice at offset 0 (2048 training blocks of 64 characters, 128 validation blocks); Submit uses a different 600k-character slice at offset 3,000,000 (4096 training blocks, 256 validation blocks). Prompts for decoding are 24-character prefixes of held-out validation blocks.","time_limits":{"test":300,"dev":120},"example":{"input":"harness trains the GPT with your latent_objective, then drafts with your latent_transition on 24 held-out prompts","output":"JSON with test_acc = mean accepted drafts per cycle (baseline starter about 0.01, NextLat reference well above the 0.8 threshold), plus val_loss, effective_rank, lossless"},"pytorch_starter_code":"import torch\nimport torch.nn.functional as F\nimport numpy as np\n\n# The harness trains a small character-level GPT on TinyStories with\n#     loss = cross_entropy + latent_objective(h, x, mask, params, aux)\n# and then drafts tokens by rolling YOUR latent_transition forward from the\n# transformer's last hidden state, verifying each draft with one transformer pass.\n# Score = mean accepted drafts per cycle (higher is better), counted only if the\n# validation loss stays under the gate. Baseline below: no objective, identity\n# transition -> almost nothing is accepted.\n#\n# You may read: h (B, T, d) final hidden states, x (B, T) input tokens, mask (B, T) bool,\n# params (the GPT dict: 'wte' (V, d) embeddings, 'head_w' (d, V), 'head_b' (V), ...).\n# Helpers available from the harness: output_head(h, params), gpt_hidden_states(tokens, params, n_heads).\n\n\ndef init_aux_params(d_model: int, vocab_size: int, seed: int = 0) -> dict:\n    \"\"\"Return a dict of float32 tensors with requires_grad=True. They are trained\n    jointly with the transformer by the harness's Adam optimizer.\"\"\"\n    # TODO: allocate whatever your latent dynamics model needs\n    return {\"unused\": torch.zeros(1, requires_grad=True)}\n\n\ndef latent_objective(h, x, mask, params, aux):\n    \"\"\"Return a 0-dim tensor that is ADDED to the next-token cross-entropy.\n    Design the training signal that makes hidden states predictable from\n    (previous hidden state, next token).\"\"\"\n    # TODO: your auxiliary loss\n    return torch.tensor(0.0)\n\n\ndef latent_transition(h, x_emb, aux):\n    \"\"\"Predict the NEXT hidden state from the current one and the embedding of the\n    token that was just consumed. Must be deterministic. Works on (..., d) inputs.\"\"\"\n    # TODO: your latent dynamics model\n    return h\n","model_specs":"Functional character-level GPT owned by the harness: token + position embeddings, 2 pre-LN blocks (4-head causal attention, GELU MLP), final LayerNorm, linear output head; d_model 64, context 64. Adam lr 3e-3, batch 32, 300 steps on Run / 600 steps on Submit, loss = CE + latent_objective. Evaluation: self-speculative greedy decoding of 24 characters from held-out prompts with up to 4 drafts per cycle rolled from your latent_transition.","gpu":false,"description":"# Design Your Own Latent Dynamics: Self-Speculative Decoding on TinyStories\n\nA transformer has no built-in reason to keep a compact, consistent internal state: attention can always re-read the raw history, so nothing forces the hidden state `h_t` to be *predictable* from `h_(t-1)` and the next token. **Next-Latent Prediction** (Teoh et al., 2025) argues that if you add a training signal that makes hidden states predictable in latent space, the transformer forms coherent latent dynamics - and those dynamics can then be used as a free draft model for speculative decoding.\n\nThis lab hands you the open question, not the answer. **Design the latent dynamics model and the training signal.** The harness owns everything else.\n\n## What you write\n\n- `init_aux_params(d_model, vocab_size, seed) -> dict` - any extra tensors you need (trained jointly with the transformer).\n- `latent_objective(h, x, mask, params, aux) -> 0-dim tensor` - added to the next-token cross-entropy at every training step. `h` is `(B, T, d)` final hidden states, `x` the `(B, T)` input tokens, `params` the transformer's parameter dict (read-only).\n- `latent_transition(h, x_emb, aux) -> tensor` - predicts the next hidden state from the current one and the embedding of the token just consumed. Must be deterministic and work on `(..., d)` inputs.\n\n## What the harness does\n\nTrains a character-level GPT (`d_model=64`, 2 layers, 4 heads, context 64) on a slice of **TinyStories** with `loss = CE + latent_objective(...)`, then generates 24 characters from 24 held-out prompts by **self-speculative decoding**: it takes the transformer's next token, rolls *your* `latent_transition` forward to draft up to 4 more characters, verifies them with one transformer pass, and keeps the longest correct prefix. Greedy verification makes the output identical to plain greedy decoding, so the only thing your design changes is *how many drafts survive*.\n\n## Score\n\n`mean accepted drafts per cycle` (higher is better; pass at **0.8**). The baseline in the starter code - no objective, identity transition - accepts almost nothing. The score counts only if the model's validation loss stays under a gate (**2.05 nats/char** on Submit after 600 steps, 2.5 on Run after 300): an objective that degrades the language model to make drafts trivially agree scores 0. A plain next-token model lands near 2.0, so a good objective may cost a little perplexity but not much.\n\n## Rules\n\n- Do not change the transformer or the decoding procedure; only the three functions are yours.\n- Read `params` freely, but train the output head only through the harness's cross-entropy (detach `head_w`/`head_b` inside your objective if you use them).\n- CPU tensors only; `numpy` and `torch` only; the objective must return a finite scalar.\n","tags":["nextlat","speculative-decoding","world-model","belief-state","self-supervised","tinystories","pytorch"],"id":"442392d7-09c3-4535-94f5-3aa8f288cce5","difficulty":"hard","evaluation_metric":"mean_accepted_drafts","schema":"practical_question_v1","min_eval_metric":0.8,"category":"Deep Learning","title":"Design Your Own Latent Dynamics: Self-Speculative Decoding on TinyStories","time_limits_seconds":{"dev":120,"test":300}},{"created_at":"2026-10-31T23:42:02.503000+00:00","type":"general","test_cases":[{"test":"import numpy as np\n_r = np.random.default_rng(3)\n_v = estimate_mi(_r.standard_normal((300, 2)), _r.standard_normal((300, 3)))\nprint(\"one finite number:\", bool(np.isfinite(float(_v))))","expected_output":"one finite number: True"},{"test":"import numpy as np\n_r = np.random.default_rng(11)\n_rho = 0.9\n_x = _r.standard_normal((2000, 1))\n_y = _rho * _x + np.sqrt(1 - _rho ** 2) * _r.standard_normal((2000, 1))\n_truth = -0.5 * np.log(1 - _rho ** 2)\n_a = estimate_mi(_x.copy(), _y.copy())\n_b = estimate_mi(_x.copy(), _y.copy())\nprint(\"same input, same answer:\", bool(abs(float(_a) - float(_b)) < 1e-6))","expected_output":"same input, same answer: True"},{"test":"import numpy as np\n_r = np.random.default_rng(11)\n_rho = 0.9\n_x = _r.standard_normal((2000, 1))\n_y = _rho * _x + np.sqrt(1 - _rho ** 2) * _r.standard_normal((2000, 1))\n_truth = -0.5 * np.log(1 - _rho ** 2)\nprint(\"gaussian pair within 0.1 nats:\", bool(abs(float(estimate_mi(_x, _y)) - _truth) < 0.1))\nprint(\"exp(3x) changes nothing:\", bool(abs(float(estimate_mi(np.exp(3 * _x), _y)) - _truth) < 0.1))","expected_output":"gaussian pair within 0.1 nats: True\nexp(3x) changes nothing: True"},{"test":"import numpy as np\n_r = np.random.default_rng(5)\n_v = float(estimate_mi(_r.standard_normal((500, 3)), _r.lognormal(size=(500, 3))))\nprint(\"independent blocks read near zero:\", bool(abs(_v) < 0.1))","expected_output":"independent blocks read near zero: True"}],"lower_is_better":true,"approved_user_libraries":["numpy","scipy","sklearn"],"data_info":"Synthetic pairs generated inside the grader (no download). Each has 200 to 4000 rows and 1 to 5 columns per block, from a hidden generator with a true MI known in closed form or by numerical integration. Run: 208 pairs. Submit: 480 different pairs, with extra generator variants that Run never shows.","time_limits":{"test":300,"dev":120},"example":{"input":"estimate_mi(x, y) with x, y of shape (2000, 1) from a Gaussian pair with rho = 0.9","output":"a float close to 0.830, the value of eq. 6.70; the score is the mean absolute error in nats over all pairs (pass at 0.27 or lower)"},"gpu":false,"description":"The book defines the mutual information between two random variables, $I(X;Y) = \\mathbb{E}\\left[\\log \\frac{p(x,y)}{p(x)p(y)}\\right]$, and gives one continuous case in closed form: for a bivariate Gaussian with correlation $\\rho$, $I(X;Y) = -\\frac{1}{2}\\log(1-\\rho^2)$. For almost everything else the joint density is unknown, and the book warns that the estimate depends heavily on how you discretize, then points to nearest-neighbour methods as an alternative.\n\nHere you are given only samples, and the grader knows the true answer. Build the estimator with the smallest error in nats. Any method is allowed.\n\n## Your function\n\n```python\ndef estimate_mi(x, y):\n    ...\n    return mi        # one float, in nats\n```\n\n- `x`: a float array of shape `(n, d_x)`, `y`: a float array of shape `(n, d_y)`. Rows are i.i.d. pairs. Both arrays are always 2-D, also when $d = 1$.\n- $n$ runs from 200 to 4000. $d_x$ and $d_y$ run from 1 to 5.\n- Return $\\hat I(X;Y)$, where $X$ and $Y$ are the whole blocks of columns. One number per pair of arrays.\n\n## The data\n\nEvery pair of arrays comes from its own hidden generator, and its true MI is known exactly: in closed form where one exists (the Gaussian formula and its blocks, Student-t and uniform noise channels), otherwise by high-accuracy numerical integration of the true density. The true values run from 0 to about 7 nats. Columns have arbitrary units and offsets. The generators include:\n\n- Gaussian pairs and blocks with random correlation;\n- the same pushed through hidden invertible maps, which leave MI unchanged (the data processing inequality applied in both directions);\n- independent $X$ and $Y$ with awkward marginals, where MI is 0;\n- heavy-tailed joint distributions, some with zero correlation and non-zero MI;\n- noise channels and nonlinear or multimodal relationships, where correlation can be 0 while MI is large;\n- extra columns that carry no information about the other block;\n- discrete columns: quantized outputs $X \\to Y \\to Z$ and categorical tables whose labels are arbitrary numbers.\n\n**Run** scores 208 pairs. **Submit** scores 480 different pairs, from those generators plus transforms, marginals, relationships and block maps that Run never shows.\n\n## Score (lower is better)\n\n$$\\text{score} = \\frac{1}{N}\\sum_{i=1}^N \\min\\left(\\left|\\hat I_i - I_i\\right|,\\ 3\\right)$$\n\nThis is the mean absolute error in nats, with each pair's error capped at 3. You pass at **0.27** or lower; below that, lower ranks higher. The starter, a fixed 10-bin histogram, scores about 0.72 on Submit.\n\n## Rules, budget and gates\n\n- `estimate_mi` gets at most 5 s per call. All calls together get 60 s on Run and 180 s on Submit.\n- The same arrays must give the same answer: the grader asks again for a few pairs and any difference above $10^{-6}$ fails the run. If your method uses randomness, seed it inside the function.\n- Mutual information is never negative. Small negative estimates are allowed and scored as they are; anything below -0.5 fails the run.\n- The run fails (score 99) if `estimate_mi` raises or exits, returns something that is not one finite number, or goes over a budget.\n- Your code may import numpy, scipy, scikit-learn and small standard-library helpers such as `math` or `itertools`. Files, datasets, environment variables and dynamic attribute access are refused before anything runs. Your source is limited to 20,000 characters, 300 numeric literals (none above 64 bits) and 1,500 characters of strings outside docstrings.\n\nThe report shows your score, the mean error per generator family, and two diagnostics that do not affect the score: `symmetry_gap` compares `estimate_mi(x, y)` with `estimate_mi(y, x)`, and `invariance_gap` compares your answer before and after a strictly monotone map of every column of `x`. For a perfect estimator both are 0, because $I(X;Y)$ is symmetric and invariant to those maps.","tags":["mutual-information","information-theory","estimation","density-estimation","open-ended","leaderboard"],"id":"47731b22-57eb-4f40-85a0-424714386269","dataset_id":"synthetic","img_type":"full","evaluation_metric":"mae_nats","difficulty":"hard","min_eval_metric":0.27,"category":"Statistics","dataset":"Synthetic pairs with known mutual information (generated in the grader)","title":"Best Mutual Information Estimator","time_limits_seconds":{"dev":120,"test":300}},{"created_at":"2026-10-19T15:28:47.860000+00:00","description":"Learn the best sparse dictionary of a language model's residual stream that you can inside a training budget. The activations are the 512-dimensional residual stream after block 3 of Pythia-70m on TinyStories text. Any method counts: an L1 sparse autoencoder, a top-k or JumpReLU autoencoder, dead-latent resampling, k-SVD, orthogonal matching pursuit, or something of your own. The leaderboard ranks by **explained variance** of held-out activations, higher is better, under a fixed sparsity budget.\n\n**Contract.** Implement three functions:\n\n- `train(X_train) -> model` receives a float32 array of shape `(N, 512)` and returns any object.\n- `encode(model, X) -> Z` maps a float32 array `(n, 512)` to codes `(n, width)`; a latent counts as active when its code is non-zero. `encode` must be deterministic.\n- `decode(model, Z) -> X_hat` maps codes back to `(n, 512)` reconstructions and must be an affine function of `Z` (a linear dictionary plus a bias). The harness checks this by mixing two codes.\n\n**Budget.** Submit: `train` gets 40,000 activations and must return within 120 seconds of wall-clock time on CPU; scoring uses 10,000 held-out activations from a disjoint part of the text. Run: 10,000 training activations, a 45-second budget, 2,000 held-out.\n\n**Score.** explained variance = 1 - (sum of squared reconstruction errors) / (total variance of the held-out activations). The harness reports a dense 32-component PCA next to your number for reference; that reference is not an eligible entry because every one of its latents fires everywhere. Clearing 0.7 counts as solved; everything above that is leaderboard.\n\n**Gates.** The score is set to 0 (a fail) if `train` runs over budget, if the dictionary is wider than 2,048 latents, if the mean number of active latents per held-out activation is above 32, if more than half of the latents never fire, if more than 1% of the latents fire on more than half of all activations, if `encode` is not deterministic, or if `decode` is not affine in the code.","type":"general","tags":["interpretability","sparse-autoencoder","dictionary-learning","superposition","open-ended","leaderboard"],"id":"4f593102-2101-4946-8881-d6f66684853a","img_type":"pytorch","dataset_id":"pythia70m-resid-l3","evaluation_metric":"explained_variance","lower_is_better":false,"data_info":"Pythia-70m residual stream after block 3 on TinyStories text: x_train (40,000, 512) and x_test (10,000, 512) float32, from disjoint parts of the text, with the first four positions of every 128-token window dropped. Submit: train on all 40,000 with a 120 s budget, score 10,000 held-out. Run: train on 10,000 with a 45 s budget, score 2,000. The harness reports explained variance, mean L0, dead and dense latent fractions, training time and a dense PCA reference.","time_limits":{"test":300,"dev":120},"difficulty":"hard","approved_user_libraries":["numpy","torch","math","time","random"],"min_eval_metric":0.7,"category":"Interpretability","title":"Best Dictionary at a Fixed Sparsity","gpu":false,"dataset":"Pythia-70m residual stream (layer 3)","time_limits_seconds":{"dev":120,"test":300}},{"description":"Implement `generate_adversarial_example()` that takes a trained model, an input image, its true label, and a perturbation budget epsilon, then returns a **perturbed image** that (1) fools the model into predicting a different class, (2) stays within epsilon of the original in L∞ norm, and (3) remains in valid pixel range [0,1]. You may use any gradient-based adversarial attack method (FGSM, PGD, etc.).","constraints":["Return tensor of SAME shape as input x","L∞ distance: ||x_adv - x||_∞ ≤ epsilon","Valid range: all pixels in [0,1]","Must fool the model: model(x_adv).argmax() != y","Use gradient-based methods only"],"id":"5","test_cases":[{"test":"import torch\nimport torch.nn as nn\n\n# Dummy model and data\nclass DummyModel(nn.Module):\n    def __init__(self):\n        super().__init__()\n        self.fc = nn.Linear(784, 10)\n    def forward(self, x):\n        return self.fc(x.flatten(1))\n\nmodel = DummyModel()\nmodel.eval()\nx = torch.rand(1, 1, 28, 28)\ny = torch.tensor([3])\nepsilon = 0.1\ncriterion = nn.CrossEntropyLoss()\n\nx_adv = generate_adversarial_example(model, x, y, epsilon, criterion)\nprint(x_adv.shape == x.shape)","expected_output":"True"},{"test":"import torch\nimport torch.nn as nn\n\nclass DummyModel(nn.Module):\n    def __init__(self):\n        super().__init__()\n        self.fc = nn.Linear(784, 10)\n    def forward(self, x):\n        return self.fc(x.flatten(1))\n\nmodel = DummyModel()\nmodel.eval()\nx = torch.rand(1, 1, 28, 28)\ny = torch.tensor([3])\nepsilon = 0.1\ncriterion = nn.CrossEntropyLoss()\n\nx_adv = generate_adversarial_example(model, x, y, epsilon, criterion)\nlinf_dist = (x_adv - x).abs().max().item()\nprint(linf_dist <= epsilon + 1e-5)","expected_output":"True"},{"test":"import torch\nimport torch.nn as nn\n\nclass DummyModel(nn.Module):\n    def __init__(self):\n        super().__init__()\n        self.fc = nn.Linear(784, 10)\n    def forward(self, x):\n        return self.fc(x.flatten(1))\n\nmodel = DummyModel()\nmodel.eval()\nx = torch.rand(1, 1, 28, 28)\ny = torch.tensor([3])\nepsilon = 0.1\ncriterion = nn.CrossEntropyLoss()\n\nx_adv = generate_adversarial_example(model, x, y, epsilon, criterion)\nin_range = (x_adv.min().item() >= 0.0) and (x_adv.max().item() <= 1.0)\nprint(in_range)","expected_output":"True"}],"approved_user_libraries":["torch","numpy"],"difficulty":"hard","evaluation_metric":"Fooling Rate","data_info":"MNIST 28x28 grayscale digits (10 classes). Test images scaled to [0,1], shaped (1,1,28,28) for single samples.","time_limits":{"test":"240 seconds","dev":"90 seconds"},"schema":"practical_question_v1","min_eval_metric":0.5,"example":{"input":{"y":"tensor([3])","epsilon":"0.1","x":"tensor([[[[0.0, 0.0, ..., 0.8, 0.9], ...]]]) shape (1,1,28,28)"},"output":{"properties":["model(x_adv).argmax() != y","||x_adv - x||_∞ ≤ epsilon","x_adv in [0,1]"],"x_adv":"tensor([[[[0.0, 0.05, ..., 0.85, 1.0], ...]]]) shape (1,1,28,28)"}},"category":"Adversarial Robustness","title":"MNIST: Adversarial Example Generation","model_specs":"Pre-trained CNN provided by the test harness. You do NOT train the model—you attack it.","memory_limit":"2 GB","dataset":"MNIST","createdAt":"2026-05-13T21:01:43.953000+00:00","time_limits_seconds":{"dev":90,"test":240},"type":"epoch","lower_is_better":false,"gpu":false},{"created_at":"2026-10-28T18:58:44.152000+00:00","description":"## Best Classifier Trained on Noisy Labels\n\nSomebody labelled a batch of Fashion-MNIST images in a hurry. Many labels are wrong, nobody says which, and the corruption is different every time. Write a training procedure that, given only the pixels and these noisy labels, returns a classifier whose probabilities are as good as possible **for the true labels**.\n\n### What you write\n\n```python\ndef train(X_train, y_noisy, n_classes):\n    ...\n    return predict_proba        # predict_proba(X) -> array of shape (len(X), n_classes)\n```\n\n- `X_train`: float32 array of shape (12000, 784), pixels scaled to [0, 1] (28 x 28 images, flattened).\n- `y_noisy`: int64 array of shape (12000,) with labels in 0..9. Some of them are wrong.\n- `n_classes`: 10.\n- `predict_proba(X)` must return finite, non-negative probabilities whose rows sum to 1 (within 1e-3).\n\n### How labels are corrupted\n\nEach grader run trains your procedure from scratch on **four regimes**, each with its own 12,000 images and its own corruption. The corruption mixes three kinds of label errors at rates you are not told:\n\n- a label replaced by a uniformly random other class,\n- every image of one class systematically relabelled as one particular other class, part of the time,\n- ambiguous images, close to another class, given that other class's label.\n\nIn every regime the true class is still the most common label for every kind of image, but it can be far from the only one. The **Run** button shows four regimes and names what each one is; **Submit** uses four held-out regimes (different images, rates and class mappings) and does not name them.\n\n### Score\n\nFor each regime the grader calls `predict_proba` on clean test images and computes the log loss against the **true** labels:\n\n$$\\text{LL} = -\\frac{1}{N}\\sum_{n=1}^{N} \\log \\max\\big(\\hat p(y_n \\mid x_n),\\ 10^{-6}\\big)$$\n\nYour score is the mean log loss over the four regimes (lower is better). Log loss is a proper scoring rule, so it rewards being right **and** honest about confidence: a model that simply copies the noise rate into its probabilities pays for it.\n\nThe floor is **0.80**, a bit better than plain multinomial logistic regression trained on the noisy labels as if they were clean (about 0.88 on Submit). Accuracy per regime is reported too, but only the log loss counts.\n\n### Budgets and rules\n\n- `train` gets **40 s** of wall time per regime (2 CPU cores), `predict_proba` gets 10 s for the test set.\n- Libraries: numpy, scipy, scikit-learn, PyTorch (CPU) and the Python maths modules. Nothing else is importable.\n- Your code sees only `(X_train, y_noisy, n_classes)` and the test images. It may not read files, datasets or the network (no `dml_data`, `sklearn.datasets`, `np.load`, `open`, `getattr` and the like), may not embed pretrained weights or data (source at most 40,000 characters, at most 600 numeric literals, no long encoded strings), and starts fresh in every regime (module state does not carry over).\n- Any rule violation, invalid probabilities, an exception or a blown budget fails the run with no score.\n","type":"general","tags":["label noise","robust logistic regression","log loss","calibration","competitive","probabilistic machine learning"],"id":"54309ff5-6fe2-4d32-8255-a30f33f1f34a","img_type":"full","test_cases":[{"test":"import numpy as np\n_r = np.random.default_rng(0)\n_X = _r.random((300, 784)).astype(np.float32)\n_y = _r.integers(0, 10, 300)\n_pp = train(_X, _y, 10)\n_P = np.asarray(_pp(_X[:50]), dtype=np.float64)\nprint(_P.shape == (50, 10) and bool(np.all(np.isfinite(_P))) and bool(_P.min() >= 0) and bool(np.allclose(_P.sum(1), 1, atol=1e-3)))","expected_output":"True"},{"test":"import numpy as np\n_r = np.random.default_rng(1)\n_M = _r.random((10, 784)).astype(np.float32)\n_y = np.repeat(np.arange(10), 60)\n_X = np.clip(_M[_y] + 0.05 * _r.standard_normal((600, 784)), 0, 1).astype(np.float32)\n_P = np.asarray(train(_X, _y, 10)(_X))\nprint(bool((_P.argmax(1) == _y).mean() > 0.95))","expected_output":"True"},{"test":"import numpy as np\n_r = np.random.default_rng(2)\n_M = _r.random((10, 784)).astype(np.float32)\n_y = np.repeat(np.arange(10), 200)\n_X = np.clip(_M[_y] + 0.05 * _r.standard_normal((2000, 784)), 0, 1).astype(np.float32)\n_f = _r.random(2000) < 0.4\n_yn = _y.copy()\n_yn[_f] = (_y[_f] + _r.integers(1, 10, 2000)[_f]) % 10\n_P = np.asarray(train(_X, _yn, 10)(_M))\n# 40 % of the labels are wrong, yet each cluster centre's true class is certain\nprint(bool(_P[np.arange(10), np.arange(10)].mean() > 0.85))","expected_output":"True"}],"dataset_id":"fashion-mnist","lower_is_better":true,"evaluation_metric":"clean_log_loss","data_info":"Fashion-MNIST (dml_data id fashion-mnist), pixels flattened to 784 float32 values in [0, 1]. Each grader run draws four disjoint training sets of 12,000 images from the 60,000 training images and corrupts their labels with a hidden regime. Run tests on 5,000 other training-split images; Submit tests on the official 10,000-image test split with clean labels. Run seed 42, Submit seed 2026 with held-out noise regimes.","time_limits":{"test":300,"dev":300},"difficulty":"hard","approved_user_libraries":["numpy","scipy","sklearn","torch"],"min_eval_metric":0.8,"category":"Machine Learning","title":"Best Classifier Trained on Noisy Labels","dataset":"Fashion-MNIST","gpu":false,"time_limits_seconds":{"dev":300,"test":300}},{"offline":true,"description":"Train a classifier for all ten MNIST digits from a transfer set that contains **no 3 at all**. You get the teacher's logits for every transfer image, and the teacher has seen plenty of 3s. The score is **two_sided_acc**: the average of your accuracy on the test 3s and your accuracy on the other test digits. Higher is better; 0.94 counts as solved.\n\nThis is an experiment from Hinton, Vinyals and Dean, \"Distilling the Knowledge in a Neural Network\" (2015): a student trained on a teacher's soft targets can learn a class it never saw.\n\n**The teacher.** The grader trains it in a separate process before `train` is called, the same way every time: a fully connected network 784-400-400-10 with ReLU units, dropout (0.2 on the pixels, 0.5 on the hidden units), a max-norm weight constraint and training images shifted by up to two pixels, on the first 12,000 MNIST training images, all ten digits. It is trained in 64-bit floating point so that it comes out exactly the same on every grading machine, and it gets about 96% of the Run images and 97% of the Submit images right.\n\n**Contract.** Implement two functions:\n- `train(X, y, teacher_logits) -> model`. `X` is a float32 array of shape (n, 784): the same 12,000 training images, flattened, pixels in 0 to 1, with every 3 removed (n is about 10,800). `y` holds their int64 labels; 3 never appears. `teacher_logits` is a float32 array of shape (n, 10): the teacher's logits (the inputs to its softmax, at temperature 1) for each image in `X`. Return any object.\n- `predict(model, X) -> scores`. `X` is a float32 array of test images of shape (m, 784). Return an array of shape (m, 10). The predicted digit for an image is the argmax of its row.\n\n**What is scored.** MNIST test images the transfer set does not contain: 7,000 on Submit (about 700 of them are 3s), 3,000 others on Run. The test images have all ten digits in MNIST's natural proportions, about one tenth each. two_sided_acc = (fraction of test 3s predicted as 3 + fraction of the other test images predicted correctly) / 2. The report also shows the two halves (`acc_on_3s`, `acc_on_other_digits`) and the teacher's own test accuracy.\n\n**Budget.** `train` must return within 60 seconds of wall-clock time on one CPU, and `predict` within 10 seconds. The grader calls `torch.manual_seed` and `np.random.seed` before `train`.\n\n**Gates.** The score is set to 0 (a fail) if `train` or `predict` runs over budget, if `predict` returns anything other than an (m, 10) array of finite numbers, or if your code breaks the rules below.\n\n**What your code may use.** numpy, torch and small standard-library helpers (math, random, time, collections, itertools, functools, ...). Graded runs have no network, and your code may not open files, load datasets, or embed data: string constants are limited to 3,000 characters and numeric literals to 600. In this lab it may also not use private attributes (ones that start with `_`, such as `x._foo`) or the names `sys`, `os`, `builtins`, `importlib`, `inspect`, `ctypes`, `gc`, `pickle`, `json`, `subprocess`, `types`, `operator`, `traceback`, `weakref`, `modules` and a few more like them (the error message names the one it found), nor `torch.set_num_threads` or functions that write files (`save`, `savez`, `savetxt`, `tofile`, `dump`). The transfer set and the teacher's logits arrive as the arguments to `train`; the test images reach your code only as the argument to `predict`, and the grader turns what `predict` returns into plain numbers before its clock stops.","type":"general","tags":["distillation","knowledge-distillation","soft-targets","temperature","mnist","omitted-class","paper-implementation"],"id":"5925eccc-3fb2-4b70-a730-6f7f88d0fe9e","created_at":"2026-11-23T14:19:50.181000+00:00","img_type":"pytorch","test_cases":[{"test":"import numpy as np\nrng = np.random.default_rng(0)\nX = rng.random((64, 784), dtype=np.float32)\ny = rng.choice([0, 1, 2, 4, 5, 6, 7, 8, 9], 64).astype(np.int64)\nlogits = rng.standard_normal((64, 10)).astype(np.float32)\nm = train(X, y, logits)\ns = np.asarray(predict(m, X[:5]))\nprint(s.shape == (5, 10) and bool(np.all(np.isfinite(s))))","expected_output":"True"}],"dataset_id":"mnist","evaluation_metric":"two_sided_acc","difficulty":"medium","data_info":"Transfer set: the first 12,000 MNIST training images (CC BY-SA 3.0) with every 3 removed, about 10,800 images flattened to 784 float32 pixels in 0 to 1, their labels, and the teacher's float32 logits (n, 10). The teacher is trained by the grader on the same 12,000 images including the 3s. Scored: MNIST test images 3,000 to 9,999 on Submit, 0 to 2,999 on Run.","time_limits":{"test":180,"dev":150},"lower_is_better":false,"approved_user_libraries":["numpy","torch","math","collections","random","time"],"min_eval_metric":0.94,"example":{"input":"train(X_without_3s, y_without_3s, teacher_logits), then predict(model, X_test)","output":"(m, 10) scores; two_sided_acc = (accuracy on test 3s + accuracy on the other digits) / 2"},"category":"Deep Learning","title":"Recognize a Digit the Student Never Saw","dataset":"MNIST","gpu":false,"time_limits_seconds":{"dev":150,"test":180}},{"created_at":"2026-11-01T01:03:34.611000+00:00","type":"general","test_cases":[{"test":"import numpy as np\nfrom scipy.special import ndtr, ndtri\n\n\nclass _P:\n    \"\"\"A small standard normal p with the contract's methods, for these checks only.\"\"\"\n    def __init__(self, d):\n        self.dim = d\n\n    def sample(self, n, r):\n        return r.standard_normal((n, self.dim))\n\n    def from_unit(self, u):\n        return ndtri(np.clip(u, 1e-16, 1 - 1e-16))\n\n    def to_unit(self, x):\n        return ndtr(x)\n\n    def log_prob(self, x):\n        return -0.5 * (x * x).sum(1) - 0.5 * self.dim * np.log(2 * np.pi)\n\n\ndef _counted(g, budget):\n    used = [0]\n\n    def f(x):\n        x = np.array(x, dtype=float)\n        used[0] += len(x)\n        if used[0] > budget:\n            raise RuntimeError(\"over budget\")\n        return g(x)\n\n    return f, used\n\n\ndef _ratio(g, d, budget, truth, sd, seeds=40):\n    total = 0.0\n    for s in range(seeds):\n        f, _ = _counted(g, budget)\n        total += ((float(estimate(f, _P(d), budget, np.random.default_rng(s))) - truth) / (sd / budget ** 0.5)) ** 2\n    return (total / seeds) ** 0.5\n_f, _u = _counted(lambda x: (x * x).sum(1), 512)\n_v = estimate(_f, _P(2), 512, np.random.default_rng(1))\nprint(\"one finite number:\", bool(np.isfinite(float(_v))))\nprint(\"stays within the budget:\", _u[0] <= 512)","expected_output":"one finite number: True\nstays within the budget: True"},{"test":"import numpy as np\nfrom scipy.special import ndtr, ndtri\n\n\nclass _P:\n    \"\"\"A small standard normal p with the contract's methods, for these checks only.\"\"\"\n    def __init__(self, d):\n        self.dim = d\n\n    def sample(self, n, r):\n        return r.standard_normal((n, self.dim))\n\n    def from_unit(self, u):\n        return ndtri(np.clip(u, 1e-16, 1 - 1e-16))\n\n    def to_unit(self, x):\n        return ndtr(x)\n\n    def log_prob(self, x):\n        return -0.5 * (x * x).sum(1) - 0.5 * self.dim * np.log(2 * np.pi)\n\n\ndef _counted(g, budget):\n    used = [0]\n\n    def f(x):\n        x = np.array(x, dtype=float)\n        used[0] += len(x)\n        if used[0] > budget:\n            raise RuntimeError(\"over budget\")\n        return g(x)\n\n    return f, used\n\n\ndef _ratio(g, d, budget, truth, sd, seeds=40):\n    total = 0.0\n    for s in range(seeds):\n        f, _ = _counted(g, budget)\n        total += ((float(estimate(f, _P(d), budget, np.random.default_rng(s))) - truth) / (sd / budget ** 0.5)) ** 2\n    return (total / seeds) ** 0.5\n_g = lambda x: np.cos(x[:, 0]) * x[:, 1]\n_f1, _ = _counted(_g, 512)\n_f2, _ = _counted(_g, 512)\n_a = float(estimate(_f1, _P(2), 512, np.random.default_rng(7)))\n_b = float(estimate(_f2, _P(2), 512, np.random.default_rng(7)))\nprint(\"same rng, same answer:\", abs(_a - _b) < 1e-9)","expected_output":"same rng, same answer: True"},{"test":"import numpy as np\nfrom scipy.special import ndtr, ndtri\n\n\nclass _P:\n    \"\"\"A small standard normal p with the contract's methods, for these checks only.\"\"\"\n    def __init__(self, d):\n        self.dim = d\n\n    def sample(self, n, r):\n        return r.standard_normal((n, self.dim))\n\n    def from_unit(self, u):\n        return ndtri(np.clip(u, 1e-16, 1 - 1e-16))\n\n    def to_unit(self, x):\n        return ndtr(x)\n\n    def log_prob(self, x):\n        return -0.5 * (x * x).sum(1) - 0.5 * self.dim * np.log(2 * np.pi)\n\n\ndef _counted(g, budget):\n    used = [0]\n\n    def f(x):\n        x = np.array(x, dtype=float)\n        used[0] += len(x)\n        if used[0] > budget:\n            raise RuntimeError(\"over budget\")\n        return g(x)\n\n    return f, used\n\n\ndef _ratio(g, d, budget, truth, sd, seeds=40):\n    total = 0.0\n    for s in range(seeds):\n        f, _ = _counted(g, budget)\n        total += ((float(estimate(f, _P(d), budget, np.random.default_rng(s))) - truth) / (sd / budget ** 0.5)) ** 2\n    return (total / seeds) ** 0.5\n# a smooth integrand with a known mean: E[exp(x1) + cos(x2)], x ~ N(0, I)\n_m = np.exp(0.5) + np.exp(-0.5)\n_var = (np.exp(2) - np.exp(1)) + (0.5 * (1 + np.exp(-2)) - np.exp(-1))\n_r = _ratio(lambda x: np.exp(x[:, 0]) + np.cos(x[:, 1]), 2, 1024, _m, _var ** 0.5)\nprint(\"smooth: RMSE under 0.8 of plain Monte Carlo:\", _r < 0.8)","expected_output":"smooth: RMSE under 0.8 of plain Monte Carlo: True"},{"test":"import numpy as np\nfrom scipy.special import ndtr, ndtri\n\n\nclass _P:\n    \"\"\"A small standard normal p with the contract's methods, for these checks only.\"\"\"\n    def __init__(self, d):\n        self.dim = d\n\n    def sample(self, n, r):\n        return r.standard_normal((n, self.dim))\n\n    def from_unit(self, u):\n        return ndtri(np.clip(u, 1e-16, 1 - 1e-16))\n\n    def to_unit(self, x):\n        return ndtr(x)\n\n    def log_prob(self, x):\n        return -0.5 * (x * x).sum(1) - 0.5 * self.dim * np.log(2 * np.pi)\n\n\ndef _counted(g, budget):\n    used = [0]\n\n    def f(x):\n        x = np.array(x, dtype=float)\n        used[0] += len(x)\n        if used[0] > budget:\n            raise RuntimeError(\"over budget\")\n        return g(x)\n\n    return f, used\n\n\ndef _ratio(g, d, budget, truth, sd, seeds=40):\n    total = 0.0\n    for s in range(seeds):\n        f, _ = _counted(g, budget)\n        total += ((float(estimate(f, _P(d), budget, np.random.default_rng(s))) - truth) / (sd / budget ** 0.5)) ** 2\n    return (total / seeds) ** 0.5\n# a rare event: Pr(X > 3) under N(0, 1), about 5 hits at this budget\n_q = float(ndtr(-3.0))\n_r = _ratio(lambda x: (x[:, 0] > 3.0) * 1.0, 1, 4000, _q, (_q * (1 - _q)) ** 0.5)\nprint(\"rare event: RMSE under 0.8 of plain Monte Carlo:\", _r < 0.8)","expected_output":"rare event: RMSE under 0.8 of plain Monte Carlo: True"}],"approved_user_libraries":["numpy","scipy"],"lower_is_better":true,"data_info":"No dataset: every task is generated inside the grader from a hidden family of distributions and integrands, with a true value known in closed form or by high-accuracy quadrature. Run: 40 tasks, 16 repeats each. Submit: 95 different tasks, 20 repeats each, with families and distributions that Run never shows. Budgets run from 400 to 8000 evaluations and dimensions from 1 to 8.","time_limits":{"test":300,"dev":120},"example":{"input":"estimate(f, p, budget, rng) with budget = 4000 and f(x) = 1 if x > 3 else 0 under p = N(0, 1)","output":"a float close to 0.00135; plain Monte Carlo has RMSE 0.00058 here, so an RMSE of 0.00029 counts as a ratio of 0.5 (the score is the geometric mean of such ratios over all tasks; pass at 0.8 or lower)"},"gpu":false,"description":"The book approximates a distribution by drawing $N_s$ samples and treating them as spikes. The same idea estimates an expectation by the sample mean, and the central limit theorem gives its error: the sample mean is approximately normal around the true value with standard deviation $\\sigma / \\sqrt{N}$. That rate is the baseline here. Halving the error by brute force takes four times the samples.\n\nHere the number of evaluations of $f$ is fixed. Build the estimator of $\\mathbb{E}_{x \\sim p}[f(x)]$ with the lowest error for that budget. Any method is allowed.\n\n## Your function\n\n```python\ndef estimate(f, p, budget, rng):\n    ...\n    return value        # one float: your estimate of E_p[f(x)]\n```\n\n- `f(x)`: the integrand, a black box. `x` is a float array of shape `(n, p.dim)`; it returns a float array of shape `(n,)`. You may call it as often as you like with any `n`.\n- `budget`: the total number of rows `f` may receive during this call, from 400 to 8000.\n- `rng`: a `numpy.random.Generator`. Draw all your randomness from it.\n- `p`: the distribution, with `p.dim` (1 to 8) and four methods:\n  - `p.sample(n, rng)` returns `n` draws, shape `(n, dim)`;\n  - `p.log_prob(x)` returns the log density, shape `(n,)`;\n  - `p.from_unit(u)` maps points of the unit cube to $x$, so that $u \\sim \\text{Unif}[0,1]^{d}$ gives $x \\sim p$;\n  - `p.to_unit(x)` is its inverse.\n\n## How the budget is counted\n\nThe grader counts inside `f`, on the rows of the array it receives. Producing points is free however you do it: from `p.sample`, from `p.from_unit`, or from your own generator. Evaluating them is what costs. A call that would take the total past `budget` is refused and fails the run, even if your code catches the exception.\n\nEach `f` works only during its own call of `estimate`. Using one kept from an earlier call also fails the run.\n\n## The tasks\n\nEvery task has a hidden $(p, f)$ family, a dimension and a budget, and is repeated 16 times on Run and 20 times on Submit. **Each repeat draws new parameters for both $p$ and $f$**, including a random scale and offset of $f$, so nothing learned about one call's integrand carries over to the next. Every true value is known in closed form or by high-accuracy quadrature, so your error is measured against the truth.\n\n- $p$ may be Gaussian with or without correlation, uniform on a box, or other standard laws.\n- $f$ may be smooth, sharply peaked, discontinuous, heavy-tailed, or a rare event such as $\\Pr(X > 3)$. Rare events are set so that plain Monte Carlo expects only 4 to 40 hits at your budget.\n\n**Run** scores 40 tasks. **Submit** scores 95 different tasks, including integrand families and distributions that Run never shows.\n\n## Score (lower is better)\n\nFor one repeat with true value $\\mu$ and integrand standard deviation $\\sigma$, plain Monte Carlo at the same budget $N$ has RMSE exactly $\\sigma / \\sqrt{N}$. For a task, the grader computes\n\n$$r = \\sqrt{\\frac{1}{R} \\sum_{i=1}^{R} \\left( \\frac{\\hat\\mu_i - \\mu_i}{\\sigma_i / \\sqrt{N}} \\right)^2}$$\n\nclipped to $[0.001, 30]$. The score is the geometric mean of $r$ over all tasks:\n\n$$\\text{score} = \\exp\\left( \\frac{1}{T} \\sum_{t=1}^{T} \\log r_t \\right)$$\n\nPlain Monte Carlo, the starter, scores about 0.96 on Submit: near 1, and a little below because a finite sample of heavy-tailed errors usually misses its largest ones. You pass at **0.8** or lower, a 20% error reduction; below that, lower ranks higher.\n\n## Rules and gates\n\n- Budget: at most 3 s per call of `estimate`, and 60 s in total on Run, 180 s on Submit.\n- The same `f`, `p`, `budget` and `rng` must give the same answer: the grader repeats a few calls and any difference fails the run. Draw randomness from `rng` and keep no state between calls.\n- The run fails (score 99) if `estimate` goes over a budget, raises or exits, or returns something that is not one finite number.\n- Your code may import numpy, scipy and small standard-library helpers such as `math`, `itertools`, `collections`, `heapq`, `random`, `time`, `warnings` and `typing`. Other imports are refused.\n- You may write ordinary classes. **Attribute assignment is allowed only as `self.name = ...` inside a method of a class you define**, with `self` as the method's first parameter and never rebound; every other `a.b = ...` or `del a.b` is refused. Make instances with `K(...)` and call methods on the instance: `K.method(...)`, passing a class around, class decorators and metaclasses are refused, and `super()` reaches a parent's method. Your code may also not use names such as `sys`, `type`, `getattr`, `setattr`, `vars`, `globals`, `eval`, `exec`, `compile`, `open` or `format`, nor double-underscore names beyond the usual ones such as `__init__`, `__repr__`, `__lt__` and `__name__`. All of this is checked before anything runs.\n- Your source is limited to 20,000 characters, 300 numeric constants and 3,000 characters of strings, docstrings included.\n\nThe report shows your score, the geometric mean per integrand group (`smooth`, `peaked`, `discontinuous`, `rare_event`, `heavy_tailed`), the share of the budget you used, and your time.","tags":["monte-carlo","variance-reduction","importance-sampling","quasi-monte-carlo","probability","open-ended","leaderboard"],"id":"597d20b0-1436-4b3c-8e7d-717c36780d5c","dataset_id":"synthetic","img_type":"full","difficulty":"hard","evaluation_metric":"rmse_ratio","min_eval_metric":0.8,"category":"Probability","dataset":"Synthetic integrands with known expectations (generated in the grader)","title":"Lowest-Error Monte Carlo Estimator Under a Sample Budget","time_limits_seconds":{"dev":120,"test":300}},{"created_at":"2026-11-06T15:13:04.362000+00:00","type":"general","constraints":["place(history, cluster) returns a (gpus, slots_per_gpu) integer array of expert ids, -1 for an empty slot; a fresh process per task","every expert needs at least one copy and no GPU may hold the same expert twice; an invalid placement fails the run","5 s of CPU per task counting all threads and child processes, 10 s wall; over budget or an exception scores 1.5 for that task","module level and class bodies hold only imports, constants, and function and class definitions; no calls there","numpy, scipy, math, itertools, collections, heapq, bisect, random, statistics, time, warnings, typing, copy only; attributes may be assigned only on self, inside a method defined in a class body","source capped at 40000 characters, 600 numeric literals, 2000 characters of string constants"],"test_cases":[{"test":"import numpy as np\n_tc_rng = np.random.default_rng(11)\n_tc_cl = {'nodes': 2, 'gpus_per_node': 4, 'gpus': 8, 'experts': 16, 'slots_per_gpu': 3, 'top_k': 4,\n          'trace_tokens_per_gpu': 32, 'sample_scale': 256, 'row_us': 0.17, 'token_bytes': 4096,\n          'nvlink_GBps': 150.0, 'rdma_GBps': 20.0, 'a2a_passes': 4, 'history_steps': 12, 'graded_steps': 6}\n_tc_w = np.ones(16)\n_tc_w[[0, 1, 2]] = 6.0\n_tc_ex = np.stack([np.stack([_tc_rng.choice(16, 4, replace=False, p=_tc_w / _tc_w.sum()) for _ in range(256)])\n                   for _ in range(12)])\n_tc_hist = {'experts': _tc_ex, 'src': np.repeat(np.arange(8), 32),\n            'counts': np.stack([np.bincount(s.ravel(), minlength=16) for s in _tc_ex])}\n_tc_P = np.asarray(place(_tc_hist, dict(_tc_cl)))\ndef _tc_busiest(P):\n    P = np.asarray(P, dtype=int)\n    tot = _tc_hist['counts'].sum(0).astype(float)\n    n = np.array([(P == e).any(1).sum() for e in range(16)])\n    return max(sum(tot[e] / n[e] for e in row if e >= 0) for row in P)\nprint(_tc_P.shape)","expected_output":"(8, 3)"},{"test":"import numpy as np\n_tc_rng = np.random.default_rng(11)\n_tc_cl = {'nodes': 2, 'gpus_per_node': 4, 'gpus': 8, 'experts': 16, 'slots_per_gpu': 3, 'top_k': 4,\n          'trace_tokens_per_gpu': 32, 'sample_scale': 256, 'row_us': 0.17, 'token_bytes': 4096,\n          'nvlink_GBps': 150.0, 'rdma_GBps': 20.0, 'a2a_passes': 4, 'history_steps': 12, 'graded_steps': 6}\n_tc_w = np.ones(16)\n_tc_w[[0, 1, 2]] = 6.0\n_tc_ex = np.stack([np.stack([_tc_rng.choice(16, 4, replace=False, p=_tc_w / _tc_w.sum()) for _ in range(256)])\n                   for _ in range(12)])\n_tc_hist = {'experts': _tc_ex, 'src': np.repeat(np.arange(8), 32),\n            'counts': np.stack([np.bincount(s.ravel(), minlength=16) for s in _tc_ex])}\n_tc_P = np.asarray(place(_tc_hist, dict(_tc_cl)))\ndef _tc_busiest(P):\n    P = np.asarray(P, dtype=int)\n    tot = _tc_hist['counts'].sum(0).astype(float)\n    n = np.array([(P == e).any(1).sum() for e in range(16)])\n    return max(sum(tot[e] / n[e] for e in row if e >= 0) for row in P)\n_ok = all((_tc_P == e).any() for e in range(16)) and _tc_P.min() >= -1 and _tc_P.max() < 16\n_ok = _ok and all(len(set(r[r >= 0].tolist())) == len(r[r >= 0]) for r in _tc_P)\nprint(bool(_ok))","expected_output":"True"},{"test":"import numpy as np\n_tc_rng = np.random.default_rng(11)\n_tc_cl = {'nodes': 2, 'gpus_per_node': 4, 'gpus': 8, 'experts': 16, 'slots_per_gpu': 3, 'top_k': 4,\n          'trace_tokens_per_gpu': 32, 'sample_scale': 256, 'row_us': 0.17, 'token_bytes': 4096,\n          'nvlink_GBps': 150.0, 'rdma_GBps': 20.0, 'a2a_passes': 4, 'history_steps': 12, 'graded_steps': 6}\n_tc_w = np.ones(16)\n_tc_w[[0, 1, 2]] = 6.0\n_tc_ex = np.stack([np.stack([_tc_rng.choice(16, 4, replace=False, p=_tc_w / _tc_w.sum()) for _ in range(256)])\n                   for _ in range(12)])\n_tc_hist = {'experts': _tc_ex, 'src': np.repeat(np.arange(8), 32),\n            'counts': np.stack([np.bincount(s.ravel(), minlength=16) for s in _tc_ex])}\n_tc_P = np.asarray(place(_tc_hist, dict(_tc_cl)))\ndef _tc_busiest(P):\n    P = np.asarray(P, dtype=int)\n    tot = _tc_hist['counts'].sum(0).astype(float)\n    n = np.array([(P == e).any(1).sum() for e in range(16)])\n    return max(sum(tot[e] / n[e] for e in row if e >= 0) for row in P)\n_d = np.full((8, 3), -1)\n_d[:, :2] = np.arange(16).reshape(8, 2)\nprint(_tc_busiest(_tc_P) < 0.9 * _tc_busiest(_d))","expected_output":"True"},{"test":"import numpy as np\n_tc_rng = np.random.default_rng(11)\n_tc_cl = {'nodes': 2, 'gpus_per_node': 4, 'gpus': 8, 'experts': 16, 'slots_per_gpu': 3, 'top_k': 4,\n          'trace_tokens_per_gpu': 32, 'sample_scale': 256, 'row_us': 0.17, 'token_bytes': 4096,\n          'nvlink_GBps': 150.0, 'rdma_GBps': 20.0, 'a2a_passes': 4, 'history_steps': 12, 'graded_steps': 6}\n_tc_w = np.ones(16)\n_tc_w[[0, 1, 2]] = 6.0\n_tc_ex = np.stack([np.stack([_tc_rng.choice(16, 4, replace=False, p=_tc_w / _tc_w.sum()) for _ in range(256)])\n                   for _ in range(12)])\n_tc_hist = {'experts': _tc_ex, 'src': np.repeat(np.arange(8), 32),\n            'counts': np.stack([np.bincount(s.ravel(), minlength=16) for s in _tc_ex])}\n_tc_P = np.asarray(place(_tc_hist, dict(_tc_cl)))\ndef _tc_busiest(P):\n    P = np.asarray(P, dtype=int)\n    tot = _tc_hist['counts'].sum(0).astype(float)\n    n = np.array([(P == e).any(1).sum() for e in range(16)])\n    return max(sum(tot[e] / n[e] for e in row if e >= 0) for row in P)\nprint(int((_tc_P >= 0).sum()) > 16)","expected_output":"True"}],"lower_is_better":true,"approved_user_libraries":["numpy","scipy"],"data_info":"There is no dataset to read: the grader generates every routing trace in a separate process, and your code receives only the history part.\n\nEach task is one MoE layer with 8 experts per token on one cluster. Each step, every GPU holds 4 sequences, each drawn from one of several data domains. Experts specialise: each expert prefers one domain, some also serve a second, and a few are liked by every domain. Within a sequence, every token picks its top-8 experts from noisy router scores. How often each domain appears, and the router's preference for each expert, drift from step to step. The history gives 64 steps, and the graded future is the next 32.\n\nThe trace samples 8,192 real tokens per GPU per step down to `trace_tokens_per_gpu` (128 to 512) tokens, and `sample_scale` scales the counts back up. `cluster` also carries `history_steps` and `graded_steps`.\n\nRun uses 10 tasks on these cluster shapes:\n- 2 nodes of 8 GPUs, 64 experts, 5 slots per GPU (1 spare), 20 GB/s between nodes\n- 4 nodes of 4 GPUs, 64 experts, 5 slots per GPU (1 spare), 20 GB/s between nodes\n- 4 nodes of 8 GPUs, 128 experts, 5 slots per GPU (1 spare), 20 GB/s between nodes\n\nand these kinds of drift:\n- **steady**: the domain mix and the router's preferences hold still apart from step-to-step noise\n- **drift**: both wander slowly and randomly\n\nSubmit uses 20 tasks with new seeds: 6 like these, and 14 with 4 more kinds of drift and 4 more cluster shapes that are not listed here.","time_limits":{"test":300,"dev":180},"gpu":false,"description":"## Fastest Expert Placement\n\nIn expert-parallel training, every MoE layer sends each token to the GPUs that hold its top-8 experts and brings the results back. The step waits for the busiest GPU to finish its expert work, and for the slowest link to finish moving tokens. Links inside a node (NVLink) are several times faster than the network between nodes. You decide **where the experts live**: which GPU holds each expert, and which experts get extra copies in the few spare memory slots each GPU has.\n\nYou are given a routing trace of the last 64 training steps. Your placement is then held fixed for the next 32 steps and graded on what the router does during those steps. The router's preferences drift over time, so a placement fitted to the past has to keep working in the future.\n\n### What you write\n\n```python\ndef place(history, cluster):\n    # history[\"experts\"]: int array (steps, tokens, top_k), the experts each trace token was routed to\n    # history[\"src\"]:     int array (tokens,), the GPU each trace token starts on (the same every step)\n    # history[\"counts\"]:  int array (steps, experts), routed copies per expert per step\n    # cluster: dict with nodes, gpus_per_node, gpus, experts, slots_per_gpu, top_k, and the cost constants below\n    ...\n    return P   # int array (gpus, slots_per_gpu): the expert ids each GPU holds, -1 for an empty slot\n```\n\nGPU `g` sits on node `g // gpus_per_node`. Every expert needs at least one copy, and no GPU may hold the same expert twice. `place` runs once per task, each time in a fresh process. The starter contains `simulate(placement, experts, src, cluster)`, the exact simulator the grader uses, so you can score any placement on the history before you return it.\n\n### How a step is simulated\n\n**Which copy a token uses.** A token on GPU $g$ that is routed to expert $e$ uses the copy on $g$ itself if $g$ holds $e$. Otherwise it uses a copy on its own node, and if its node has none, any copy. When several copies qualify, it takes copy number (token index + $e$) mod (number of qualifying copies), counting copies in increasing GPU order.\n\n**Dispatch.** A token crosses the network once for each other node it needs, landing on the GPU with the same position in that node. From there, and from its own GPU inside its own node, it travels over NVLink once to each further GPU that runs one of its experts.\n\n**Step time.** With $s$ = `sample_scale` (each trace token stands for $s$ real tokens) and $b$ = `token_bytes`:\n\n$$\nt_{\\text{step}} = \\underbrace{\\max_g r_g \\, s \\, t_{\\text{row}}}_{\\text{expert compute}} \\; + \\; p \\left( \\max_n \\frac{\\max(\\text{out}_n, \\text{in}_n) \\, s \\, b}{G \\, B_{\\text{net}}} + \\max_g \\frac{\\max(\\text{out}_g, \\text{in}_g) \\, s \\, b}{B_{\\text{nvl}}} \\right)\n$$\n\nHere $r_g$ is the number of routed token copies GPU $g$ runs, $t_{\\text{row}}$ = `row_us` = 0.17 µs (forward and backward), $p$ = `a2a_passes` = 4 (dispatch and combine, forward and backward), $G$ = `gpus_per_node`, $B_{\\text{net}}$ = `rdma_GBps` per GPU between nodes, and $B_{\\text{nvl}}$ = `nvlink_GBps` = 150 per GPU inside a node. $\\text{out}_n$ and $\\text{in}_n$ count the network crossings leaving and entering node $n$, and $\\text{out}_g$ and $\\text{in}_g$ count the NVLink transfers leaving and entering GPU $g$. Each step's tokens fill GPUs evenly, 8,192 real tokens per GPU.\n\n### How it is graded\n\nFor each task, the grader simulates your placement and the **default layout** (expert $e$ on GPU $e$ // (experts / gpus), spare slots empty, which is what the starter returns) on the same 32 graded steps. The task's score is your mean step time divided by the default layout's. Your score is the mean over tasks. **Lower is better**: 1.000 means no faster than the default layout, and the lab is passed at **0.82 or below**.\n\n- **Run**: 10 tasks on 3 cluster shapes and 2 kinds of drift, listed under Data. Run shows every task's step time, its parts (compute, between nodes, inside nodes), the busiest GPU's load over the mean, remote nodes per token, CPU time, and your printed output.\n- **Submit**: 20 tasks with new seeds: 6 like Run's, and 14 with kinds of drift or cluster shapes that Run never shows. These include more nodes, fewer experts with more spare slots, and slower networks. Submit reports your score with two parts, over the Run-like tasks and over the rest, and hides per-task results and your printed output.\n\n### Budgets and rules\n\n- Each task gets **5 s of CPU time**, counting every thread and every process your code starts; `time.process_time()` inside `place` reads nearly the same clock. A task over budget, still running after 10 s of wall time, or raising an exception scores 1.5 for that task. Run shows the error message.\n- An invalid placement fails the whole run: a wrong shape, an id outside 0 .. experts - 1 other than -1, an expert with no copy, or the same expert twice on one GPU.\n- Your code sees only the history. The graded steps are generated in a separate process and never sent to it.\n- Libraries: numpy, scipy, math, itertools, collections, heapq, bisect, random, statistics, time, warnings, typing, copy. Everything else, including file access and any dataset, is refused.\n- Write classes as usual: `self.x = ...` works inside a method defined in a class body. Assigning to or deleting an attribute of anything else (`x.y = ...`) is refused, and so are names that reach modules or object internals (`getattr`, `__dict__` and so on).\n- Module level and class bodies may hold only imports from that list, constants, and function and class definitions (`@staticmethod`, `@classmethod` and `@property` work on methods without annotations). Calls, loops and conditions go inside your functions.\n- Your source is capped at 40,000 characters, 600 numeric literals and 2,000 characters of string constants.\n","tags":["mixture-of-experts","expert-parallelism","load-balancing","systems","simulation","competitive"],"id":"5d73196d-8aea-44e0-9c1e-ecc410eca380","img_type":"full","dataset_id":"synthetic","evaluation_metric":"relative_step_time","difficulty":"hard","min_eval_metric":0.82,"category":"Mixture of Experts","title":"Fastest Expert Placement","dataset":"MoE routing traces generated in the grader: drifting domain mix and router preferences on simulated clusters","time_limits_seconds":{"dev":180,"test":300}},{"created_at":"2026-10-28T19:06:55.865000+00:00","type":"general","test_cases":[{"test":"import numpy as np\ndef _task(seed, D, scale, n_test=400):\n    r = np.random.default_rng(seed)\n    while True:\n        w = r.normal(0.0, scale, D)\n        Xa = r.normal(0.0, 1.0, (20, D)) * 3.0 + 10.0\n        ya = (r.random(20) < 1 / (1 + np.exp(-((Xa - 10.0) / 3.0) @ w))).astype(np.int64)\n        if 0 < ya.sum() < 20:\n            break\n    Xb = r.normal(0.0, 1.0, (n_test, D)) * 3.0 + 10.0\n    return Xa, ya, Xb, w\nok = True\nfor D in (2, 10):\n    Xa, ya, Xb, _ = _task(D, D, 1.0)\n    p = np.asarray(fit_predict(Xa, ya, Xb), dtype=float)\n    ok = ok and p.shape == (400,) and bool(np.all(np.isfinite(p)) and np.all((p > 0) & (p < 1)))\nprint(\"valid probabilities:\", ok)","expected_output":"valid probabilities: True"},{"test":"import numpy as np\ndef _task(seed, D, scale, n_test=400):\n    r = np.random.default_rng(seed)\n    while True:\n        w = r.normal(0.0, scale, D)\n        Xa = r.normal(0.0, 1.0, (20, D)) * 3.0 + 10.0\n        ya = (r.random(20) < 1 / (1 + np.exp(-((Xa - 10.0) / 3.0) @ w))).astype(np.int64)\n        if 0 < ya.sum() < 20:\n            break\n    Xb = r.normal(0.0, 1.0, (n_test, D)) * 3.0 + 10.0\n    return Xa, ya, Xb, w\nXa, ya, Xb, w = _task(11, 3, 4.0)\np = np.asarray(fit_predict(Xa, ya, Xb), dtype=float)\na = ((Xb - 10.0) / 3.0) @ w\nprint(\"higher where the true logit is higher:\", bool(p[a > 2].mean() > p[a < -2].mean() + 0.3))","expected_output":"higher where the true logit is higher: True"},{"test":"import numpy as np\ndef _task(seed, D, scale, n_test=400):\n    r = np.random.default_rng(seed)\n    while True:\n        w = r.normal(0.0, scale, D)\n        Xa = r.normal(0.0, 1.0, (20, D)) * 3.0 + 10.0\n        ya = (r.random(20) < 1 / (1 + np.exp(-((Xa - 10.0) / 3.0) @ w))).astype(np.int64)\n        if 0 < ya.sum() < 20:\n            break\n    Xb = r.normal(0.0, 1.0, (n_test, D)) * 3.0 + 10.0\n    return Xa, ya, Xb, w\nXa, ya, Xb, w = _task(12, 2, 4.0)\np = np.asarray(fit_predict(Xa, ya, Xb), dtype=float)\nprint(\"predictions depend on the features:\", bool(np.std(p) > 0.1))","expected_output":"predictions depend on the features: True"}],"lower_is_better":true,"approved_user_libraries":["numpy","scipy","sklearn"],"data_info":"Synthetic small-data logistic tasks generated inside the grader (no dataset download): per task D in 2..10 correlated Gaussian features with random offsets and scales, labels from a logistic model whose weights are drawn from a zero-mean Gaussian with a task-specific hidden scale; 20 training rows (both classes present) and 400 test rows, half spread beyond the training range. Run: 120 tasks. Submit: 300 different tasks. Scored by expected log loss against the true probabilities.","time_limits":{"test":300,"dev":120},"example":{"input":"fit_predict(X_train (20, D) floats, y_train (20,) ints in {0, 1}, X_test (400, D) floats), once per task","output":"array of 400 probabilities strictly inside (0, 1); Submit mean expected log loss about 0.68 for the label frequency (the starter) and 0.57 for a MAP plug-in with a fixed N(0, 1) prior on standardised features; the entropy floor is about 0.30"},"gpu":false,"description":"With twenty labelled examples, a logistic regression can be very sure of itself and very wrong. The book shows the problem on a small separable data set: many decision boundaries fit the training points perfectly, the maximum-likelihood weights run off to infinity, and the plug-in prediction $p(y = 1 \\mid x, \\hat{w})$ becomes 0 or 1 everywhere away from the boundary. Your job is to output class probabilities that are as **honest** as possible: confident where the twenty labels justify it, and not elsewhere.\n\n## The tasks\n\nThe grader generates many small binary classification tasks. In every task:\n\n- there are $D$ features, with $D$ between 2 and 10; the features are correlated Gaussians, and each comes with its own unknown offset and scale;\n- the label follows a logistic model, $p(y = 1 \\mid x) = \\sigma(b + w^\\top z)$, where $z$ is $x$ standardised feature by feature with the population mean and standard deviation (which you are not given);\n- $b$ and $w$ are drawn afresh for every task; $w$ comes from a zero-mean isotropic Gaussian whose scale **differs from task to task and is never given to you**;\n- there are 20 training rows (both classes always appear) and 400 test rows: half are drawn like the training rows, half are spread well beyond the range of the training rows.\n\n## Your function\n\n```python\ndef fit_predict(X_train, y_train, X_test):\n    ...\n    return p_test   # numpy array, shape (400,): P(y = 1 | x) for each test row\n```\n\n- `X_train`: float array of shape (20, D); `y_train`: int array of shape (20,) with values in {0, 1}; `X_test`: float array of shape (400, D).\n- Return one probability per test row, each **strictly** between 0 and 1.\n- The grader calls `fit_predict` once per task, one task after another.\n\nApproved libraries: numpy, scipy, scikit-learn. CPU only.\n\n## Score (lower is better)\n\nThe grader knows the true probability $p^*_i = \\sigma(b + w^\\top z_i)$ of every test row, so it scores your $p_i$ by the **expected log loss**\n\n$$\\ell = -\\frac{1}{400} \\sum_{i=1}^{400} \\Big( p^*_i \\log p_i + (1 - p^*_i) \\log (1 - p_i) \\Big),$$\n\nwhich is the log loss (in nats) averaged over every possible draw of the test labels. It is a proper scoring rule: for each row it is minimised by $p_i = p^*_i$, so overconfidence and underconfidence both cost. The score is the mean of $\\ell$ over all tasks. **Run** scores 120 tasks; **Submit** scores 300 other tasks that Run never shows. You pass at a mean expected log loss of **0.52** or lower; below that, lower ranks higher.\n\n## Budget and gates\n\nAt most 3 seconds per task, and on average 0.5 seconds per task (60 s in total on Run, 150 s on Submit). The run fails (score 99) if `fit_predict` raises, goes over either time limit, returns the wrong number of values, or returns any value that is not finite or not strictly between 0 and 1.\n\nThe report shows your score split into the near rows and the far rows and into the weaker-signal and stronger-signal half of the tasks, your worst task, the score of predicting the smoothed training label frequency everywhere, and the expected log loss of the true probabilities themselves (the entropy floor no method can beat).","tags":["bayesian","logistic-regression","laplace-approximation","posterior-predictive","calibration","log-loss","open-ended","leaderboard"],"id":"5ead5173-8bf6-43ff-8d78-e5da445781fc","img_type":"full","dataset_id":"synthetic","evaluation_metric":"log_loss","difficulty":"medium","min_eval_metric":0.52,"category":"Logistic Regression","title":"Most Honest Predictions From Twenty Labels","dataset":"Synthetic small-data logistic regression tasks (generated in the grader)","time_limits_seconds":{"dev":120,"test":300}},{"description":"Build a complete neural network from scratch using **only NumPy**. You must implement forward propagation, backward propagation (backprop), and parameter updates manually. No PyTorch, TensorFlow, or autograd libraries allowed. Implement a simple MLP that achieves ≥85% accuracy on MNIST by manually computing all gradients.","constraints":["Use ONLY numpy - no PyTorch, TensorFlow, JAX, or autograd libraries","Manually implement forward and backward passes","Manually compute gradients for all parameters","Implement at least: Linear layers, ReLU, Softmax, Cross-Entropy loss","Must support mini-batch training"],"id":"6","test_cases":[{"test":"import numpy as np\nnp.random.seed(42)\nmodel = NeuralNetwork(input_size=784, hidden_size=128, output_size=10)\nX = np.random.rand(10, 784)\nprobs = model.forward(X)\nprint(probs.shape == (10, 10) and np.allclose(probs.sum(axis=1), 1.0))","expected_output":"True"},{"test":"import numpy as np\nnp.random.seed(42)\nmodel = NeuralNetwork(input_size=784, hidden_size=128, output_size=10, lr=0.01)\nX = np.random.rand(32, 784)\ny = np.random.randint(0, 10, 32)\n\n# Get initial predictions\ninitial_probs = model.forward(X)\ninitial_pred = np.argmax(initial_probs, axis=1)\n\n# Train for a few steps\nfor _ in range(10):\n    model.train_step(X, y)\n\n# Get updated predictions\nfinal_probs = model.forward(X)\nfinal_pred = np.argmax(final_probs, axis=1)\n\n# Check that predictions changed (learning happened)\nchanged = not np.array_equal(initial_pred, final_pred)\nprint(changed)","expected_output":"True"},{"test":"import numpy as np\nnp.random.seed(42)\nmodel = NeuralNetwork(input_size=784, hidden_size=128, output_size=10, lr=0.1)\nX = np.random.rand(32, 784)\ny = np.random.randint(0, 10, 32)\n\n# Training should decrease loss\ninitial_loss = model.train_step(X, y)\nfor _ in range(20):\n    loss = model.train_step(X, y)\nfinal_loss = loss\n\nprint(final_loss < initial_loss)","expected_output":"True"}],"approved_user_libraries":["numpy"],"difficulty":"hard","evaluation_metric":"Accuracy","data_info":"MNIST 28x28 grayscale digits (10 classes). Inputs flattened to 784-dim vectors, scaled to [0,1].","time_limits":{"test":"300 seconds","dev":"120 seconds"},"schema":"practical_question_v1","min_eval_metric":0.85,"example":{"input":{"X_batch":"np.array shape (32, 784), values in [0,1]","y_batch":"np.array shape (32,), integer labels 0-9"},"output":{"gradients":"Computed via manual backprop through all layers","forward_output":"np.array shape (32, 10), class probabilities"}},"category":"Neural Network Fundamentals","title":"MNIST: Build Neural Network from Scratch (NumPy Only)","model_specs":"MLP architecture: Input(784) → Hidden(128, ReLU) → Output(10, Softmax). You implement everything from scratch.","memory_limit":"2 GB","dataset":"MNIST","createdAt":"2026-05-13T21:01:44.123000+00:00","time_limits_seconds":{"dev":120,"test":300},"type":"epoch","lower_is_better":false,"gpu":false},{"created_at":"2026-11-01T01:04:11.357000+00:00","type":"general","test_cases":[{"test":"import numpy as np\n_r = np.random.default_rng(21)\n_x = _r.uniform(-2, 2, (3000, 4))\n_y = _x[:, 0] + 0.3 * _r.standard_normal(3000)\n_m = fit(_x, _y)\n_mu, _s = predict(_m, _x[:50])\n_mu, _s = np.asarray(_mu, float), np.asarray(_s, float)\nprint(\"shapes:\", _mu.shape == (50,), _s.shape == (50,))\nprint(\"positive and finite:\", bool((_s > 0).all() and np.isfinite(_mu).all()))","expected_output":"shapes: True True\npositive and finite: True"},{"test":"import numpy as np\n_r = np.random.default_rng(21)\n_x = _r.uniform(-2, 2, (3000, 4))\n_y = 3 * np.sin(2 * _x[:, 0]) + 0.1 * _r.standard_normal(3000)\n_q = _r.uniform(-2, 2, (500, 4))\n_mu, _s = predict(fit(_x, _y), _q)\nprint(\"follows a nonlinear mean:\", bool(np.sqrt(np.mean((np.asarray(_mu, float) - 3 * np.sin(2 * _q[:, 0])) ** 2)) < 0.8))","expected_output":"follows a nonlinear mean: True"},{"test":"import numpy as np\n_r = np.random.default_rng(21)\n_x = _r.uniform(-2, 2, (3000, 4))\n_g = np.where(_x[:, 1] > 0, 2.0, 0.1)\n_y = _x[:, 0] + _g * _r.standard_normal(3000)\n_q = _r.uniform(-2, 2, (500, 4))\n_mu, _s = predict(fit(_x, _y), _q)\n_s = np.asarray(_s, float)\nprint(\"wider where the noise is larger:\", bool(np.median(_s[_q[:, 1] > 0.3]) > 3 * np.median(_s[_q[:, 1] < -0.3])))","expected_output":"wider where the noise is larger: True"},{"test":"import numpy as np\n_r = np.random.default_rng(21)\n_x = _r.uniform(-2, 2, (3000, 4))\n_y = _x[:, 0] + 0.2 * _r.standard_normal(3000)\n_y2 = _y.copy()\n_hit = _r.random(3000) < 0.05\n_y2[_hit] += 5 * _r.standard_t(2.0, int(_hit.sum()))\n_q = _r.uniform(-2, 2, (500, 4))\n_mu, _s = predict(fit(_x, _y2), _q)\nprint(\"sigma survives corrupted labels:\", bool(np.median(np.asarray(_s, float)) < 0.6))","expected_output":"sigma survives corrupted labels: True"}],"approved_user_libraries":["numpy","scipy","sklearn","torch","lightgbm","xgboost"],"lower_is_better":true,"data_info":"Synthetic tasks generated inside the grader (no download): y = f(x) + g(x) * eps with a hidden mean, a hidden input-dependent noise scale, 1200 to 6000 training rows, 4 to 10 input columns and corrupted training labels. Run: 10 tasks. Submit: 32 different tasks, with families Run never shows. Scored against the true conditional distribution on 3,000 test inputs per task.","time_limits":{"test":600,"dev":200},"example":{"input":"fit(X_train, y_train) on one hidden task, then predict(model, X_test) with X_test of shape (3000, d)","output":"(mu, sigma), two float arrays of shape (3000,); the score is the mean excess negative log-likelihood over the true conditional in nats, averaged over tasks (pass at 0.8 or lower)"},"gpu":false,"description":"The book makes both parameters of a Gaussian depend on the input,\n\n$$p(y \\mid x; \\theta) = \\mathcal{N}\\left(y \\mid f_\\mu(x; \\theta),\\ f_\\sigma(x; \\theta)^2\\right) \\qquad \\text{(eq. 2.120)}$$\n\nFixing the variance gives homoscedastic regression. Letting it vary gives heteroskedastic regression, which for a linear model uses the softplus function to keep $\\sigma$ positive. The Gaussian, however, is sensitive to outliers.\n\nHere both problems arrive together. Every task has its own hidden mean and its own hidden noise pattern, and some of the training labels are corrupted. Predict a Gaussian for every new input that is as close as possible to the true distribution of $y$ there: narrow where the noise is small, wide where it is large. Any method is allowed.\n\n## Your functions\n\n```python\ndef fit(X_train, y_train):\n    ...\n    return model          # anything you like\n\ndef predict(model, X):\n    ...\n    return mu, sigma      # two float arrays of shape (n,)\n```\n\n`fit` and `predict` are called once per task. `X_train` has shape `(n, d)` and `y_train` shape `(n,)`. `predict` gets the test inputs only.\n\n## The data\n\nEvery task comes from a generator inside the grader:\n\n$$y = f(x) + g(x)\\,\\varepsilon, \\qquad \\varepsilon \\sim \\mathcal{N}(0, 1)$$\n\n- $n$ runs from 1,200 to 6,000 and $d$ from 4 to 10. Every column of `X` and `y` itself has its own arbitrary units and offset.\n- $f$ is nonlinear in most tasks. $g$ is a different function of $x$, and it changes a lot within one task. A column may matter to $f$, to $g$, to both or to neither.\n- Training labels only: a fraction of them, usually 3% to 10%, have also been hit by a heavy-tailed error (Student $t$ with $\\nu = 2$). Depending on the task the errors are symmetric, push in one direction, or concentrate in one region of the inputs. Which rows are hit is not revealed.\n- Test inputs come from the same distribution as the training inputs, and the test side is clean: your score uses the true $f(x)$ and $g(x)$ directly.\n\n**Run** scores 10 tasks. **Submit** scores 32 different tasks, including mean functions, noise patterns and kinds of corruption that Run never shows.\n\n## Score (lower is better)\n\nFor a test input with true mean $m = f(x)$ and true standard deviation $g = g(x)$, the grader computes the expected Gaussian negative log-likelihood of a clean $y$ under your prediction, minus the same quantity for the true distribution:\n\n$$\\text{excess}(x) = \\log\\frac{\\sigma}{g} + \\frac{g^2 + (m - \\mu)^2}{2\\sigma^2} - \\frac{1}{2}$$\n\nThis is $\\mathrm{KL}\\left(\\mathcal{N}(m, g^2)\\,\\|\\,\\mathcal{N}(\\mu, \\sigma^2)\\right)$ in nats. It is 0 only when $\\mu = m$ and $\\sigma = g$, and no test labels are drawn, so it has no sampling noise. The score is the mean over the test inputs of a task, capped at 10 per task, then the mean over tasks. You pass at **0.8** or lower; below that, lower ranks higher. The starter, a single Gaussian for all inputs, scores about 1.45 on Submit.\n\n## Rules, budget and gates\n\n- `fit` plus `predict` get at most 15 s of CPU per task, counted over all threads and worker processes, so more threads or a larger `n_jobs` do not buy more compute. Each task starts with one thread.\n- The run fails (score 99) if `predict` returns the wrong shape or a non-finite value, if any $\\sigma$ is below $0.001$ times the interquartile scale of `y_train` ((q75 - q25) / 1.349), if your code raises or exits, or if a task goes over budget.\n- Your code may import numpy, scipy, scikit-learn, PyTorch, LightGBM, XGBoost and `math`, `itertools`, `collections`, `warnings`, `heapq`, `bisect`, `typing`, `time`, `random`, `statistics`, `copy`. Files, datasets, environment variables, dynamic attribute access, star imports, other objects' private attributes and metaclasses are refused before grading starts.\n- Classes work as usual: `self.x = ...` is fine directly inside a method whose first parameter is `self`. Assigning to an attribute anywhere else (`x.y = ...`) is refused, because learner code and grader share one process.\n- Your source is limited to 20,000 characters, 300 numeric literals and 1,500 characters of strings outside docstrings.\n\nThe report shows your score, how much of it comes from the mean and how much from the scale, the true coverage of your 90% interval, the score by mean function, noise pattern and corruption, and your CPU use.","tags":["heteroskedastic","gaussian","negative-log-likelihood","robust-regression","uncertainty","open-ended","leaderboard"],"id":"60e60050-0186-4505-ae1f-d989d39b4faf","img_type":"full","dataset_id":"synthetic","difficulty":"hard","evaluation_metric":"excess_nll","min_eval_metric":0.8,"category":"Regression","dataset":"Synthetic heteroskedastic regression tasks with corrupted training labels (generated in the grader)","title":"Sharpest Honest Regressor: Lowest Gaussian NLL with Input-Dependent Noise","time_limits_seconds":{"dev":200,"test":600}},{"created_at":"2026-11-01T03:52:18.683000+00:00","type":"general","constraints":["train gets 90 s on a T4 at reference speed, passed as budget_seconds; CPU over all threads counts, and worker processes are not available","predict_proba gets 12% of that in total, on batches in a hidden order, and must depend only on the model and the reviews in the call","reviews arrive as random word ids with some words removed; no files, no network, nothing pretrained","attributes may be assigned only on self, inside a method defined in a class body","source capped at 30,000 characters, 200 numeric literals, 250 characters of string constants"],"test_cases":[{"test":"\nimport numpy as np\n_r = np.random.default_rng(0)\n\n\ndef _make(n):\n    docs, ys = [], []\n    for i in range(n):\n        y = i % 2\n        k = int(_r.integers(30, 90))\n        d = _r.integers(2, 400, k)\n        cue = _r.integers(400 + 50 * y, 450 + 50 * y, max(2, k // 8))\n        d[_r.integers(0, k, len(cue))] = cue\n        docs.append(d.astype(np.int32))\n        ys.append(y)\n    return docs, np.array(ys, dtype=np.int64)\n\n\n_D, _y = _make(600)\n_T, _z = _make(200)\nimport contextlib\nimport io\nwith contextlib.redirect_stdout(io.StringIO()):     # your own prints are fine: they stay out of the comparison\n    _m = train(_D, _y, 500, 20.0)\n    _p = np.asarray(predict_proba(_m, _T), dtype=np.float64)\n_c = np.clip(_p, 1e-6, 1 - 1e-6)\n_l = float(-(_z * np.log(_c) + (1 - _z) * np.log(1 - _c)).mean())\nprint(_p.shape)","expected_output":"(200,)"},{"test":"\nimport numpy as np\n_r = np.random.default_rng(0)\n\n\ndef _make(n):\n    docs, ys = [], []\n    for i in range(n):\n        y = i % 2\n        k = int(_r.integers(30, 90))\n        d = _r.integers(2, 400, k)\n        cue = _r.integers(400 + 50 * y, 450 + 50 * y, max(2, k // 8))\n        d[_r.integers(0, k, len(cue))] = cue\n        docs.append(d.astype(np.int32))\n        ys.append(y)\n    return docs, np.array(ys, dtype=np.int64)\n\n\n_D, _y = _make(600)\n_T, _z = _make(200)\nimport contextlib\nimport io\nwith contextlib.redirect_stdout(io.StringIO()):     # your own prints are fine: they stay out of the comparison\n    _m = train(_D, _y, 500, 20.0)\n    _p = np.asarray(predict_proba(_m, _T), dtype=np.float64)\n_c = np.clip(_p, 1e-6, 1 - 1e-6)\n_l = float(-(_z * np.log(_c) + (1 - _z) * np.log(1 - _c)).mean())\nprint(bool(np.isfinite(_p).all() and _p.min() >= 0 and _p.max() <= 1))","expected_output":"True"},{"test":"\nimport numpy as np\n_r = np.random.default_rng(0)\n\n\ndef _make(n):\n    docs, ys = [], []\n    for i in range(n):\n        y = i % 2\n        k = int(_r.integers(30, 90))\n        d = _r.integers(2, 400, k)\n        cue = _r.integers(400 + 50 * y, 450 + 50 * y, max(2, k // 8))\n        d[_r.integers(0, k, len(cue))] = cue\n        docs.append(d.astype(np.int32))\n        ys.append(y)\n    return docs, np.array(ys, dtype=np.int64)\n\n\n_D, _y = _make(600)\n_T, _z = _make(200)\nimport contextlib\nimport io\nwith contextlib.redirect_stdout(io.StringIO()):     # your own prints are fine: they stay out of the comparison\n    _m = train(_D, _y, 500, 20.0)\n    _p = np.asarray(predict_proba(_m, _T), dtype=np.float64)\n_c = np.clip(_p, 1e-6, 1 - 1e-6)\n_l = float(-(_z * np.log(_c) + (1 - _z) * np.log(1 - _c)).mean())\nprint(bool(float(((_p > 0.5) == (_z == 1)).mean()) > 0.9))","expected_output":"True"},{"test":"\nimport numpy as np\n_r = np.random.default_rng(0)\n\n\ndef _make(n):\n    docs, ys = [], []\n    for i in range(n):\n        y = i % 2\n        k = int(_r.integers(30, 90))\n        d = _r.integers(2, 400, k)\n        cue = _r.integers(400 + 50 * y, 450 + 50 * y, max(2, k // 8))\n        d[_r.integers(0, k, len(cue))] = cue\n        docs.append(d.astype(np.int32))\n        ys.append(y)\n    return docs, np.array(ys, dtype=np.int64)\n\n\n_D, _y = _make(600)\n_T, _z = _make(200)\nimport contextlib\nimport io\nwith contextlib.redirect_stdout(io.StringIO()):     # your own prints are fine: they stay out of the comparison\n    _m = train(_D, _y, 500, 20.0)\n    _p = np.asarray(predict_proba(_m, _T), dtype=np.float64)\n_c = np.clip(_p, 1e-6, 1 - 1e-6)\n_l = float(-(_z * np.log(_c) + (1 - _z) * np.log(1 - _c)).mean())\nprint(bool(_l < 0.2))","expected_output":"True"}],"lower_is_better":true,"approved_user_libraries":["numpy","scipy","sklearn","torch"],"data_info":"IMDB Movie Reviews (registry id imdb-reviews; Maas et al. 2011), already tokenised. The grader passes integer arrays with random word ids and 5% of words removed: whole reviews to train on, and excerpts of at most 50 consecutive words and at most 40% of the review to predict. Run: 20,000 training reviews and 5,000 held-out reviews from the official training split. Submit: the official 25,000 training and 25,000 test reviews, with different ids, removed words and excerpts. Your code never reads the data files.","time_limits":{"test":360,"dev":300},"gpu":true,"description":"## Best IMDB Sentiment Model Trained from Scratch in a Budget\n\nThe book trains an embedding and a small MLP on the IMDB movie reviews and reports 86% validation accuracy, then turns to models that read reviews as sequences. Here you train on whole reviews and predict from a short excerpt of each held-out review, in a fixed amount of T4 time and with nothing pretrained. Build whatever you think works best, and compete on log loss.\n\n### What you write\n\n```python\ndef train(docs, labels, vocab_size, budget_seconds):\n    ...\n    return model                        # anything predict_proba can use\n\ndef predict_proba(model, docs):\n    ...\n    return p                            # np.ndarray of shape (len(docs),): P(review is positive)\n```\n\n- `docs` is a list of 1-D integer arrays, in reading order. In `train` each array is a whole review, and `labels` is an array of 0 (negative) and 1 (positive).\n- In `predict_proba` each array is an **excerpt**: one run of consecutive words from a held-out review, starting at a random place, of length $\\min(50, \\lceil 0.4\\,L \\rceil)$ for a review of $L$ words. The label belongs to the whole review.\n- Word ids run from 1 to `vocab_size - 1`. The grader assigns them at random, so an id says nothing about the word or how common it is, and the ids differ between Run and Submit. Id 0 never appears, so you can use it for padding. Id 1 means a word that no training review uses, and appears only in excerpts.\n- Punctuation and capitals are already gone. The grader also removed 5% of the words from every review at random before anything else, so neighbours in `docs` are not always neighbours in the original.\n\n### The budget\n\n`train` gets **90 s** on a T4 at reference speed. The grader times this machine with a fixed GPU workload before your code loads, and passes the scaled time as `budget_seconds`, so use that number, not 90. Past it, your process is stopped and the run does not score.\n\n- The clock starts when `train` is called and stops when it returns. Importing and loading your file are free, but module-level code gets at most 20 s and sees no data.\n- CPU time counts too. Across all your threads, the limit is 10% above `budget_seconds` plus 2 s, so more threads do not buy more compute. If you use more than one thread, watch `time.process_time()`. Worker processes are not available, so `n_jobs` above 1 either fails or falls back to threads, which count.\n- `predict_proba` gets 12% of the budget (at least 10 s), in total over all its calls.\n\n### How it is graded\n\nThe grader calls `predict_proba` on batches of 500 excerpts in a hidden order, and takes\n\n$$\n\\text{score} = -\\frac{1}{N} \\sum_{n=1}^{N} \\Big[ y_n \\log p_n + (1 - y_n) \\log (1 - p_n) \\Big]\n$$\n\nwith each $p_n$ clipped to $[10^{-6}, 1 - 10^{-6}]$. **Lower is better.** You pass at **0.60** or below, and past that you are competing on the number. Accuracy is reported alongside but does not count.\n\n- **Run**: 20,000 labelled reviews to train on, and excerpts of 5,000 held-out reviews, all from the official training split. Whole runs of neighbouring reviews are held out together, so reviews of one movie stay on one side. Your printed output and errors are shown. On Run, scores usually come out about 0.02 higher than on Submit, since Run trains on fewer reviews and its held-out reviews happen to be harder.\n- **Submit**: the full 25,000 official training reviews, scored on excerpts of the 25,000 official test reviews, with different ids, removed words and excerpts. What you print is not shown, and errors show only their type.\n\nA slice of the excerpts comes round a second time at the end. `predict_proba` must depend only on the model and the excerpts in that call, so a batch must not change how later excerpts are scored. If the repeated excerpts' mean absolute logit moves by more than 0.1, the run does not score.\n\n### Rules\n\nThese exist because every IMDB label is public. A run that breaks one prints a score of 99 and fails.\n\n- Your code gets no files and no network, and nothing pretrained can be loaded. The grader owns all data access. Code that runs when your file loads may not create or change files outside temporary folders.\n- Allowed imports: numpy, torch, scipy, sklearn, math, random, time, collections, itertools, copy, heapq, bisect, statistics, warnings, typing, enum, abc.\n- Write ordinary classes freely, including `class Net(nn.Module)`. Outside a method of a class, attributes may not be assigned, so write `x.data[:] = ...` rather than `x.data = ...`, and `p.requires_grad_(False)` rather than `p.requires_grad = False`.\n- Source limits: 30,000 characters, 10,000 without comments and docstrings, 200 numeric literals of at most 8 characters each and 400 characters in total, 250 characters of string constants, 32 items in any literal list, tuple, set or dict, 130 names of at most 16 characters, and 40 functions and classes.\n","tags":["nlp","sentiment","rnn","cnn","attention","transformer","bag-of-words","calibration","competitive","pml-book"],"id":"6599a5d4-11d5-42a0-897a-04cf6eada8d5","dataset_id":"imdb-reviews","img_type":"full","difficulty":"hard","evaluation_metric":"log_loss","min_eval_metric":0.6,"category":"NLP","dataset":"IMDB Movie Reviews","title":"Best IMDB Sentiment Model Trained from Scratch in a Budget","time_limits_seconds":{"dev":300,"test":360}},{"created_at":"2026-10-28T19:03:09.728000+00:00","type":"general","test_cases":[{"test":"import numpy as np\n_g = np.random.default_rng(11)\n_proto = np.round(_g.uniform(0, 16, (10, 64)))\ndef _make(n, rate):\n    y = np.arange(n) % 10\n    X = np.clip(np.round(_proto[y] + _g.normal(0, 3.0, (n, 64))), 0, 16)\n    Xm = X.copy()\n    Xm[_g.random(X.shape) < rate] = np.nan\n    return X, Xm, y\n_X, _Xtr, _ytr = _make(400, 0.3)\n_pp = train(_Xtr, _ytr)\n_Xf, _Xte, _yte = _make(30, 0.5)\n_Xq = np.vstack([_Xte, np.full((2, 64), np.nan)])\n_P = np.asarray(_pp(_Xq), dtype=float)\nprint(_P.shape == (32, 10), bool(np.all(np.isfinite(_P)) and _P.min() >= 0), bool(np.allclose(_P.sum(1), 1.0, atol=1e-5)))","expected_output":"True True True"},{"test":"import numpy as np\n_g = np.random.default_rng(11)\n_proto = np.round(_g.uniform(0, 16, (10, 64)))\ndef _make(n, rate):\n    y = np.arange(n) % 10\n    X = np.clip(np.round(_proto[y] + _g.normal(0, 3.0, (n, 64))), 0, 16)\n    Xm = X.copy()\n    Xm[_g.random(X.shape) < rate] = np.nan\n    return X, Xm, y\n_X, _Xtr, _ytr = _make(400, 0.3)\n_pp = train(_Xtr, _ytr)\n_Xf, _Xte, _yte = _make(200, 0.5)\n_P = np.asarray(_pp(_Xte), dtype=float)\nprint(\"half the pixels missing, accuracy above 0.9:\", bool(np.mean(_P.argmax(1) == _yte) > 0.9))","expected_output":"half the pixels missing, accuracy above 0.9: True"},{"test":"import numpy as np\n_g = np.random.default_rng(11)\n_proto = np.round(_g.uniform(0, 16, (10, 64)))\ndef _make(n, rate):\n    y = np.arange(n) % 10\n    X = np.clip(np.round(_proto[y] + _g.normal(0, 3.0, (n, 64))), 0, 16)\n    Xm = X.copy()\n    Xm[_g.random(X.shape) < rate] = np.nan\n    return X, Xm, y\n_X, _Xtr, _ytr = _make(400, 0.3)\n_pp = train(_Xtr, _ytr)\n_Xf, _Xte, _yte = _make(200, 0.0)\n_keep = _g.random(_Xf.shape)\n_few = np.where(_keep < 0.1, _Xf, np.nan)\n_many = np.where(_keep < 0.6, _Xf, np.nan)\n_pf = np.asarray(_pp(_few), dtype=float)[np.arange(200), _yte].mean()\n_pm = np.asarray(_pp(_many), dtype=float)[np.arange(200), _yte].mean()\nprint(\"more pixels seen, more probability on the true class:\", bool(_pm > _pf + 0.05))","expected_output":"more pixels seen, more probability on the true class: True"}],"lower_is_better":true,"approved_user_libraries":["numpy","scipy","sklearn"],"data_info":"scikit-learn 8x8 digits (registry id sklearn-digits, 1,797 images, 64 pixel features 0-16, 10 classes), loaded by the harness through dml_data. A fixed set of 700 digits is Submit's test set; Run tests on 400 of the others. Run: 1,397 training rows with 30% of entries missing completely at random; test regimes 30%/60%/90% scattered and a hidden 4x4 block (100 rows each). Submit: 1,097 training rows with per-row missing rates, 700 test rows over seven hidden regimes. NaN marks a missing pixel; three all-missing rows are added to every predict_proba call.","time_limits":{"test":240,"dev":180},"example":{"input":"train(X_train (1,097 x 64 floats, NaN = missing), y_train) -> predict_proba; predict_proba(X_test (703 x 64, NaN = missing))","output":"a (703, 10) array of class probabilities; Submit mean log loss about 2.31 for the class prior, 0.87-0.90 for mean imputation + logistic regression, 0.65 for the reference"},"gpu":false,"description":"Some pixels of every digit you will classify are gone, and you do not know in advance how many or which ones. Build a classifier that still gives **honest class probabilities** when features go missing, at training time and at test time. The book argues that a generative classifier can handle this in a principled way; here any method is allowed and the scoring rule decides.\n\n## The data\n\nThe 8x8 handwritten digits from scikit-learn (1,797 images, 10 classes). Each image is a row of 64 pixel intensities (integers 0 to 16, stored as floats, row-major so pixel `8*r + c` is row `r`, column `c`). A missing pixel is `NaN`. Missingness never depends on the pixel values themselves (missing completely at random), but it can be scattered over the image or hide a contiguous block of it.\n\n## Your function\n\n```python\ndef train(X_train, y_train):\n    ...\n    return predict_proba\n\ndef predict_proba(X):        # returned by train\n    ...\n    return P                 # numpy array, shape (len(X), 10)\n```\n\n- `X_train`: float array `(N, 64)` with `NaN` for missing pixels. `y_train`: int array `(N,)` with labels 0 to 9.\n- `predict_proba(X)` gets float rows `(M, 64)` that may contain `NaN`, including rows where **every** pixel is missing, and returns one probability distribution over the 10 classes per row: finite, non-negative, each row summing to 1 (within 1e-5).\n- The grader calls `train` once and `predict_proba` once, on all test rows together in shuffled order.\n\nApproved libraries: numpy, scipy, scikit-learn (plus the standard maths modules). CPU only.\n\n## What Run and Submit grade\n\n- **Run**: training rows 1,397 with 30% of their pixels missing at random; 400 test digits, 100 in each of four regimes: 30%, 60% and 90% of pixels missing at random, and a random 4x4 block hidden.\n- **Submit**: 1,097 training rows whose missing rate varies from row to row; 700 held-out test digits that Run never tests on, split evenly over **seven regimes Run does not show you**, ranging from no missing pixels to almost none observed, scattered and in blocks.\n\nBoth also send three rows with every pixel missing; they are not scored, but your probabilities for them must be valid.\n\n## Score (lower is better)\n\nFor each regime, the mean log loss (cross-entropy) of the true labels,\n\n$$\\text{LL} = -\\frac{1}{M}\\sum_{i=1}^{M} \\log p(y_i \\mid x_{i,\\text{obs}}),$$\n\nwith probabilities clipped below at $10^{-6}$. Your score is the mean of the per-regime log losses. Log loss is a proper scoring rule: it is minimised by the true conditional probabilities, so confident mistakes cost a lot and hedging everything costs too. A classifier that predicts the class frequencies scores about 2.30. You pass at **0.84** or lower; below that, lower ranks higher. The report shows, per regime, the missing fraction, your log loss, your accuracy and the class-prior log loss.\n\n## Budget and rules\n\n`train` gets 90 seconds and `predict_proba` 30 seconds. The run fails (score 99) if either raises, goes over its budget, returns the wrong shape, or returns a row that is not a valid probability distribution. The harness owns the data: code that imports anything outside numpy, scipy, scikit-learn and the standard maths modules, imports `sklearn.datasets`, opens files, names a dataset or uses introspection (`getattr`, `globals`, `exec`,...) is refused, and so is code over 40,000 characters or with more than 400 numeric literals.","tags":["missing-data","generative-classifier","naive-bayes","gaussian-discriminant-analysis","calibration","log-loss","open-ended","leaderboard"],"id":"6c088b1a-22c9-4a01-a73f-67c155882ee2","img_type":"full","dataset_id":"sklearn-digits","evaluation_metric":"log_loss","difficulty":"medium","min_eval_metric":0.84,"category":"Classification","title":"Best Classifier When Features Go Missing","dataset":"scikit-learn 8x8 digits with pixels missing at random","time_limits_seconds":{"dev":180,"test":240}},{"description":"You're given a **very deep network** (30 layers) that suffers from training problems, achieving only ~20% accuracy. Your task: **fix the architecture** to achieve high accuracy while **maintaining the depth (≥30 layers)**. The baseline deep network trains poorly due to vanishing gradients. You can modify the architecture however you like (skip connections, normalization, etc.) but you must keep at least 30 layers. Solutions with <30 layers automatically score 0.","constraints":["Network must have ≥30 layers","Solutions with <30 layers automatically score 0","Must train on CPU within 2 minutes","Any architecture modifications allowed","Can add skip connections, normalization, change activations, etc.","Final score = validation accuracy if depth ≥30, else 0"],"scoring_formula":"If layers < 30: score=0. Else: score = val_accuracy. Rank by highest accuracy.","id":"7","test_cases":[{"test":"import torch\nimport torch.nn as nn\n\ntorch.manual_seed(42)\nmodel = DeepNetwork(input_size=784, hidden_size=128, num_classes=10)\nx = torch.randn(16, 784)\n\ntry:\n    output = model(x)\n    print(output.shape == torch.Size([16, 10]))\nexcept:\n    print(False)","expected_output":"True"},{"test":"import torch\nimport torch.nn as nn\n\ntorch.manual_seed(42)\nmodel = DeepNetwork(input_size=784, hidden_size=128, num_classes=10)\n\n# Count Linear layers in the main stack\ndef count_layers(model):\n    count = 0\n    # Check model.layers (plain architecture)\n    if hasattr(model, 'layers') and isinstance(model.layers, nn.ModuleList):\n        for module in model.layers:\n            if isinstance(module, nn.Linear):\n                count += 1\n    # Check model.blocks (residual architecture)\n    if hasattr(model, 'blocks') and isinstance(model.blocks, nn.ModuleList):\n        for block in model.blocks:\n            for module in block.modules():\n                if isinstance(module, nn.Linear):\n                    count += 1\n    return count\n\nlayer_count = count_layers(model)\nprint(layer_count >= 30)","expected_output":"True"},{"test":"import torch\nimport torch.nn as nn\n\ntorch.manual_seed(42)\nmodel = DeepNetwork(input_size=784, hidden_size=128, num_classes=10)\nx = torch.randn(16, 784, requires_grad=True)\n\ntry:\n    output = model(x)\n    loss = output.sum()\n    loss.backward()\n    # Check that gradients flow through the network\n    has_grad = x.grad is not None and x.grad.abs().sum() > 0\n    print(has_grad)\nexcept:\n    print(False)","expected_output":"True"}],"approved_user_libraries":["torch","numpy"],"difficulty":"medium","evaluation_metric":"Accuracy","data_info":"MNIST 28x28 grayscale digits (10 classes). Inputs flattened to 784-dim vectors, scaled to [0,1].","time_limits":{"test":"180 seconds","dev":"120 seconds"},"schema":"practical_question_v1","min_eval_metric":0.85,"example":{"input":{"X":"np.array shape (batch, 784), values in [0,1]","y":"np.array shape (batch,), integer labels 0-9"},"output":{"val_accuracy":"Baseline gets ~20%, you should get 90%+","note":"Network must remain deep (≥30 layers)"}},"category":"Network Optimization","title":"MNIST: Fix Very Deep Network Training","model_specs":"Baseline: 30-layer plain network (trains poorly). You must keep ≥30 layers in your fix.","memory_limit":"2 GB","dataset":"MNIST","createdAt":"2026-05-13T21:01:44.258000+00:00","time_limits_seconds":{"dev":120,"test":180},"type":"epoch","lower_is_better":false,"gpu":false},{"created_at":"2026-10-28T20:57:08.520000+00:00","type":"general","test_cases":[{"test":"import numpy as np\n_r = np.random.default_rng(3)\n_proto = _r.random((10, 28, 28)).astype(np.float32)\ndef _imgs(cls):\n    x = _proto[cls] * 0.7 + 0.3 * _r.random((len(cls), 28, 28)).astype(np.float32)\n    return np.clip(x, 0, 1).astype(np.float32)\n_yl = np.repeat(np.arange(10), 4)\n_Xl, _Xu = _imgs(_yl), _imgs(_r.integers(0, 10, 600))\n_m = train(_Xl, _yl, _Xu)\n_P = np.asarray(predict_proba(_m, _imgs(_r.integers(0, 10, 50))), dtype=float)\nprint(_P.shape == (50, 10), bool(np.all(np.isfinite(_P)) and _P.min() >= -1e-6 and np.abs(_P.sum(1) - 1).max() < 1e-3))","expected_output":"True True"},{"test":"import numpy as np\n_r = np.random.default_rng(3)\n_proto = _r.random((10, 28, 28)).astype(np.float32)\ndef _imgs(cls):\n    x = _proto[cls] * 0.7 + 0.3 * _r.random((len(cls), 28, 28)).astype(np.float32)\n    return np.clip(x, 0, 1).astype(np.float32)\n_yl = np.repeat(np.arange(10), 4)\n_Xl, _Xu = _imgs(_yl), _imgs(_r.integers(0, 10, 600))\n_m = train(_Xl, _yl, _Xu)\n_P = np.asarray(predict_proba(_m, _imgs(np.array([4]))), dtype=float)\nprint(\"one image:\", _P.shape == (1, 10) and abs(float(_P.sum()) - 1.0) < 1e-3)","expected_output":"one image: True"},{"test":"import numpy as np\n_r = np.random.default_rng(3)\n_proto = _r.random((10, 28, 28)).astype(np.float32)\ndef _imgs(cls):\n    x = _proto[cls] * 0.7 + 0.3 * _r.random((len(cls), 28, 28)).astype(np.float32)\n    return np.clip(x, 0, 1).astype(np.float32)\n_yl = np.repeat(np.arange(10), 4)\n_Xl, _Xu = _imgs(_yl), _imgs(_r.integers(0, 10, 600))\n_m = train(_Xl, _yl, _Xu)\n_P = np.asarray(predict_proba(_m, _imgs(_r.integers(0, 10, 1200))), dtype=float)\nprint(\"large batch:\", _P.shape == (1200, 10) and bool(np.abs(_P.sum(1) - 1).max() < 1e-3))","expected_output":"large batch: True"}],"lower_is_better":false,"approved_user_libraries":["numpy","torch","scipy","sklearn"],"data_info":"MNIST from the dml_data registry (mnist), loaded by the grader. Per draw: 40 labelled training images (4 per class, float32 (40, 28, 28) in [0, 1]) with class ids randomly relabelled per draw, 20,000 other unlabelled training images (float32 (20000, 28, 28)), and 5,000 test-split images handed to predict_proba in shuffled order. Each draw runs in a fresh Python process with a 120 s budget for train + predict_proba on a T4 GPU. Run: 1 draw on one half of the test split. Submit: 3 different draws on the other half.","time_limits":{"test":600,"dev":240},"example":{"input":"train(X_lab (40, 28, 28), y_lab (40,), X_unlab (20000, 28, 28)); predict_proba(model, X_test (5000, 28, 28))","output":"P of shape (5000, 10), rows summing to 1; Submit mean accuracy about 0.65 for softmax regression on the 40 labels"},"gpu":true,"description":"Someone hands you 60,000 handwritten digits and the budget to label 40 of them. Semi-supervised learning is about exactly this setting: the labelled set is far too small to learn a classifier from, but the unlabelled images show how the data is shaped, and its methods (self-training and pseudo-labels, entropy minimization, label propagation on graphs, consistency regularization, self-supervised pre-training and distillation) all turn that shape into accuracy. Your job is to build the most accurate digit classifier you can from **40 labels**. Any method is allowed.\n\n## The data\n\nEach **draw** gives you, from the MNIST training split:\n\n- `X_lab`: float32 array of shape `(40, 28, 28)`, pixel values in [0, 1], **4 images of each class**, in random order.\n- `y_lab`: int64 array of shape `(40,)` with their class ids, 0 to 9.\n- `X_unlab`: float32 array of shape `(20000, 28, 28)`: 20,000 other training images, **without labels**.\n\nThe class ids are **randomly relabelled on every draw**: id 3 is not the digit 3, and the mapping changes from draw to draw, so the 40 labels are the only source of class identity. Your classifier is then scored on 5,000 images from the MNIST **test split**, which `train` never sees.\n\n## Your functions\n\n```python\ndef train(X_lab, y_lab, X_unlab):\n    ...\n    return model            # anything you like\n\ndef predict_proba(model, X):\n    ...\n    return P                # numpy array, shape (len(X), 10)\n```\n\n`predict_proba` receives all 5,000 test images in one call (shape `(5000, 28, 28)`, shuffled) and must return a numpy array of class probabilities: finite, non-negative, every row summing to 1 (within 1e-3), column `c` for class id `c`. Using the test images themselves without labels (transductive inference) is allowed.\n\nThe run has an **NVIDIA T4 GPU** (`torch.cuda.is_available()` is True). Approved libraries: numpy, torch, scipy, scikit-learn, plus small standard-library helpers (math, random, time, collections, itertools, functools, dataclasses, typing, copy, heapq, bisect, statistics, warnings, enum, abc).\n\n## Score (higher is better)\n\nThe score is **test accuracy** (the argmax of your probabilities against the true relabelled class), averaged over draws. **Run** scores one draw on 5,000 test images. **Submit** scores **three other draws** (different labelled images, unlabelled pool and relabelling) on 5,000 different test images that Run never uses; the score is the mean of the three accuracies. You pass at a mean accuracy of **0.85**; above that, higher ranks higher. The report also shows the test negative log-likelihood of your probabilities, which does not affect the score.\n\n## Budget and gates\n\n`train` plus `predict_proba` get **120 seconds per draw**, measured by the grader. Each draw runs in a **fresh Python process**: your code is loaded again, sees only that draw's inputs, and nothing learned on an earlier draw carries over. Before calling `train`, the grader seeds `random`, `numpy` and `torch` with the draw's seed. The run fails with a score of 0 if:\n\n- `train` or `predict_proba` raises, or together they take more than 120 s on a draw;\n- the probabilities have the wrong shape, are not finite, are negative, or a row does not sum to 1;\n- your code reads data that the grader did not hand it. The grader owns every byte of data: imports outside the approved list, `dml_data`, dataset loaders, file and network access (`open`, `.load`, `np.load`, `torch.load`, `torch.hub`,...), `getattr`/`setattr`/`globals`/`vars`, and dunder attributes such as `__dict__` or `__class__` are rejected before `train` is called;\n- your source is longer than 30,000 characters, its string constants add up to more than 3,000 characters, it has more than 600 numeric literals, or an integer literal has more than 18 digits. Those caps keep pretrained weights and label tables out of the source: the model must be learned from the 40 labels and the unlabelled pool during the run.\n\nThe report lists, per draw, your accuracy, NLL and the seconds spent in `train` and `predict_proba`.","tags":["semi-supervised","pseudo-labeling","label-propagation","consistency-regularization","few-labels","mnist","open-ended","leaderboard"],"id":"70e324df-437f-491e-bb9b-704ab86a984e","img_type":"full","dataset_id":"mnist","difficulty":"hard","evaluation_metric":"accuracy","min_eval_metric":0.85,"category":"Computer Vision","title":"Most Accurate Classifier from 40 Labels","dataset":"MNIST (40 labelled + 20,000 unlabelled images per draw)","time_limits_seconds":{"dev":240,"test":600}},{"created_at":"2026-10-28T19:11:15.609000+00:00","type":"general","test_cases":[{"test":"import numpy as np\n_r = np.random.default_rng(3)\n_ok = True\nfor _est, _x in ((\"mean\", _r.normal(5.0, 2.0, 12)), (\"median\", _r.exponential(1.0, 7)),\n                 (\"variance\", _r.normal(0.0, 3.0, 20)), (\"proportion\", (_r.random(15) < 0.3).astype(float))):\n    for _lv in (0.8, 0.9, 0.95):\n        _lo, _hi = interval(_x.copy(), _est, _lv)\n        _ok = _ok and bool(np.isfinite(_lo)) and bool(np.isfinite(_hi)) and float(_lo) <= float(_hi)\nprint(\"finite and ordered:\", _ok)","expected_output":"finite and ordered: True"},{"test":"import numpy as np\n_x = np.random.default_rng(4).lognormal(0.0, 1.0, 9)\n_a = interval(_x.copy(), \"mean\", 0.9)\n_b = interval(_x.copy(), \"mean\", 0.9)\nprint(\"same input, same interval:\", bool(float(_a[0]) == float(_b[0]) and float(_a[1]) == float(_b[1])))","expected_output":"same input, same interval: True"},{"test":"import numpy as np\n_lo, _hi = interval(np.zeros(10), \"proportion\", 0.9)\nprint(\"ten failures still leave room above zero:\", bool(float(_hi) > 0.0))","expected_output":"ten failures still leave room above zero: True"},{"test":"import numpy as np\n_lo, _hi = interval(np.array([1.0, 2.5, 3.0, 7.0]), \"variance\", 0.9)\nprint(\"variance interval stays non-negative:\", bool(float(_lo) >= 0.0))","expected_output":"variance interval stays non-negative: True"}],"lower_is_better":true,"approved_user_libraries":["numpy","scipy"],"data_info":"Synthetic datasets generated inside the grader (no download): each is 3 to 60 i.i.d. draws (5 to 60 Bernoulli draws for proportions) from a hidden distribution family with a random shift/scale, with a random level in {0.8, 0.9, 0.95}. Run: 1,600 datasets (400 per estimand) from one set of families and success-rate distribution. Submit: 4,800 datasets (1,200 per estimand) from different families and a different success-rate distribution.","time_limits":{"test":300,"dev":120},"example":{"input":"interval(np.array([0.8, 1.9, 0.4, 3.2, 1.1]), \"mean\", 0.9)","output":"(lo, hi), e.g. (0.67, 2.29) from the Wald interval; Submit mean normalised interval score about 7.4 for the Wald starter (pass at 6.4 or lower)"},"gpu":false,"description":"The book gives two ways to put an interval around an unknown quantity: a Bayesian **credible interval**, which holds $1-\\alpha$ of the posterior mass, and a frequentist **confidence interval**, which covers the true value in $1-\\alpha$ of repeated datasets. The textbook Wald interval $\\hat\\theta \\pm z_{\\alpha/2}\\,\\widehat{\\mathrm{se}}$ can go wrong with small samples and near a boundary: one Bernoulli trial with $y = 0$ gives the interval $(0, 0)$.\n\nHere your intervals are judged on outcomes. The grader draws thousands of small datasets whose true value it knows and scores every interval with the **interval score**, which rewards short intervals and charges for every miss in proportion to how far it misses. Build the method that scores best; any approach is allowed.\n\n## Your function\n\n```python\ndef interval(sample, estimand, level):\n    ...\n    return lo, hi\n```\n\n- `sample`: a 1-D numpy array of floats, i.i.d. draws from an unknown distribution. It has 3 to 60 values (5 to 60 for proportions).\n- `estimand`: one of\n  - `\"mean\"`: the population mean,\n  - `\"median\"`: the population median,\n  - `\"variance\"`: the population variance,\n  - `\"proportion\"`: the success probability $P(y = 1)$; the sample then holds only 0.0 and 1.0.\n- `level`: 0.8, 0.9 or 0.95. Write $\\alpha = 1 - \\text{level}$.\n- Return two finite numbers `lo <= hi`.\n\nThe truth is always the value for the distribution the sample came from, never a property of the sample itself.\n\n## The data\n\nEvery dataset comes from its own draw of a distribution family, a sample size and a level. The families include symmetric, heavy-tailed, skewed positive and bounded shapes. Families that can take any real value are shifted and rescaled by random amounts; positive and bounded families are only rescaled, so they stay non-negative. Proportions come from Bernoulli trials whose success rate is often close to 0 or 1.\n\n**Run** scores 1,600 datasets (400 per estimand). **Submit** scores 4,800 different datasets (1,200 per estimand) drawn from **other distribution families and another distribution of success rates** that Run never shows, so your method has to work on shapes it has not seen.\n\n## Score (lower is better)\n\nFor a dataset with true value $\\theta$, your interval $(l, u)$ and $\\alpha = 1 - \\text{level}$, the interval score is\n\n$$S = (u - l) + \\frac{2}{\\alpha}\\,(l - \\theta)_+ + \\frac{2}{\\alpha}\\,(\\theta - u)_+$$\n\nwhere $(t)_+ = \\max(t, 0)$. Each $S$ is divided by the dataset's true scale so that datasets of every size and unit count equally:\n\n- proportion: $\\sqrt{\\theta(1-\\theta)/n}$, the true standard error of the sample proportion;\n- mean, median, variance: half the width of the central 68% range of the plug-in estimate (the sample mean, the sample median, or the sample variance with $n - 1$) over repeated samples of the same size from the same distribution, which the grader computes by simulation.\n\nYour score is the mean of the normalised interval scores over all datasets. You pass at **6.4** or lower; below that, lower ranks higher. The starter is the Wald interval for every estimand and scores about 7.4 on Submit.\n\n## Rules, budget and gates\n\n- `interval` must be a pure function of its arguments: the same inputs must give the same interval. The grader calls it in batches inside fresh forked copies of your process (nothing carries over between batches) and, at the end, asks again for a random subset of datasets in a different order; any difference fails the run. If you use randomness, such as a bootstrap, seed it from the data.\n- No files, environment variables or dynamic attribute access: `open`, `os`, `pickle`, `np.save` / `np.load`, `getattr`, `globals` and similar are refused before anything runs.\n- All calls together get 60 seconds on Run and 120 seconds on Submit. Work done once at import time is not counted against that budget, but the whole run must finish within the lab's time limit.\n- The run fails (score 1,000,000) if `interval` raises or exits, returns anything other than two numbers, returns an end that is not finite or `lo > hi`, changes its answer for the same input, or goes over the budget.\n\nApproved libraries: numpy, scipy.\n\nThe report shows your score, coverage and mean normalised width for each estimand, and your score and coverage by sample-size band ($n \\le 6$, $7$ to $20$, $21$ to $60$) and by level.","tags":["confidence-intervals","credible-intervals","bootstrap","interval-score","proper-scoring-rules","small-samples","open-ended","leaderboard"],"id":"73281627-5479-466c-96e9-3203769ddc81","img_type":"full","dataset_id":"synthetic","evaluation_metric":"interval_score","difficulty":"hard","min_eval_metric":6.4,"category":"Statistics","title":"Shortest Honest Intervals","dataset":"Synthetic small samples from hidden distribution families (generated in the grader)","time_limits_seconds":{"dev":120,"test":300}},{"created_at":"2026-10-28T17:32:11.175000+00:00","type":"general","test_cases":[{"test":"import numpy as np\n_r = np.random.default_rng(5)\n_n = 3000\ndef _X(n):\n    return {\"Area\": _r.choice(list(\"ABCDEF\"), n), \"VehPower\": _r.integers(4, 16, n), \"VehAge\": _r.integers(0, 20, n),\n            \"DrivAge\": _r.integers(18, 90, n), \"BonusMalus\": _r.integers(50, 160, n), \"VehBrand\": _r.choice([\"B1\", \"B2\", \"B12\"], n),\n            \"VehGas\": _r.choice([\"Diesel\", \"Regular\"], n), \"Density\": _r.integers(1, 5000, n), \"Region\": _r.choice([\"R11\", \"R24\", \"R82\"], n)}\nXa, Xb = _X(_n), _X(200)\nea, eb = _r.uniform(0.1, 1.0, _n), _r.uniform(0.1, 1.0, 200)\nca = _r.poisson(ea * 0.1)\np = np.asarray(fit_predict(Xa, ca, ea, Xb, eb), dtype=float)\nprint(p.shape == (200,), bool(np.all(np.isfinite(p)) and np.all(p > 0)))","expected_output":"True True"},{"test":"import numpy as np\n_r = np.random.default_rng(6)\n_n = 4000\ndef _X(n):\n    return {\"Area\": _r.choice(list(\"ABCDEF\"), n), \"VehPower\": _r.integers(4, 16, n), \"VehAge\": _r.integers(0, 20, n),\n            \"DrivAge\": _r.integers(18, 90, n), \"BonusMalus\": _r.integers(50, 160, n), \"VehBrand\": _r.choice([\"B1\", \"B2\", \"B12\"], n),\n            \"VehGas\": _r.choice([\"Diesel\", \"Regular\"], n), \"Density\": _r.integers(1, 5000, n), \"Region\": _r.choice([\"R11\", \"R24\", \"R82\"], n)}\nXa = _X(_n)\nea = _r.uniform(0.1, 1.0, _n)\nca = _r.poisson(ea * 0.03 * (Xa[\"BonusMalus\"] / 50.0) ** 2)\nXb = {k: np.repeat(v[:2], 1) for k, v in Xa.items()}\nXb[\"BonusMalus\"] = np.array([50, 150])\np = np.asarray(fit_predict(Xa, ca, ea, Xb, np.array([1.0, 1.0])), dtype=float)\nprint(\"riskier policy predicted higher:\", bool(p[1] > 1.5 * p[0]))","expected_output":"riskier policy predicted higher: True"},{"test":"import numpy as np\n_r = np.random.default_rng(7)\n_n = 3000\ndef _X(n):\n    return {\"Area\": _r.choice(list(\"ABCDEF\"), n), \"VehPower\": _r.integers(4, 16, n), \"VehAge\": _r.integers(0, 20, n),\n            \"DrivAge\": _r.integers(18, 90, n), \"BonusMalus\": _r.integers(50, 160, n), \"VehBrand\": _r.choice([\"B1\", \"B2\", \"B12\"], n),\n            \"VehGas\": _r.choice([\"Diesel\", \"Regular\"], n), \"Density\": _r.integers(1, 5000, n), \"Region\": _r.choice([\"R11\", \"R24\", \"R82\"], n)}\nXa = _X(_n)\nea = _r.uniform(0.1, 1.0, _n)\nca = _r.poisson(ea * 0.1)\nXb = {k: np.repeat(v[:1], 2) for k, v in Xa.items()}\np = np.asarray(fit_predict(Xa, ca, ea, Xb, np.array([1.0, 0.5])), dtype=float)\nprint(\"half the exposure, half the claims:\", bool(abs(p[1] / p[0] - 0.5) < 1e-6))","expected_output":"half the exposure, half the claims: True"}],"lower_is_better":true,"approved_user_libraries":["numpy","scipy","pandas","sklearn","statsmodels","lightgbm","xgboost"],"data_info":"Synthetic freMTPL2-like portfolios generated inside the grader (no dataset download): nine rating factors (Area, VehPower, VehAge, DrivAge, BonusMalus, VehBrand, VehGas, Density, Region) as a dict of numpy arrays, exposure in years, and overdispersed claim counts from a hidden claim-rate law. Run: one portfolio (100,000 train / 200,000 test). Submit: three different portfolios with their own hidden laws, same sizes.","time_limits":{"test":300,"dev":120},"example":{"input":"fit_predict(X_train (dict of 9 arrays, 100,000 policies), claims_train, exposure_train, X_test (200,000 policies), exposure_test)","output":"expected claims per test policy, e.g. array([0.031, 0.004, 0.112, ...]); Submit mean Poisson deviance about 0.558 for a constant frequency, 0.505 for the book's ridge, 0.485 for the book's Poisson GLM"},"gpu":false,"description":"A motor insurer prices every policy by the number of claims it expects the policy to make. The book fits this on the French motor third-party liability portfolio (freMTPL2): most policies never claim, the rest claim once or twice, and the metric that separates good models from bad ones is the **Poisson deviance**, not the squared error. Your job is to predict expected claim counts for policies you have not seen, as well as you can.\n\n## The data\n\nThe grader builds a portfolio with the freMTPL2 rating factors and a **hidden claim-rate law**: the expected claims of a policy depend on its factors through a law you never see, and claims are overdispersed (more variable than Poisson). About 95% of policies make no claim and the claim frequency is around 8 to 11% per policy-year. Each policy has:\n\n- `Area`: str, \"A\" to \"F\"\n- `VehPower`: int, 4 to 15\n- `VehAge`: int, vehicle age in years\n- `DrivAge`: int, driver age, 18 to 99\n- `BonusMalus`: int, 50 to 230 (below 100 is a bonus, above is a malus)\n- `VehBrand`: str, 11 brands (\"B1\"... \"B14\")\n- `VehGas`: str, \"Diesel\" or \"Regular\"\n- `Density`: int, inhabitants per square km of the driver's town\n- `Region`: str, 22 regions (\"R11\"... \"R94\")\n\nand an **exposure**: the fraction of a year the policy was in force, in (0, 1].\n\n## Your function\n\n```python\ndef fit_predict(X_train, claims_train, exposure_train, X_test, exposure_test):\n    ...\n    return expected_claims   # numpy array, shape (n_test,)\n```\n\n- `X_train`, `X_test`: dicts mapping the nine column names above to numpy arrays (one entry per policy).\n- `claims_train`: int array, the number of claims each training policy made during its exposure.\n- `exposure_train`, `exposure_test`: float arrays, years in force.\n- Return the **expected number of claims** of each test policy over its own exposure (a count, not a rate per year). Every value must be finite and greater than 0.\n\nApproved libraries: numpy, scipy, pandas, scikit-learn, statsmodels, lightgbm, xgboost. CPU only.\n\n## Score (lower is better)\n\nFor test policies with observed claims $c_i$, exposure $e_i$ and your predictions $\\hat{m}_i$,\n\n$$D = \\frac{2}{\\sum_i e_i} \\sum_i \\left( c_i \\log\\frac{c_i}{\\hat{m}_i} - c_i + \\hat{m}_i \\right)$$\n\nwith $0 \\log 0 = 0$. This is the Poisson deviance applied to the claim frequencies $c_i / e_i$ and weighted by exposure, the metric the book reports. **Run** scores one portfolio (100,000 training policies, 200,000 test policies). **Submit** scores three other portfolios of the same size, each with its own hidden claim law that Run never shows; the score is the mean of their deviances. You pass at a mean deviance of **0.497** or lower; below that, lower ranks higher.\n\n## Budget and gates\n\n`fit_predict` gets 60 seconds per portfolio. The run fails (score 99) if `fit_predict` raises, goes over the budget, returns the wrong number of values, returns a value that is not finite or not positive, or predicts a total number of claims more than 25% away from the observed total (that catches rates returned where counts are expected).\n\nThe report shows, per portfolio, your deviance, the deviance of a constant claim frequency, the deviance of the hidden true expected claims (a practical lower bound), the fraction of that gap you closed, and your predicted against the observed claim total.","tags":["glm","poisson-regression","deviance","insurance","count-data","open-ended","leaderboard"],"id":"74df628d-bc19-4f90-ae97-7872c1202b1a","dataset_id":"synthetic","img_type":"full","evaluation_metric":"poisson_deviance","difficulty":"medium","min_eval_metric":0.497,"category":"Regression","dataset":"Synthetic freMTPL2-like motor insurance portfolios (generated in the grader)","title":"Lowest Poisson Deviance on Insurance Claims","time_limits_seconds":{"dev":120,"test":300}},{"created_at":"2026-11-01T00:09:06.004000+00:00","type":"general","test_cases":[{"test":"import torch\nimport torch.nn as nn\nclass _Main(nn.Module):\n    def __init__(self):\n        super().__init__()\n        self.width, self.max_chunks = 192, 512\n        self.layer = nn.Linear(192, 192)\n    def forward(self, x):\n        return self.layer(x)\nmain = _Main()\ntext = b\"Once upon a time there was a little girl named Lily. She loved to play outside in the sun. \" * 40\nmodel = train(text, main, 2)\nx = torch.cat([torch.full((2, 1), 256), torch.tensor(list(text[:1022])).reshape(2, 511)], dim=1)\nchunks, b, h = encode(model, x)\nlogits = decode(model, x, b, h, main(chunks))\nprint(b.dtype == torch.bool and bool(b[:, 0].all()) and tuple(chunks.shape) == (2, int(b.sum(1).max()), 192))","expected_output":"True"},{"test":"import torch\nimport torch.nn as nn\nclass _Main(nn.Module):\n    def __init__(self):\n        super().__init__()\n        self.width, self.max_chunks = 192, 512\n        self.layer = nn.Linear(192, 192)\n    def forward(self, x):\n        return self.layer(x)\nmain = _Main()\ntext = b\"Once upon a time there was a little girl named Lily. She loved to play outside in the sun. \" * 40\nmodel = train(text, main, 2)\nx = torch.cat([torch.full((2, 1), 256), torch.tensor(list(text[:1022])).reshape(2, 511)], dim=1)\nchunks, b, h = encode(model, x)\nlogits = decode(model, x, b, h, main(chunks))\nprint(tuple(logits.shape) == (2, 512, 256))","expected_output":"True"},{"test":"import torch\nimport torch.nn as nn\nclass _Main(nn.Module):\n    def __init__(self):\n        super().__init__()\n        self.width, self.max_chunks = 192, 512\n        self.layer = nn.Linear(192, 192)\n    def forward(self, x):\n        return self.layer(x)\nmain = _Main()\ntext = b\"Once upon a time there was a little girl named Lily. She loved to play outside in the sun. \" * 40\nmodel = train(text, main, 2)\nx = torch.cat([torch.full((2, 1), 256), torch.tensor(list(text[:1022])).reshape(2, 511)], dim=1)\nchunks, b, h = encode(model, x)\nlogits = decode(model, x, b, h, main(chunks))\nx2 = x.clone()\nx2[:, 300:] = 7\nc2, b2, h2 = encode(model, x2)\nl2 = decode(model, x2, b2, h2, main(c2))\nprint(bool((logits[:, :299] - l2[:, :299]).abs().max() < 0.02))","expected_output":"True"},{"test":"import torch\nimport torch.nn as nn\nclass _Main(nn.Module):\n    def __init__(self):\n        super().__init__()\n        self.width, self.max_chunks = 192, 512\n        self.layer = nn.Linear(192, 192)\n    def forward(self, x):\n        return self.layer(x)\nmain = _Main()\ntext = b\"Once upon a time there was a little girl named Lily. She loved to play outside in the sun. \" * 40\nmodel = train(text, main, 2)\nx = torch.cat([torch.full((2, 1), 256), torch.tensor(list(text[:1022])).reshape(2, 511)], dim=1)\nchunks, b, h = encode(model, x)\nlogits = decode(model, x, b, h, main(chunks))\nprint(4.0 <= b.numel() / int(b.sum()) <= 6.0)","expected_output":"True"}],"approved_user_libraries":["torch","numpy","math","collections","itertools","functools","random","time"],"lower_is_better":true,"data_info":"TinyStories validation text as UTF-8 bytes, with every byte value swapped for another by a secret permutation that changes on each run. train_bytes is a contiguous 6 MB slice. The hidden text comes from other parts of the file and is scored in windows of 512 bytes: 150 KB on Run, two 250 KB slices on Submit. It reaches your code only through encode and decode, after train has returned. The report shows the score, mean chunk length, the numbers you kept and timings.","time_limits":{"test":120,"dev":120},"example":{"input":"b, the chunk starts for the window x = [start symbol, 17, 203, 203, 88, 41, 9, 203, 56]","output":"[True, False, False, False, True, False, False, False, True] for chunks of 4 bytes. Position 0 always starts a chunk."},"gpu":true,"description":"Most language models still start with a tokenizer that someone built by hand. The H-Net paper (Hwang, Wang and Gu, 2025) asks whether a model can learn to split raw bytes by itself, while it trains. This lab hands you the part of an H-Net that stays fixed and leaves everything else to you: how to read bytes, where to cut them, and how to turn chunks back into predictions. The leaderboard ranks you by **bits per byte** on text you never train on. Lower is better.\n\n**The text is scrambled.** The grader takes TinyStories and swaps every byte value for another, using a secret permutation that changes on every run. The patterns survive, but you cannot write a rule about letters or spaces, because your code does not know which byte is which. Your system has to find the structure from the data.\n\n**Contract.** Write three functions:\n\n- `train(train_bytes, main, seconds) -> model`: `main` is the fixed Transformer, 3 layers wide `main.width` = 192, taking at most `main.max_chunks` = 512 chunks. Call `main(chunks)` while training and train it together with your own layers. Return within `seconds`.\n- `encode(model, x) -> (chunks, b, h)`: `x` is a long tensor of shape (B, L) on the GPU, holding bytes, with 256 as the start symbol in `x[:, 0]`. Return `b`, a bool tensor of shape (B, L) marking where chunks start, with `b[:, 0]` True; `chunks`, a float tensor of shape (B, M, 192) with one vector per chunk in order, where M is the most chunks in any row; and `h`, anything you want handed to `decode`.\n- `decode(model, x, b, h, z) -> logits`: `z` of shape (B, M, 192) is the main network's output for your chunks. Return `logits` of shape (B, L, 256), where `logits[:, t]` predicts the byte after `x[:, t]` using only `x[:, :t + 1]`.\n\n**What the grader does.** It calls `train`, keeps its own copy of the trained main network, and zeroes the one you hold, so `main` only works inside `train`. For every hidden window of 512 bytes it calls `encode`, runs the main network on your chunks itself, calls `decode`, and prices every byte. Rows in a batch are shuffled, so a row's neighbour is not its continuation.\n\n**Rules.** The score is set to 99.0 (a fail) if any of these happen:\n\n- Chunks do not average between 4 and 6 bytes on the hidden text. The main network costs compute per chunk, so this is the paper's compute matching.\n- More than 100,000 numbers are still alive outside the main network when `train` returns: parameters, buffers and arrays, not counting gradients. Do not keep the optimizer, the training data or a copy of the main network.\n- Predictions change when later bytes change, when other rows change, or between two calls on the same input.\n- The main network does not matter: each window is given another window's main network output, and its loss has to get worse by at least 0.01 bits per byte.\n- `train` runs past its budget, `encode` and `decode` take more than 20 s over the hidden text, or your code opens the dataset file.\n\n**Score.** Total negative log-likelihood of the hidden bytes in bits, divided by the number of bytes. Clearing 1.78 counts as solved; everything below that is leaderboard.\n\n**Time.** Run and Submit both give `train` 45 s on a T4, so either takes about a minute. They differ only in which text they use. Scores move between runs, because the permutation is new and training stops on the clock: over 16 Submit runs the reference moved between 1.57 and 1.64, so judge a change over more than one run.\n\n**New to this?** The learn section walks through a first submission without code.","tags":["h-net","dynamic-chunking","tokenizer-free","byte-level","bits-per-byte","compute-matching","pytorch","open-ended","leaderboard"],"id":"76682c0a-d553-4d10-b3c5-f6dc18041811","img_type":"pytorch","dataset_id":"tinystories","difficulty":"hard","evaluation_metric":"bits_per_byte","min_eval_metric":1.78,"category":"NLP","dataset":"TinyStories","title":"Build Your Own H-Net","time_limits_seconds":{"dev":120,"test":120}},{"created_at":"2026-10-27T19:29:26.808000+00:00","type":"general","test_cases":[{"test":"r = lower({'base_shape': (2, 3), 'out_shape': (3, 2), 'ops': (('permute', (1, 0)),)})\nprint(type(r) is tuple and len(r) == 2)","expected_output":"True"},{"test":"import numpy as np\n\ndef _t_gather(chain):\n    a = np.arange(int(np.prod(chain[\"base_shape\"])), dtype=np.int64).reshape(chain[\"base_shape\"])\n    for kind, arg in chain[\"ops\"]:\n        if kind == \"reshape\":\n            a = a.reshape(arg)\n        elif kind == \"permute\":\n            a = a.transpose(arg)\n        elif kind == \"expand\":\n            a = np.broadcast_to(a, arg)\n        elif kind == \"shrink\":\n            a = a[tuple(slice(b, e) for b, e in arg)]\n        elif kind == \"pad\":\n            a = np.pad(a, [tuple(p) for p in arg], constant_values=-1)\n        elif kind == \"flip\":\n            a = np.flip(a, axis=tuple(arg))\n    return a\n\ndef _t_eval(e, grid):\n    if type(e) in (int, bool):\n        return np.broadcast_to(np.asarray(e), grid[0].shape)\n    op = e[0]\n    if op == \"range\":\n        return grid[e[1]]\n    a = [_t_eval(x, grid) for x in e[1:] if not isinstance(x, str)]\n    if op == \"add\": return a[0] + a[1]\n    if op == \"mul\": return a[0] * a[1]\n    if op == \"div\": return np.floor_divide(a[0], a[1])\n    if op == \"mod\": return np.mod(a[0], a[1])\n    if op == \"cmplt\": return a[0] < a[1]\n    if op == \"where\": return np.where(a[0], a[1], a[2])\n    if op == \"max\": return np.maximum(a[0], a[1])\n    if op == \"xor\": return np.bitwise_xor(a[0], a[1])\n    if op == \"shl\": return np.left_shift(a[0], a[1])\n    if op == \"cast\": return (a[0] != 0) if e[2] == \"bool\" else a[0].astype(np.int64)\n    raise ValueError(op)\n\ndef _t_cost(*roots):\n    seen, total, stack = set(), 0, [r for r in roots if type(r) is tuple]\n    while stack:\n        e = stack.pop()\n        if e in seen:\n            continue\n        seen.add(e)\n        if e[0] != \"range\":\n            total += 4 if e[0] in (\"div\", \"mod\") else 1\n        stack.extend(x for x in e[1:] if type(x) is tuple)\n    return total\n\ndef _t_check(chain):\n    ref = _t_gather(chain)\n    grid = np.indices(ref.shape)\n    i, v = lower(chain)\n    iv, vv = _t_eval(i, grid), _t_eval(v, grid)\n    return bool(np.array_equal(vv, ref >= 0) and np.array_equal(iv[ref >= 0], ref[ref >= 0])), _t_cost(i, v)\nchain = {'base_shape': (3, 4), 'out_shape': (7, 4),\n         'ops': (('pad', ((1, 0), (2, 1))), ('flip', (1,)), ('permute', (1, 0)))}\nprint(_t_check(chain)[0])","expected_output":"True"},{"test":"import numpy as np\n\ndef _t_gather(chain):\n    a = np.arange(int(np.prod(chain[\"base_shape\"])), dtype=np.int64).reshape(chain[\"base_shape\"])\n    for kind, arg in chain[\"ops\"]:\n        if kind == \"reshape\":\n            a = a.reshape(arg)\n        elif kind == \"permute\":\n            a = a.transpose(arg)\n        elif kind == \"expand\":\n            a = np.broadcast_to(a, arg)\n        elif kind == \"shrink\":\n            a = a[tuple(slice(b, e) for b, e in arg)]\n        elif kind == \"pad\":\n            a = np.pad(a, [tuple(p) for p in arg], constant_values=-1)\n        elif kind == \"flip\":\n            a = np.flip(a, axis=tuple(arg))\n    return a\n\ndef _t_eval(e, grid):\n    if type(e) in (int, bool):\n        return np.broadcast_to(np.asarray(e), grid[0].shape)\n    op = e[0]\n    if op == \"range\":\n        return grid[e[1]]\n    a = [_t_eval(x, grid) for x in e[1:] if not isinstance(x, str)]\n    if op == \"add\": return a[0] + a[1]\n    if op == \"mul\": return a[0] * a[1]\n    if op == \"div\": return np.floor_divide(a[0], a[1])\n    if op == \"mod\": return np.mod(a[0], a[1])\n    if op == \"cmplt\": return a[0] < a[1]\n    if op == \"where\": return np.where(a[0], a[1], a[2])\n    if op == \"max\": return np.maximum(a[0], a[1])\n    if op == \"xor\": return np.bitwise_xor(a[0], a[1])\n    if op == \"shl\": return np.left_shift(a[0], a[1])\n    if op == \"cast\": return (a[0] != 0) if e[2] == \"bool\" else a[0].astype(np.int64)\n    raise ValueError(op)\n\ndef _t_cost(*roots):\n    seen, total, stack = set(), 0, [r for r in roots if type(r) is tuple]\n    while stack:\n        e = stack.pop()\n        if e in seen:\n            continue\n        seen.add(e)\n        if e[0] != \"range\":\n            total += 4 if e[0] in (\"div\", \"mod\") else 1\n        stack.extend(x for x in e[1:] if type(x) is tuple)\n    return total\n\ndef _t_check(chain):\n    ref = _t_gather(chain)\n    grid = np.indices(ref.shape)\n    i, v = lower(chain)\n    iv, vv = _t_eval(i, grid), _t_eval(v, grid)\n    return bool(np.array_equal(vv, ref >= 0) and np.array_equal(iv[ref >= 0], ref[ref >= 0])), _t_cost(i, v)\nchain = {'base_shape': (8, 2, 3), 'out_shape': (2, 4, 6),\n         'ops': (('reshape', (2, 2, 2, 2, 3)), ('permute', (0, 3, 1, 4, 2)), ('reshape', (2, 4, 6)))}\nok, c = _t_check(chain)\nprint(ok and c <= 48)","expected_output":"True"}],"lower_is_better":true,"approved_user_libraries":["numpy","math","collections","itertools","functools","random"],"data_info":"Synthetic movement-op chains generated inside the grader from fixed seeds. Run: 24 chains from six families (transposes, tiling, upsampling, padded windows, strided pooling, random chains). Submit: 45 held-out chains from seven families (im2col patches, pixel shuffle, space-to-depth, circular shifts, zero insertion, kernel flips, longer random chains). Every output has at most 4,096 elements, and correctness is checked exhaustively at every output position.","time_limits":{"test":240,"dev":120},"example":{"input":"lower({'base_shape': (6, 4), 'out_shape': (4, 6), 'ops': (('permute', (1, 0)),)})","output":"(('add', ('mul', ('range', 1), 4), ('range', 0)), True)  # cost 2; the report compares it with the starter's cost for the same chain"},"gpu":false,"description":"Once a compiler lowers a tensor program to loops, movement ops (reshape, permute, expand, shrink, pad, flip, stack) stop being free bookkeeping. Every element a kernel reads needs an address: the flat index into the input buffer, plus a flag saying whether the element is real data or padding. That arithmetic runs once per element of every load, so its cost matters. Write the lowering that turns a chain of movement ops into this index math using as few ALU ops as you can. The leaderboard ranks by **relative cost, lower is better**.\n\n**Contract.** Define `lower(chain) -> (index_expr, valid_expr)`.\n\n- `chain[\"base_shape\"]` is the shape of a contiguous row-major buffer: element `(i0, i1, ...)` is stored at flat index `i0*s0 + i1*s1 + ...`, where `s` are the row-major strides.\n- `chain[\"ops\"]` is a tuple of `(kind, arg)` applied in order to a view of that buffer:\n  - `(\"reshape\", shape)`: same element count, row-major order.\n  - `(\"permute\", order)`: output axis `i` is input axis `order[i]`.\n  - `(\"expand\", shape)`: axes of size 1 broadcast to the new size.\n  - `(\"shrink\", ((begin, end), ...))`: keep elements `begin..end-1` of every axis.\n  - `(\"pad\", ((before, after), ...))`: add `before` and `after` padding elements on every axis. Padding is not part of the buffer.\n  - `(\"flip\", axes)`: reverse the listed axes.\n  - `(\"stack\", (branch0, branch1, ...))`: each branch is a tuple of ops applied to the current view. All branches end with the same shape, and their results are stacked along a new leading axis.\n- `chain[\"out_shape\"]` is the shape after the last op.\n- `(\"range\", i)` is the coordinate along output axis `i`: an i32 with bounds `0 .. out_shape[i] - 1`.\n- `index_expr` (i32) must equal the element's flat buffer index at every output position that is not padding. At padding positions its value does not matter.\n- `valid_expr` (bool) must be True exactly at the positions that are not padding. Return `True` if the chain has no padding.\n\n**Expressions.** Build them from Python ints (i32 constants), `True`/`False`, `(\"range\", i)` and tuples `(op, ...)`:\n\n- `(\"add\", a, b)`, `(\"mul\", a, b)`, `(\"max\", a, b)`, `(\"xor\", a, b)`, `(\"shl\", a, b)`\n- `(\"div\", a, b)` and `(\"mod\", a, b)`: floor division and floor modulo (Python's `//` and `%`)\n- `(\"cmplt\", a, b)` is the bool `a < b`; `(\"where\", c, a, b)`; `(\"cast\", x, \"i32\")` and `(\"cast\", x, \"bool\")`\n\nThese are the week-1 UOp ALU semantics. i32 arithmetic wraps mod 2^32. `add`, `mul`, `div`, `mod` and `shl` take i32 operands; `max`, `xor` and `cmplt` take two operands of the same dtype (i32 or bool); a number literal next to a bool operand becomes a bool. Every subexpression must be defined at every output position: no division or modulo by zero and shift amounts in 0..31, also inside the branch of a `where` that is not taken. Use plain tuples, Python ints and bools (numpy integer scalars are accepted too).\n\n**Score.** Your two expressions are hash-consed together, so structurally equal subexpressions count once. Each unique op costs 1, except `div` and `mod`, which cost 4. Constants and ranges are free. A chain's ratio is your cost divided by the cost of the starter's lowering of that chain, so the starter scores exactly 1.0. The score is the mean ratio over all chains, **lower is better**. A score of at most **0.75** counts as solved; everything below that is leaderboard.\n\n- **Run:** 24 chains from six families: transposes, tiling, upsampling, padded windows, strided pooling and random chains. The report lists every chain with your cost and the starter's.\n- **Submit:** 45 held-out chains from seven different families: image and channel layout transforms, circular shifts, zero insertion, kernel flips and longer random chains. The report shows the mean ratio per family.\n\n**Budget and rules.** `lower` may spend at most 60 s in total on Run and 120 s on Submit. `random` and `numpy.random` are seeded before every chain. Your code may import only `numpy`, `math`, `collections`, `itertools`, `functools`, `random`, `heapq` and `bisect`, and may use an imported module only as `module.name`.\n\n**Gates.** The score is set to 99 and the run fails if any of these happen:\n- An index or valid value is wrong at any output position.\n- An expression is malformed, has the wrong dtype, divides by zero, or has more than 20,000 unique nodes.\n- `lower` raises or exits, or the time budget runs out.\n- Your code reads files, uses introspection (`globals`, `vars`, `getattr`/`setattr`, frames, tracebacks, `eval`/`exec`), names a special `__dunder__` attribute, changes an imported module or name, or redefines a built-in name at module level.","tags":["compilers","movement-ops","rangeify","symbolic","index-math","tinygrad","open-ended","leaderboard"],"id":"78868c50-937b-4a1b-8c05-fb4897286846","img_type":"full","dataset_id":"synthetic","evaluation_metric":"relative_cost","difficulty":"hard","min_eval_metric":0.75,"category":"Compilers","title":"Cheapest Index Math","dataset":"Synthetic movement-op chains (reshape, permute, expand, shrink, pad, flip, stack)","time_limits_seconds":{"dev":120,"test":240}},{"created_at":"2026-11-01T03:09:58.982000+00:00","type":"general","constraints":["train gets about 30 s per fold and predict_proba a tenth of that, scaled to the machine's measured speed; a call more than 15% late scores 0","predict_proba returns finite, non-negative rows of shape (len(X), 10) that sum to 1 within 1e-3","numpy, torch, scipy and scikit-learn on a Tesla T4; the harness owns all data access","at most 8000 characters of code, 200 numbers, 400 characters of strings, 130 defined names","attribute assignment only on self inside a method of a class"],"test_cases":[{"test":"import numpy as np\n_r = np.random.default_rng(0)\n_pats = _r.integers(0, 2, (10, 5, 5, 3)) * 255\ndef _make(n):\n    X = _r.integers(0, 40, (n, 32, 32, 3)).astype(np.uint8)\n    y = _r.integers(0, 10, n).astype(np.int64)\n    for i in range(n):\n        a, b = _r.integers(0, 28, 2)\n        X[i, a:a + 5, b:b + 5] = _pats[y[i]]\n    return X, y\n_Xa, _ya = _make(800)\n_Xb, _yb = _make(200)\n_m = train(_Xa, _ya, 8.0)\n_p = np.asarray(predict_proba(_m, _Xb), dtype=float)\nprint(_p.shape)","expected_output":"(200, 10)"},{"test":"import numpy as np\n_r = np.random.default_rng(0)\n_pats = _r.integers(0, 2, (10, 5, 5, 3)) * 255\ndef _make(n):\n    X = _r.integers(0, 40, (n, 32, 32, 3)).astype(np.uint8)\n    y = _r.integers(0, 10, n).astype(np.int64)\n    for i in range(n):\n        a, b = _r.integers(0, 28, 2)\n        X[i, a:a + 5, b:b + 5] = _pats[y[i]]\n    return X, y\n_Xa, _ya = _make(800)\n_Xb, _yb = _make(200)\n_m = train(_Xa, _ya, 8.0)\n_p = np.asarray(predict_proba(_m, _Xb), dtype=float)\nprint(bool(np.isfinite(_p).all() and _p.min() >= -1e-6 and np.abs(_p.sum(1) - 1).max() < 1e-3))","expected_output":"True"},{"test":"import numpy as np\n_r = np.random.default_rng(0)\n_pats = _r.integers(0, 2, (10, 5, 5, 3)) * 255\ndef _make(n):\n    X = _r.integers(0, 40, (n, 32, 32, 3)).astype(np.uint8)\n    y = _r.integers(0, 10, n).astype(np.int64)\n    for i in range(n):\n        a, b = _r.integers(0, 28, 2)\n        X[i, a:a + 5, b:b + 5] = _pats[y[i]]\n    return X, y\n_Xa, _ya = _make(800)\n_Xb, _yb = _make(200)\n_m = train(_Xa, _ya, 8.0)\n_p = np.asarray(predict_proba(_m, _Xb), dtype=float)\nprint(bool((_p.argmax(1) == _yb).mean() > 0.6))","expected_output":"True"}],"lower_is_better":false,"approved_user_libraries":["numpy","torch","scipy","sklearn"],"data_info":"CIFAR-10 from the dml_data registry (id cifar10). The registry holds a subset of the public dataset, the first 10,000 training images and the first 2,000 test images, which this lab pools into 12,000 images of 32x32 RGB, 10 classes, roughly balanced.\n\nEach split is stratified: about 8,000 images to train on, about 4,000 to score. The grader passes X_train as uint8 (n, 32, 32, 3) and y_train as int64 (n,). It passes the scored images to predict_proba as uint8 (m, 32, 32, 3), in random order, with no labels.\n\nRun scores one split. Submit scores a different 3-fold split, so every one of the 12,000 images is scored exactly once.\n\nEvery image is re-dithered by up to 2 levels per channel and randomly mirrored on every run. Your process receives only the arrays above, and it cannot read the dataset from disk.","time_limits":{"test":420,"dev":180},"gpu":true,"description":"## Best CIFAR-10 Classifier in a Fixed Training Budget\n\nYou get about 8,000 labelled CIFAR-10 images, one GPU and a stopwatch. Build whatever you think learns fastest, train it before the time runs out, and classify about 4,000 images you have never seen. The most accurate classifier wins.\n\nAny method is allowed. The only things that count are the accuracy you reach and whether you finish on time.\n\n### What you write\n\n```python\ndef train(X_train, y_train, budget_seconds):\n    ...\n    return model                    # anything you like\n\ndef predict_proba(model, X):\n    ...\n    return P                        # np.ndarray, shape (len(X), 10)\n```\n\n- `X_train`: `uint8` array of shape `(n, 32, 32, 3)`, channels last, values 0 to 255. `y_train`: `int64` array of shape `(n,)`, class ids 0 to 9 in the usual CIFAR-10 order (airplane, automobile, bird, cat, deer, dog, frog, horse, ship, truck).\n- `budget_seconds`: a float, how long `train` may run on this machine (see below).\n- `X` in `predict_proba`: `uint8` array of shape `(m, 32, 32, 3)`.\n- `P`: finite, non-negative rows that each sum to 1 (within $10^{-3}$).\n\n### How it is graded\n\nYour score is **top-1 accuracy** on the held-out images. **Higher is better**, and the lab is passed at **0.60 or above**. The mean negative log-likelihood of the true class is printed next to it as a tie-breaker, and it does not affect passing.\n\n- **Run**: one split: train on about 8,000 images, score on about 4,000.\n- **Submit**: a 3-fold split of all 12,000 images that differs from Run's. Each fold trains from scratch, and your score pools the folds, so every image is scored exactly once.\n\nEach fold runs in a fresh process that loads your file from scratch, so nothing you learn or store on one fold reaches the next. Test images reach your process only after `train` has returned.\n\n**The score is noisy.** Training on a GPU is not exactly repeatable. In calibration, repeating the same code moved a Submit score with a standard deviation of 0.2 to 0.4 percentage points, and up to about 0.9 points between the best and worst of five runs. A Run score, with one split, moved a little more: 0.2 to 0.6 points. Code that fits only a few epochs into the budget can swing by several points, so compare ideas over more than one run.\n\n### The budget\n\n- `train` gets about **30 seconds** per fold, and `predict_proba` gets a tenth of whatever `train` got.\n- Before your file loads, the grader times a fixed training workload on the GPU it was given and scales `budget_seconds` to match, so a slower machine gets more seconds and a faster one fewer. Read `budget_seconds`, do not hard-code it. Your program should buy about the same amount of training on any machine.\n- The clock is the grader's, and it runs from the moment `train` is called until it returns. Importing libraries and loading your file are free, but a file that takes over 20 s to load is stopped.\n- Stay inside `budget_seconds`. Machines still differ a little after scaling, so the grader only stops a call at 15% past its budget. A stopped call scores 0 for the whole run.\n- You get a Tesla T4 GPU and PyTorch. If a run does not get a GPU, or the GPU is far from the expected speed, the grader says it did **not score** the run. That is a platform problem, not your code, so run it again.\n\n### Rules\n\n- Libraries: numpy, torch, scipy and scikit-learn, plus small standard-library helpers (math, random, time, collections, itertools, copy, heapq, bisect, statistics, warnings, typing, enum, abc). torchvision and tinygrad are not available here.\n- The harness owns the data. All of CIFAR-10 and its labels are public, so these are refused: reading or writing files, dataset loaders, network access, `dml_data`, serialization (`torch.save`, `torch.load`, `np.load`, `pickle`), and pretrained weights. Weights have to come from your `train`.\n- Write classes the ordinary way: `self.fc = nn.Linear(...)` inside a method is fine, and so are `torch.backends.cudnn.benchmark` and `.deterministic`. Outside a method, assigning to any other attribute is refused, so use `p.requires_grad_(False)` rather than `p.requires_grad = False`, and keep other state in local variables, lists or dicts.\n- Dynamic access is refused (`getattr`, `setattr`, `vars`, `globals`, `exec`, names starting with two underscores other than the usual methods such as `__init__`), and so are `os`, `sys` and text or byte decoders (`ord`, `chr`, `tobytes`, `encode`, `decode`).\n- A file can carry at most 8,000 characters of code (comments and docstrings do not count), 200 numbers of at most 8 characters each, 400 characters of strings, 130 names you define, each up to 20 characters, and 32 items in any one list, tuple, set or dict you write out. Those caps leave ordinary code plenty of room. A table of the public labels that fits inside them covers about 1% of the images, which is worth less than a point.\n- Every image is re-dithered by up to 2 levels per channel and randomly mirrored on each run, so looking an image up by its exact bytes does not work. Neither change alters what class it shows.\n\nA refused file, an exception, a wrong shape, invalid probabilities or a missed budget sets the score to 0 and fails the run.\n","tags":["cnn","resnet","batch-normalization","data-augmentation","one-cycle","cifar10","time-budget","competitive","pml-book"],"id":"78ce204b-faea-4e2c-9b87-0338f4cd99fb","dataset_id":"cifar10","img_type":"full","difficulty":"hard","evaluation_metric":"accuracy","min_eval_metric":0.6,"category":"Computer Vision","dataset":"CIFAR-10 (12,000-image registry subset)","title":"Best CIFAR-10 Classifier in a Fixed Training Budget","time_limits_seconds":{"dev":180,"test":420}},{"created_at":"2026-10-28T18:58:28.428000+00:00","type":"general","test_cases":[{"test":"import numpy as np\nrng = np.random.default_rng(0)\nX = rng.normal(size=(200, 4))\nX[rng.random(X.shape) < 0.3] = np.nan\nm, v = impute(X.copy())\nm, v, h = np.asarray(m, float), np.asarray(v, float), np.isnan(X)\nprint(m.shape == X.shape and v.shape == X.shape and bool(np.all(np.isfinite(m[h]))) and bool(np.all(v[h] >= 1e-4)) and bool(np.allclose(m[~h], X[~h])))","expected_output":"True"},{"test":"import numpy as np\nrng = np.random.default_rng(1)\nz = rng.normal(size=400)\nX = np.column_stack([z, z + 0.1 * rng.normal(size=400), rng.normal(size=400)])\nXm = X.copy()\nhide = rng.random(400) < 0.25\nXm[hide, 1] = np.nan\nm, v = impute(Xm.copy())\nerr = np.asarray(m, float)[hide, 1] - X[hide, 1]\nprint(bool(np.sqrt(np.mean(err ** 2)) < 0.3))","expected_output":"True"},{"test":"import numpy as np\nrng = np.random.default_rng(2)\nz = rng.normal(size=400)\nX = np.column_stack([z, z + 0.1 * rng.normal(size=400), rng.normal(size=400)])\nXm = X.copy()\nhide = rng.random(400) < 0.25\nXm[hide, 1] = np.nan\nm, v = impute(Xm.copy())\nm, v = np.asarray(m, float)[hide, 1], np.asarray(v, float)[hide, 1]\nnll = 0.5 * np.log(2 * np.pi * v) + 0.5 * (X[hide, 1] - m) ** 2 / v\nprint(bool(np.mean(nll) < 0.5))","expected_output":"True"}],"lower_is_better":true,"approved_user_libraries":["numpy","scipy","sklearn","lightgbm","xgboost","math","random","itertools","functools","collections","time","copy"],"data_info":"Each task: impute(X_missing) gets one float64 (n, d) matrix with NaN for hidden entries, standardized columns (log on skewed ones). Run: Wine Quality red, 1,348 x 11, MCAR 30%; California Housing 3,000 x 8, MAR 30%. Submit: four disjoint 5,000 x 8 California Housing tables (two MCAR, two MAR), 30% hidden. Data come from dml_data registry ids wine-quality and california-housing, loaded by the grader only.","time_limits":{"test":360,"dev":180},"example":{"input":"X_missing = array([[ 0.31,   nan, -1.20, ...], [  nan, 0.85,  0.04, ...], ...])  # (5000, 8), 30% NaN","output":"(mean, var): two (5000, 8) arrays; e.g. mean[0, 1] = 0.42, var[0, 1] = 0.37. The grader prints per-task NLL / RMSE / 90% coverage and the mean NLL, e.g. 0.92"},"gpu":false,"description":"Fill in the missing entries of a real data table **and say how sure you are about each one**. The grader hides about 30% of the entries of a numeric table. For every hidden entry $x$ you return a predictive mean $m$ and a predictive variance $v$, and you are scored by the Gaussian negative log-likelihood of the true value:\n\n$$\\mathrm{NLL} = \\tfrac{1}{2}\\log(2\\pi v) + \\frac{(x - m)^2}{2v}$$\n\naveraged over the hidden entries, in nats. A confident guess that is right scores well, a confident guess that is wrong is punished hard, and a vague guess sits in between. The leaderboard ranks by the **mean NLL over the four Submit tasks, lower is better**; you pass at **1.25 or below**. Filling every hidden entry with its column mean and the column variance scores about 1.48.\n\n**Contract.** Define `impute(X_missing) -> (mean, var)`.\n\n- `X_missing` is a float64 array of shape `(n, d)`; `NaN` marks a hidden entry. Rows are records, columns are features.\n- Return two arrays of shape `(n, d)`. On hidden entries `mean` is your prediction and `var` your predictive variance (finite and at least `1e-4`). On observed entries `mean` must equal the input (within `1e-6`); `var` there is ignored.\n- The matrix you are given is the only data you get: fit whatever you like on it. Your code is loaded afresh for every task, so nothing carries over from one call to the next.\n\n**The data.** Each table comes from a registry dataset, cleaned the same way: duplicate rows dropped, right-skewed positive columns log-transformed, rows with any value more than 5 standard deviations from its column mean removed, then every column standardized to mean 0 and variance 1 over the whole cleaned dataset.\n\n- California Housing, 8 columns in this order: log median income, house age, log average rooms, log average bedrooms, log population, log average occupancy, latitude, longitude (20,407 rows after cleaning).\n- Wine Quality (red), 11 columns: fixed acidity, volatile acidity, citric acid, log residual sugar, log chlorides, log free sulfur dioxide, log total sulfur dioxide, density, pH, log sulphates, alcohol (1,348 rows).\n\nEntries are hidden in one of two ways:\n\n- **MCAR**: every entry is hidden independently with probability 0.3.\n- **MAR**: two columns are never hidden. Each other column is hidden with a probability that is a logistic function of one of those two columns (rising for some columns, falling for others), tuned so that 30% of all entries are hidden. Whether an entry is hidden depends only on values you can see.\n\n**Run** (development): Wine Quality with MCAR (all 1,348 rows) and a 3,000-row California Housing table with MAR. **Submit** (graded): four held-out California Housing tables of 5,000 rows each, with no record shared between tables: two MCAR and two MAR, driven by other columns than on Run.\n\n**Budget and rules.**\n\n- At most 60 seconds per `impute` call (CPU).\n- Libraries: numpy, scipy, scikit-learn, lightgbm, xgboost and the standard maths and container modules (math, random, itertools, functools, collections, heapq, bisect, time, warnings, ...).\n- The datasets are public, so a submission may not bring its own copy of them: no file, network or dataset access (`dml_data`, `sklearn.datasets`, `open`, loaders), no `getattr`/`globals`-style introspection, and at most 20,000 characters of code, 2,000 characters of string literals and 400 numeric literals.\n- A run fails with score 99 on any gate: an exception, a wrong shape, a non-finite mean or variance on a hidden entry, a variance below `1e-4`, a changed observed entry, a call over the time budget, or forbidden code.\n\nThe grader prints, per task, the rows, hidden entries, NLL, RMSE and the 90% coverage (the share of hidden values inside $m \\pm 1.645\\sqrt{v}$), then the score.","tags":["imputation","missing-data","multivariate-gaussian","gaussian-mixture","em","uncertainty","proper-scoring-rule","murphy-pml","open-ended","leaderboard"],"id":"7b904dda-f086-4701-a521-938ad5228f97","dataset_id":"california-housing","img_type":"full","evaluation_metric":"nll","difficulty":"hard","min_eval_metric":1.25,"category":"Machine Learning","dataset":"California Housing (Submit) and Wine Quality (Run), cleaned and standardized","title":"Best Imputer with Honest Uncertainty","time_limits_seconds":{"dev":180,"test":360}},{"created_at":"2026-09-23T04:11:29.076719+00:00","type":"general","constraints":["numpy only; no network access","Implement class Autoscaler(min_replicas, max_replicas, replica_capacity, cold_start_s) with step(t, offered_load, queue, ready, pending) -> desired total replicas","step is called once per simulated second; keep it fast (thousands of calls per trace)"],"last_updated":"2026-09-23T04:11:29.076719+00:00","test_cases":[{"test":"a = Autoscaler(2, 20, 10.0, 100.0)\nprint(hasattr(a, 'step'))","expected_output":"True"},{"test":"a = Autoscaler(2, 20, 10.0, 100.0)\nd = a.step(0.0, 30.0, 0.0, 2, 0)\nprint(2 <= float(d) <= 20)","expected_output":"True"},{"test":"a = Autoscaler(2, 20, 10.0, 100.0)\nlow = [a.step(t, 5.0, 0.0, 2, 0) for t in range(200)]\nb = Autoscaler(2, 20, 10.0, 100.0)\nhigh = [b.step(t, 190.0, 50.0, 2, 0) for t in range(200)]\nprint(float(high[-1]) > float(low[-1]))","expected_output":"True"}],"lower_is_better":true,"approved_user_libraries":["numpy"],"data_info":"Synthetic one-hour traffic traces generated inside the grader with numpy (no downloads): a daily wave, a spike, a ramp, a noisy wave and a double spike, between roughly 20 and 70 requests per second, with a replica capacity of 10 requests per second and a cold start of 90 to 100 seconds.","time_limits":{"test":120,"dev":60},"example":{"input":"step(t=600.0, offered_load=48.5, queue=12.0, ready=5, pending=1)","output":"an integer such as 7: the total replicas the fleet should have; the grader boots one more and reports the queueing penalty and replica-hours per trace"},"model_specs":"Your choice of policy. The grader owns the fleet model (fluid queue, cold starts, clamping to [min, max]) and the traffic traces; it only sees the replica count you return each second.","gpu":false,"description":"# Design Your Own Autoscaler\n\nA fleet of identical inference replicas serves a traffic stream that rises and falls. Every replica costs money for every second it exists, including the seconds it spends booting, and a new replica takes a fixed cold-start time to become ready. Your autoscaler decides, once per second, how many replicas the fleet should have. The grader charges you for the replica-seconds you used and penalizes every second in which requests were queueing.\n\n```python\nclass Autoscaler:\n    def __init__(self, min_replicas, max_replicas, replica_capacity, cold_start_s):\n        ...\n\n    def step(self, t, offered_load, queue, ready, pending):\n        ...\n        return desired_replicas\n```\n\n- `replica_capacity` is the requests per second one ready replica can serve; `cold_start_s` is how long a newly requested replica takes to become ready.\n- `step` is called every second with the time `t`, the `offered_load` in requests per second at that moment, the current `queue` backlog in requests, the number of `ready` replicas and the number of `pending` replicas still booting.\n- Return the total number of replicas you want (ready plus pending). The grader clamps it to `[min_replicas, max_replicas]`. Asking for more than you have starts boots; asking for fewer retires ready replicas immediately.\n\nHow you smooth the signal, whether you predict, how much headroom you keep, when you scale down: all yours.\n\n## How it is graded\n\nThe grader runs your autoscaler against five hidden one-hour traffic traces (a daily wave, a sudden spike, a ramp, a noisy wave and a double spike; the Run and Submit graders use different random draws and cold starts) with a fluid model of the fleet: capacity is `ready x replica_capacity`, load beyond capacity accumulates as a queue, and the queue drains when capacity is free. For each trace it computes\n\n- `replica_hours`: the sum over seconds of `ready + pending`, divided by 3600;\n- `violation_fraction`: the fraction of seconds in which the queue would take more than one second to drain.\n\nThe score is the mean over traces of `replica_hours x (1 + 30 x violation_fraction)`. Lower is better. Keeping the fleet at its maximum is safe and expensive; keeping it at its minimum is cheap and fails the penalty. Only numpy is available.\n","tags":["autoscaling","cold-start","serving","inference","queueing","open-ended"],"id":"7d2f6a1c-3b8e-4c5d-9a0f-1e2b3c4d5e6f","difficulty":"medium","evaluation_metric":"replica_hours_with_queue_penalty","schema":"Autoscaler(min_replicas: int, max_replicas: int, replica_capacity: float, cold_start_s: float); step(t: float, offered_load: float, queue: float, ready: int, pending: int) -> int","min_eval_metric":17.0,"category":"Inference","title":"Design Your Own Autoscaler","time_limits_seconds":{"dev":60,"test":120}},{"created_at":"2026-10-19T14:19:44.291000+00:00","type":"general","test_cases":[{"test":"import math\nm = train('hello world hello')\nlp = logprob(m, 'hello')\nprint(len(lp) == 5 and all(x <= 0 for x in lp))","expected_output":"True"},{"test":"import math\nm = train('abababababababab')\nlp = logprob(m, 'ab')\nprint(lp[1] > math.log(0.45))","expected_output":"True"},{"test":"import math\nm = train('the cat sat on the mat. the cat sat.')\nlp = logprob(m, 'the cat')\nprint(sum(lp) > 7 * math.log(1 / 8))","expected_output":"True"},{"test":"import math\nm = train('aaaa bbbb')\nlp = logprob(m, 'a#')\nprint(all(math.isfinite(x) for x in lp))","expected_output":"True"}],"lower_is_better":true,"approved_user_libraries":["numpy","torch","math","collections","random","time"],"data_info":"TinyStories validation text (19 MB, one string). Submit: train on characters 6,000,000-7,000,000, score characters 7,010,000-7,110,000 in 2,048-character segments, 120 s training budget. Run: train on 0-300,000, score 310,000-340,000, 45 s budget. The harness reports your bits per character, the training time and a bigram baseline.","time_limits":{"test":300,"dev":120},"example":{"input":"train(text) on the training slice, then logprob(model, 'Once upon a time')","output":"[-3.1, -1.2, -0.4, ...] (one natural-log probability per character); bits per char = -(sum) / 16 / ln 2"},"gpu":false,"description":"Build the best character-level language model of TinyStories you can inside a training budget. Any method counts: smoothed n-grams, an MLP over a context window, a recurrent net, a small transformer, or a mixture of several. The leaderboard ranks by **bits per character** on held-out text, lower is better.\n\n**Contract.** Implement two functions:\n\n- `train(text: str) -> model` receives the training slice as one string and returns any object.\n- `logprob(model, seq: str) -> list[float]` returns one natural-log probability per character of `seq`: entry `i` is `log p(seq[i] | seq[:i])`. The first entry is the unconditional probability of the first character. Every character, including ones never seen in training, must get a finite log-probability no greater than 0.\n\n**Budget.** Submit: `train` gets 1,000,000 characters and must return within 120 seconds of wall-clock time on CPU. Held-out scoring uses 100,000 characters from a different part of the corpus, scored in independent 2,048-character segments, so your model may use any context inside a segment. Run uses a 300,000-character slice, a 45-second budget and a 30,000-character test slice.\n\n**Score.** bits per character = -(sum of your log-probabilities) / (characters scored) / ln 2. The harness reports a Laplace-smoothed bigram on the same slices next to your number. Clearing 2.9 counts as solved; everything below that is leaderboard.\n\n**Gates.** The score is set to 99.0 (a fail) if `train` runs over budget, if any log-probability is non-finite or positive, if the returned list has the wrong length, or if the model is not causal: the harness changes one later character in a segment and requires the earlier log-probabilities to be unchanged to 1e-6. Dropout or sampling at scoring time will fail that check.","tags":["language-modeling","n-gram","transformer","open-ended","leaderboard"],"id":"7f65cc18-cd7d-4ba9-ad67-ad2e50b8667c","img_type":"pytorch","dataset_id":"tinystories","evaluation_metric":"bits_per_char","difficulty":"medium","min_eval_metric":2.9,"category":"Language Modeling","title":"Lowest Bits per Character","dataset":"TinyStories","time_limits_seconds":{"dev":120,"test":300}},{"description":"Implement an **optimizer update rule** using only NumPy. You will write a function `optimizer_step(param, grad, state, lr)` that takes a parameter array and its gradient, then returns the updated parameter.\n\nThe training harness handles forward/backward passes and gives you the gradients—you just decide **how to update the weights**.\n\nYou may implement **ANY update rule** you like: vanilla SGD, momentum, RMSprop, Adam, or something creative. Your optimizer will train a simple neural network on MNIST.","constraints":["Use ONLY numpy - no PyTorch, TensorFlow, or autograd libraries","optimizer_step() receives the gradient already computed","Return updated parameter with the SAME shape as input","Use the state dict to store momentum, running averages, etc.","Any update rule is valid - creativity encouraged!"],"id":"8","test_cases":[{"test":"import numpy as np\nnp.random.seed(42)\nparam = np.array([1.0, 2.0, 3.0])\ngrad = np.array([0.1, 0.2, 0.3])\nstate = {}\nnew_param, new_state = optimizer_step(param, grad, state, lr=0.1)\nprint(new_param.shape == param.shape)","expected_output":"True"},{"test":"import numpy as np\nnp.random.seed(42)\nparam = np.array([1.0, 2.0, 3.0])\ngrad = np.array([0.1, 0.2, 0.3])\nstate = {}\nnew_param, new_state = optimizer_step(param, grad, state, lr=0.1)\n# Parameter should change when gradient is non-zero\nchanged = np.sum(np.abs(new_param - param)) > 0.001\nprint(changed)","expected_output":"True"},{"test":"import numpy as np\nnp.random.seed(42)\nparam = np.array([1.0, 2.0, 3.0])\ngrad = np.array([0.0, 0.0, 0.0])  # Zero gradient\nstate = {}\nnew_param, new_state = optimizer_step(param, grad, state, lr=0.1)\n# With zero gradient (and no momentum), param should stay similar\nprint(np.allclose(new_param, param, atol=0.01))","expected_output":"True"},{"test":"import numpy as np\nnp.random.seed(42)\nparam = np.array([[1.0, 2.0], [3.0, 4.0]])\ngrad = np.array([[0.1, 0.2], [0.3, 0.4]])\nstate = {}\nnew_param, new_state = optimizer_step(param, grad, state, lr=0.1)\n# Should work with 2D arrays too\nprint(new_param.shape == (2, 2))","expected_output":"True"}],"approved_user_libraries":["numpy"],"difficulty":"medium","evaluation_metric":"Accuracy","data_info":"MNIST 28x28 grayscale digits flattened to 784-dim vectors, scaled to [0,1]. Trained with a 2-layer neural network (784→128→10).","time_limits":{"test":"180 seconds","dev":"90 seconds"},"schema":"practical_question_v1","min_eval_metric":0.85,"example":{"input":{"param":"numpy array of any shape (e.g., [784, 128] weight matrix)","grad":"numpy array of same shape (gradient of loss w.r.t. param)","state":"dict to store momentum, running averages, step count, etc.","lr":"learning rate (e.g., 0.01)"},"output":{"new_param":"updated parameter array (same shape)","state":"updated state dict"}},"category":"Optimizers","title":"Design Your Own Optimizer (NumPy)","model_specs":"2-layer neural network (784→128→10) with ReLU activation. You implement only the parameter update rule.","memory_limit":"1 GB","dataset":"MNIST","createdAt":"2026-05-13T21:01:44.402000+00:00","time_limits_seconds":{"dev":90,"test":180},"type":"epoch","lower_is_better":false,"gpu":false},{"created_at":"2026-10-31T23:48:28.778000+00:00","type":"general","test_cases":[{"test":"import numpy as np\nimport scipy.sparse as sp\ndef _graph(seed, n, Om, snr, p=30):\n    r = np.random.default_rng(seed)\n    C = len(Om)\n    y = r.integers(0, C, n)\n    P = np.asarray(Om, dtype=float)[y][:, y] / n\n    U = np.triu(r.random((n, n)) < P, 1)\n    A = sp.csr_matrix((U + U.T).astype(np.float32))\n    M = r.standard_normal((C, p))\n    M = M / np.linalg.norm(M, axis=1, keepdims=True)\n    X = (snr * M[y] + r.standard_normal((n, p))).astype(np.float32)\n    tr = np.concatenate([r.choice(np.flatnonzero(y == c), 20, replace=False) for c in range(C)])\n    r.shuffle(tr)\n    return A, X, tr, y[tr].astype(np.int64), y\ndef _acc(pred, y, tr):\n    m = np.ones(len(y), dtype=bool)\n    m[tr] = False\n    return float(np.mean(np.asarray(pred)[m] == y[m]))\n_A, _X, _tr, _yt, _y = _graph(1, 300, [[6, 6, 6], [6, 6, 6], [6, 6, 6]], 4.0)\n_p = np.asarray(predict(_A, _X, _tr, _yt, 3))\nprint(_p.shape == (300,), bool(np.all(_p == np.floor(_p))), bool(_p.min() >= 0 and _p.max() <= 2))","expected_output":"True True True"},{"test":"import numpy as np\nimport scipy.sparse as sp\ndef _graph(seed, n, Om, snr, p=30):\n    r = np.random.default_rng(seed)\n    C = len(Om)\n    y = r.integers(0, C, n)\n    P = np.asarray(Om, dtype=float)[y][:, y] / n\n    U = np.triu(r.random((n, n)) < P, 1)\n    A = sp.csr_matrix((U + U.T).astype(np.float32))\n    M = r.standard_normal((C, p))\n    M = M / np.linalg.norm(M, axis=1, keepdims=True)\n    X = (snr * M[y] + r.standard_normal((n, p))).astype(np.float32)\n    tr = np.concatenate([r.choice(np.flatnonzero(y == c), 20, replace=False) for c in range(C)])\n    r.shuffle(tr)\n    return A, X, tr, y[tr].astype(np.int64), y\ndef _acc(pred, y, tr):\n    m = np.ones(len(y), dtype=bool)\n    m[tr] = False\n    return float(np.mean(np.asarray(pred)[m] == y[m]))\n_A, _X, _tr, _yt, _y = _graph(2, 300, [[6, 6, 6], [6, 6, 6], [6, 6, 6]], 5.0)\nprint(\"strong features, uninformative links:\", _acc(predict(_A, _X, _tr, _yt, 3), _y, _tr) > 0.8)","expected_output":"strong features, uninformative links: True"},{"test":"import numpy as np\nimport scipy.sparse as sp\ndef _graph(seed, n, Om, snr, p=30):\n    r = np.random.default_rng(seed)\n    C = len(Om)\n    y = r.integers(0, C, n)\n    P = np.asarray(Om, dtype=float)[y][:, y] / n\n    U = np.triu(r.random((n, n)) < P, 1)\n    A = sp.csr_matrix((U + U.T).astype(np.float32))\n    M = r.standard_normal((C, p))\n    M = M / np.linalg.norm(M, axis=1, keepdims=True)\n    X = (snr * M[y] + r.standard_normal((n, p))).astype(np.float32)\n    tr = np.concatenate([r.choice(np.flatnonzero(y == c), 20, replace=False) for c in range(C)])\n    r.shuffle(tr)\n    return A, X, tr, y[tr].astype(np.int64), y\ndef _acc(pred, y, tr):\n    m = np.ones(len(y), dtype=bool)\n    m[tr] = False\n    return float(np.mean(np.asarray(pred)[m] == y[m]))\n_A, _X, _tr, _yt, _y = _graph(3, 400, [[24, 2, 2], [2, 24, 2], [2, 2, 24]], 0.0)\nprint(\"noise features, class links to itself:\", _acc(predict(_A, _X, _tr, _yt, 3), _y, _tr) > 0.8)","expected_output":"noise features, class links to itself: True"},{"test":"import numpy as np\nimport scipy.sparse as sp\ndef _graph(seed, n, Om, snr, p=30):\n    r = np.random.default_rng(seed)\n    C = len(Om)\n    y = r.integers(0, C, n)\n    P = np.asarray(Om, dtype=float)[y][:, y] / n\n    U = np.triu(r.random((n, n)) < P, 1)\n    A = sp.csr_matrix((U + U.T).astype(np.float32))\n    M = r.standard_normal((C, p))\n    M = M / np.linalg.norm(M, axis=1, keepdims=True)\n    X = (snr * M[y] + r.standard_normal((n, p))).astype(np.float32)\n    tr = np.concatenate([r.choice(np.flatnonzero(y == c), 20, replace=False) for c in range(C)])\n    r.shuffle(tr)\n    return A, X, tr, y[tr].astype(np.int64), y\ndef _acc(pred, y, tr):\n    m = np.ones(len(y), dtype=bool)\n    m[tr] = False\n    return float(np.mean(np.asarray(pred)[m] == y[m]))\n_A, _X, _tr, _yt, _y = _graph(4, 400, [[2, 30, 2, 2], [30, 2, 2, 2], [2, 2, 2, 30], [2, 2, 30, 2]], 0.0)\nprint(\"noise features, class links to a partner class:\", _acc(predict(_A, _X, _tr, _yt, 4), _y, _tr) > 0.8)","expected_output":"noise features, class links to a partner class: True"}],"lower_is_better":false,"approved_user_libraries":["numpy","scipy","sklearn","torch"],"data_info":"Generated inside the grader: seeded contextual stochastic block models (no dataset download). predict(A, X, train_idx, y_train, n_classes): A is a scipy.sparse.csr_matrix (N, N), float32, binary, symmetric, no self-loops; X is float32 (N, p); train_idx and y_train are int64 arrays with 20 labelled nodes per class. Graphs have roughly 1,600 to 2,700 nodes, 4 to 7 classes, mean degree 4 to 12 and 100 to 800 features. Run: 5 graphs. Submit: 11 other graphs, including families Run never shows. Each graph runs in a fresh Python process with a 30 s budget for predict on CPU.","time_limits":{"test":600,"dev":300},"example":{"input":"predict(A (N, N) csr_matrix, X (N, p), train_idx (20 per class), y_train, n_classes)","output":"labels of shape (N,) with integer class ids; the nearest-class-mean starter scores about 0.36 on Submit"},"gpu":false,"description":"Label propagation assumes that neighbours share a class. A feature-only classifier assumes the graph has nothing to say. Each is right on some graphs and badly wrong on others, and with only **20 labelled nodes per class** you have to work out which situation you are in. The book poses this task: one partially labelled graph, a label for a small fraction of its nodes, and the node features and links to fill in the rest. Your job is to build the node classifier with the highest accuracy across many graphs. Any method is allowed.\n\n## The data\n\nEvery graph comes from a seeded **contextual stochastic block model** generated inside the grader:\n\n- Each node $i$ has a hidden class $y_i$. Edges are drawn independently given the classes, with a probability that depends on the pair of classes $(y_i, y_j)$. The class compatibility pattern is hidden and differs from graph to graph: a class may link mostly to itself or mostly to other classes, and on some graphs the links say nothing about the class at all.\n- Each node has a feature vector drawn from a distribution that depends on its class. On some graphs the features are strong, on others they are close to pure noise.\n- So the signal is split between the edges and the features in a different way on every graph, and nothing tells you the split. Graph size, number of classes, mean degree and feature dimension also differ.\n\nClass ids are arbitrary and are renamed on every graph. Node ids are shuffled afresh on every run, so an id says nothing about a node.\n\n## Your function\n\n```python\ndef predict(A, X, train_idx, y_train, n_classes):\n    ...\n    return labels        # shape (N,), one integer class id per node\n```\n\n- `A`: `scipy.sparse.csr_matrix` of shape `(N, N)`, float32, binary and symmetric, with no self-loops.\n- `X`: float32 numpy array of shape `(N, p)`, the node features.\n- `train_idx`: int64 array with the ids of the labelled nodes: exactly 20 per class, in shuffled order.\n- `y_train`: int64 array of the same length with their class ids in `[0, n_classes - 1]`.\n- `n_classes`: the number of classes $C$.\n\nReturn one class id for each of the $N$ nodes, as an integer array (or a float array holding whole numbers). This is transductive: the features and links of the test nodes are in front of you, only their labels are hidden. Predictions on labelled nodes are not scored.\n\nApproved libraries: numpy, scipy, scikit-learn, torch (CPU), plus small standard-library helpers (math, random, time, collections, itertools, functools, dataclasses, typing, copy, heapq, bisect, statistics, warnings, enum, abc).\n\n## Score (higher is better)\n\nThe score of one graph is its **test accuracy**: the fraction of unlabelled nodes classified correctly. The lab score is the **mean over graphs**, each graph counting equally. **Run** scores 5 graphs. **Submit** scores 11 other graphs: it uses different seeds and adds graph families Run never shows, so the class patterns, the degree distribution and the feature distribution can all differ from what you tune on. You pass at a mean accuracy of **0.70**; above that, higher ranks higher. The report lists your accuracy and seconds per graph.\n\n## Budget and gates\n\n`predict` gets **30 seconds per graph**, measured by the grader, on CPU (numpy and torch default to 4 threads). Each graph runs in a **fresh Python process**: your code is loaded again, sees only that graph's inputs, and nothing carries over from one graph to the next. The grader seeds `random`, `numpy` and, if you imported it, `torch` before each call. The run fails with a score of 0 if:\n\n- `predict` raises, or takes longer than the budget on any graph;\n- the output is not a flat array of length $N$ holding whole-number class ids in `[0, n_classes - 1]`;\n- your code reads data the grader did not hand it. Imports outside the approved list, `dml_data`, file and network access (`open`, `.load`, `np.fromfile`, `torch.load`,...), `getattr`/`setattr`/`globals`/`vars`, and dunder attributes such as `__dict__` or `__class__` are rejected before `predict` is called;\n- your source is longer than 30,000 characters, its string constants add up to more than 3,000 characters, it has more than 600 numeric literals, or an integer literal has more than 18 digits. These caps keep stored labels out of the source.","tags":["graphs","node-classification","semi-supervised","gnn","label-propagation","stochastic-block-model","heterophily","open-ended","leaderboard"],"id":"80ecfc34-f1fb-4216-8dd0-a9c24d764e02","img_type":"full","dataset_id":"synthetic","evaluation_metric":"accuracy","difficulty":"hard","min_eval_metric":0.7,"category":"Machine Learning","title":"Best Node Classifier with 20 Labels per Class","dataset":"Synthetic contextual stochastic block models (generated in the grader)","time_limits_seconds":{"dev":300,"test":600}},{"created_at":"2026-10-27T19:52:35.781000+00:00","type":"general","test_cases":[{"test":"\nimport ctypes as _tc_ct, subprocess as _tc_sp, tempfile as _tc_tf, time as _tc_t, os as _tc_os\nimport numpy as _tc_np\n\ndef _tc_prog(M, N, K, ta=False, tb=False, epi=False):\n    L = [\"# test\", f\"%A = buffer {M * K} : dtype=f32 slot=1\", f\"%B = buffer {K * N} : dtype=f32 slot=2\"]\n    if epi:\n        L.append(f\"%bias = buffer {N} : dtype=f32 slot=3\")\n    L.append(f\"%C = buffer {M * N} : dtype=f32 slot=0\")\n    L.append(f\"%a = reshape %A [{K} {M} 1]\" if ta else f\"%a = permute (reshape %A [{M} {K} 1]) [1 0 2]\")\n    L.append(f\"%b = permute (reshape %B [{N} {K} 1]) [1 2 0]\" if tb else f\"%b = reshape %B [{K} 1 {N}]\")\n    L.append(f\"%p = mul (expand %a [{K} {M} {N}]) (expand %b [{K} {M} {N}])\")\n    L.append(\"%s = reduce %p : op=add pop=1\")\n    if epi:\n        L.append(f\"%y = max (add %s (expand (reshape %bias [1 {N}]) [{M} {N}])) 0.0\")\n        L.append(f\"%result = store (reshape %C [{M} {N}]) %y\")\n    else:\n        L.append(f\"%result = store (reshape %C [{M} {N}]) %s\")\n    return \"\\n\".join(L) + \"\\n\"\n\ndef _tc_bench(src):\n    raise RuntimeError(\"no tuning in the test cases\")\n\ndef _tc_build(src):\n    d = _tc_tf.mkdtemp()\n    open(d + \"/k.c\", \"w\").write(src)\n    p = _tc_sp.run([\"cc\", \"-O2\", \"-march=x86-64-v3\", \"-std=gnu11\", \"-shared\", \"-fPIC\", \"-Wl,-z,defs\",\n                    \"-o\", d + \"/k.so\", d + \"/k.c\", \"-lm\"], capture_output=True, text=True)\n    if p.returncode:\n        print(\"compile error:\", p.stderr[-800:])\n        return None\n    fn = _tc_ct.CDLL(d + \"/k.so\").kernel\n    fn.argtypes = [_tc_ct.POINTER(_tc_ct.c_void_p)]\n    return fn\n\ndef _tc_call(fn, bufs):\n    arr = (_tc_ct.c_void_p * len(bufs))(*[b.ctypes.data for b in bufs])\n    t0 = _tc_t.perf_counter()\n    fn(arr)\n    return _tc_t.perf_counter() - t0\n\n_s = codegen(_tc_prog(8, 8, 8), _tc_bench)\nprint(isinstance(_s, str) and \"kernel\" in _s)\n","expected_output":"True"},{"test":"\nimport ctypes as _tc_ct, subprocess as _tc_sp, tempfile as _tc_tf, time as _tc_t, os as _tc_os\nimport numpy as _tc_np\n\ndef _tc_prog(M, N, K, ta=False, tb=False, epi=False):\n    L = [\"# test\", f\"%A = buffer {M * K} : dtype=f32 slot=1\", f\"%B = buffer {K * N} : dtype=f32 slot=2\"]\n    if epi:\n        L.append(f\"%bias = buffer {N} : dtype=f32 slot=3\")\n    L.append(f\"%C = buffer {M * N} : dtype=f32 slot=0\")\n    L.append(f\"%a = reshape %A [{K} {M} 1]\" if ta else f\"%a = permute (reshape %A [{M} {K} 1]) [1 0 2]\")\n    L.append(f\"%b = permute (reshape %B [{N} {K} 1]) [1 2 0]\" if tb else f\"%b = reshape %B [{K} 1 {N}]\")\n    L.append(f\"%p = mul (expand %a [{K} {M} {N}]) (expand %b [{K} {M} {N}])\")\n    L.append(\"%s = reduce %p : op=add pop=1\")\n    if epi:\n        L.append(f\"%y = max (add %s (expand (reshape %bias [1 {N}]) [{M} {N}])) 0.0\")\n        L.append(f\"%result = store (reshape %C [{M} {N}]) %y\")\n    else:\n        L.append(f\"%result = store (reshape %C [{M} {N}]) %s\")\n    return \"\\n\".join(L) + \"\\n\"\n\ndef _tc_bench(src):\n    raise RuntimeError(\"no tuning in the test cases\")\n\ndef _tc_build(src):\n    d = _tc_tf.mkdtemp()\n    open(d + \"/k.c\", \"w\").write(src)\n    p = _tc_sp.run([\"cc\", \"-O2\", \"-march=x86-64-v3\", \"-std=gnu11\", \"-shared\", \"-fPIC\", \"-Wl,-z,defs\",\n                    \"-o\", d + \"/k.so\", d + \"/k.c\", \"-lm\"], capture_output=True, text=True)\n    if p.returncode:\n        print(\"compile error:\", p.stderr[-800:])\n        return None\n    fn = _tc_ct.CDLL(d + \"/k.so\").kernel\n    fn.argtypes = [_tc_ct.POINTER(_tc_ct.c_void_p)]\n    return fn\n\ndef _tc_call(fn, bufs):\n    arr = (_tc_ct.c_void_p * len(bufs))(*[b.ctypes.data for b in bufs])\n    t0 = _tc_t.perf_counter()\n    fn(arr)\n    return _tc_t.perf_counter() - t0\n\n_M, _N, _K = 37, 29, 23\n_fn = _tc_build(codegen(_tc_prog(_M, _N, _K, ta=True, epi=True), _tc_bench))\n_r = _tc_np.random.default_rng(0)\n_A = _r.uniform(-1, 1, (_K, _M)).astype(_tc_np.float32)\n_B = _r.uniform(-1, 1, (_K, _N)).astype(_tc_np.float32)\n_bias = _r.uniform(-1, 1, _N).astype(_tc_np.float32)\n_C = _tc_np.full((_M, _N), _tc_np.nan, _tc_np.float32)\nif _fn is not None:\n    _tc_call(_fn, [_C, _A, _B, _bias])\n    _ref = _tc_np.maximum(_A.T.astype(float) @ _B.astype(float) + _bias, 0)\n    print(bool(_tc_np.all(_tc_np.abs(_C - _ref) <= 1e-4)))\n","expected_output":"True"},{"test":"\nimport ctypes as _tc_ct, subprocess as _tc_sp, tempfile as _tc_tf, time as _tc_t, os as _tc_os\nimport numpy as _tc_np\n\ndef _tc_prog(M, N, K, ta=False, tb=False, epi=False):\n    L = [\"# test\", f\"%A = buffer {M * K} : dtype=f32 slot=1\", f\"%B = buffer {K * N} : dtype=f32 slot=2\"]\n    if epi:\n        L.append(f\"%bias = buffer {N} : dtype=f32 slot=3\")\n    L.append(f\"%C = buffer {M * N} : dtype=f32 slot=0\")\n    L.append(f\"%a = reshape %A [{K} {M} 1]\" if ta else f\"%a = permute (reshape %A [{M} {K} 1]) [1 0 2]\")\n    L.append(f\"%b = permute (reshape %B [{N} {K} 1]) [1 2 0]\" if tb else f\"%b = reshape %B [{K} 1 {N}]\")\n    L.append(f\"%p = mul (expand %a [{K} {M} {N}]) (expand %b [{K} {M} {N}])\")\n    L.append(\"%s = reduce %p : op=add pop=1\")\n    if epi:\n        L.append(f\"%y = max (add %s (expand (reshape %bias [1 {N}]) [{M} {N}])) 0.0\")\n        L.append(f\"%result = store (reshape %C [{M} {N}]) %y\")\n    else:\n        L.append(f\"%result = store (reshape %C [{M} {N}]) %s\")\n    return \"\\n\".join(L) + \"\\n\"\n\ndef _tc_bench(src):\n    raise RuntimeError(\"no tuning in the test cases\")\n\ndef _tc_build(src):\n    d = _tc_tf.mkdtemp()\n    open(d + \"/k.c\", \"w\").write(src)\n    p = _tc_sp.run([\"cc\", \"-O2\", \"-march=x86-64-v3\", \"-std=gnu11\", \"-shared\", \"-fPIC\", \"-Wl,-z,defs\",\n                    \"-o\", d + \"/k.so\", d + \"/k.c\", \"-lm\"], capture_output=True, text=True)\n    if p.returncode:\n        print(\"compile error:\", p.stderr[-800:])\n        return None\n    fn = _tc_ct.CDLL(d + \"/k.so\").kernel\n    fn.argtypes = [_tc_ct.POINTER(_tc_ct.c_void_p)]\n    return fn\n\ndef _tc_call(fn, bufs):\n    arr = (_tc_ct.c_void_p * len(bufs))(*[b.ctypes.data for b in bufs])\n    t0 = _tc_t.perf_counter()\n    fn(arr)\n    return _tc_t.perf_counter() - t0\n\n_n = 384\n_fn = _tc_build(codegen(_tc_prog(_n, _n, _n), _tc_bench))\n_naive = _tc_build(\"\"\"void kernel(float **b) { float *C = b[0], *A = b[1], *B = b[2];\n  for (int i = 0; i < 384; i++) for (int j = 0; j < 384; j++) { float s = 0.0f;\n    for (int k = 0; k < 384; k++) s += A[i * 384 + k] * B[k * 384 + j]; C[i * 384 + j] = s; } }\n\"\"\")\n_r = _tc_np.random.default_rng(1)\n_A = _r.uniform(-1, 1, (_n, _n)).astype(_tc_np.float32)\n_B = _r.uniform(-1, 1, (_n, _n)).astype(_tc_np.float32)\n_C = _tc_np.zeros((_n, _n), _tc_np.float32)\nif _fn is not None:\n    _t_you = min(_tc_call(_fn, [_C, _A, _B]) for _ in range(5))\n    _t_naive = min(_tc_call(_naive, [_C, _A, _B]) for _ in range(3))\n    print(_t_naive / _t_you >= 3.0)\n","expected_output":"True"}],"lower_is_better":false,"approved_user_libraries":["numpy","math","collections","itertools","functools","random","json"],"data_info":"Synthetic float32 matrices drawn uniformly from [-1, 1] inside the grader, fresh for every timed call. Run: five programs (square, transposed operands, batched, bias + ReLU, odd sizes). Submit: eight held-out programs up to 768 in each dimension.","time_limits":{"test":300,"dev":180},"example":{"input":"codegen(program_text, bench) where program_text is the square_256 .uir program shown in the description","output":"a C string defining void kernel(float **bufs); the grader reports e.g. your 92.1 GFLOP/s vs the reference's 85.3 GFLOP/s on square_256 (speedup 1.08) and a geometric-mean speedup over all programs"},"gpu":false,"description":"Week 6 of the course is where timing starts to matter. Your compiler receives a matrix-multiply program written in the course's `.uir` format and must emit C. The harness compiles your C, checks every result, and times it against a reference kernel compiled in the same machine with the same flags. The leaderboard ranks by **geometric-mean speedup over the reference, higher is better**.\n\n**Contract.** Define `codegen(program, bench) -> str`.\n\n- `program` is the text of one `.uir` program (format: the course spec; the starter code already includes a parser you may keep or replace).\n- Return C source that defines `void kernel(float **bufs)`. `bufs[s]` points to the buffer declared with `slot=s`: `C` is slot 0, `A` slot 1, `B` slot 2 and `bias` slot 3 when present. Buffers are contiguous `float32` arrays of the declared length. `C` holds garbage when `kernel` is called, so every element must be written.\n- Each program computes `C = A·B` for every batch, optionally followed by `C = max(C + bias, 0)`. Here is the Run program `square_256`:\n\n```\n# square_256\n%A = buffer 65536 : dtype=f32 slot=1\n%B = buffer 65536 : dtype=f32 slot=2\n%C = buffer 65536 : dtype=f32 slot=0\n%a = permute (reshape %A [256 256 1]) [1 0 2]\n%b = reshape %B [256 1 256]\n%p = mul (expand %a [256 256 256]) (expand %b [256 256 256])\n%s = reduce %p : op=add pop=1\n%result = store (reshape %C [256 256]) %s\n```\n\n- Programs always have this shape: buffer declarations, then `%a` and `%b` (views of `A` and `B` put into `[K, (batch), M, 1]` and `[K, (batch), 1, N]` with `reshape` and `permute`, which is how a transposed operand shows up), then `%p = mul (expand ...) (expand ...)`, `%s = reduce %p : op=add pop=1`, an optional `%y = max (add %s (expand (reshape %bias ...) ...)) 0.0`, and `%result = store (reshape %C ...) ...`.\n- `bench(c_source) -> float` compiles a candidate source with the same flags and gates, runs it on the current program's shapes with fresh random inputs, checks the output, and returns the median time of 3 calls in seconds. It raises `ValueError` when the source is rejected, does not compile, crashes or computes a wrong result, and `RuntimeError` once the tuning budget is used up. In the test cases `bench` always raises `RuntimeError`.\n\n**Compilation.** `cc -O2 -march=x86-64-v3 -std=gnu11 -shared -fPIC -Wl,-z,defs <your.c> -lm` with GCC 12, single-threaded. `x86-64-v3` means AVX2 and FMA; AVX-512 is not available. The flags are fixed.\n\n**Score.**\n\n- For each program, your kernel and the reference run alternately on fresh random inputs (uniform in [-1, 1]) for 5 to 61 rounds. Every one of your outputs is checked: `|C - C_exact| <= 2e-5 * (|A|·|B|) + 1e-6` element by element (plus `|bias|` when there is a bias).\n- A program's speedup is the reference's median time divided by yours. The score is the geometric mean over programs.\n- The reference is a hand-written AVX2 kernel; on large square shapes it reaches about 60-80% of the machine's measured AVX2 FMA peak, which the report prints next to your percentage for every program.\n- A score of at least **0.25** counts as solved; everything above that is leaderboard.\n- **Run:** 256 x 256 x 256; 199 x 173 x 161 (A transposed); 192 x 320 x 256 (B transposed); 96 x 128 x 160 (batch 4); 256 x 384 x 192 (bias + ReLU). **Submit:** eight held-out programs up to 768 in each dimension, including batched, transposed, odd-sized, bias + ReLU and very short-and-wide ones.\n\n**Budgets.** Python time inside `codegen` outside `bench` calls: 20 s on Run, 30 s on Submit. Total `bench` time: 30 s on Run, 60 s on Submit. A single `kernel` call may take at most 5 s. Your Python may import only `numpy`, `math`, `re`, `collections`, `itertools`, `functools`, `heapq`, `bisect`, `random`, `typing`, `dataclasses`, `string`, `textwrap` and `json`.\n\n**Gates.** The score is set to 0 and the run fails if any of these happen:\n- `codegen` raises, does not return a string, or runs over its budget.\n- The C source is rejected, fails to compile or link, crashes, hangs, takes more than 5 s for one call, or computes a wrong result on any call.\n- C rules: includes only `immintrin.h`, `stdint.h`, `stddef.h`, `string.h`, `stdlib.h`, `math.h`, `stdbool.h`, `float.h`, `limits.h`; pragmas only `#pragma GCC unroll`, `#pragma GCC ivdep` and `#pragma once`; no `##` token pasting; no inline assembly; no threads, processes, system calls, files, printing, environment access or `exit`; no `__attribute__` of kind `constructor`, `destructor`, `target`, `target_clones`, `optimize`, `section`, `alias`, `ifunc` or `visibility`. Linking against anything but libc and libm fails.\n- Python rules: no file access, introspection (`globals`, `getattr`/`setattr`, frames, `eval`/`exec`), aliases of or changes to imported modules, or redefining built-in names at module level.","tags":["compilers","codegen","gemm","simd","avx2","performance","tinygrad","open-ended","leaderboard"],"id":"83139444-71ac-4336-b380-eb36f8427753","dataset_id":"synthetic","img_type":"full","difficulty":"hard","evaluation_metric":"speedup","min_eval_metric":0.25,"category":"Compilers","dataset":"Synthetic GEMM-family .uir programs with random float32 inputs","title":"Fastest CPU GEMM","time_limits_seconds":{"dev":180,"test":300}},{"created_at":"2026-11-05T02:55:54.225000+00:00","type":"general","constraints":["train gets about 25 s, scaled to the machine's measured GPU speed; predict gets 15 s; a call more than 15% late scores 0","predict returns one (boxes (k, 4) as x1, y1, x2, y2 in pixels, scores (k,), labels (k,) in 0-4) per image; up to 100 per image are scored","score: COCO-style box mAP@[.50:.95] over all scored scenes, including scene kinds Run never shows","numpy, torch, scipy and scikit-learn on a Tesla T4; the harness owns all data access","at most 12000 characters of code, 500 numbers, 600 characters of strings, 200 defined names","attribute assignment only on self inside a method of a class"],"test_cases":[{"test":"import numpy as np\n_r = np.random.default_rng(0)\ndef _make(n):\n    X = _r.integers(0, 40, (n, 64, 64, 3)).astype(np.uint8)\n    T = []\n    yy, xx = np.mgrid[0:64, 0:64] + 0.5\n    for i in range(n):\n        s = _r.uniform(12, 24)\n        cx, cy = _r.uniform(s / 2 + 1, 63 - s / 2, 2)\n        c = int(_r.integers(0, 2))\n        if c == 1:\n            m = (np.abs(xx - cx) <= s / 2) & (np.abs(yy - cy) <= s / 2)\n        else:\n            m = (xx - cx) ** 2 + (yy - cy) ** 2 <= (s / 2) ** 2\n        X[i][m] = _r.integers(150, 256, 3)\n        T.append((np.array([[cx - s / 2, cy - s / 2, cx + s / 2, cy + s / 2]], np.float32), np.array([c], np.int64)))\n    return X, T\n_Xa, _Ta = _make(600)\n_Xb, _Tb = _make(100)\n_m = train(_Xa, _Ta, 20.0)\n_P = predict(_m, _Xb)\ndef _np(a):\n    return a.detach().cpu().numpy() if hasattr(a, 'detach') else np.asarray(a)\nprint(len(_P))","expected_output":"100"},{"test":"import numpy as np\n_r = np.random.default_rng(0)\ndef _make(n):\n    X = _r.integers(0, 40, (n, 64, 64, 3)).astype(np.uint8)\n    T = []\n    yy, xx = np.mgrid[0:64, 0:64] + 0.5\n    for i in range(n):\n        s = _r.uniform(12, 24)\n        cx, cy = _r.uniform(s / 2 + 1, 63 - s / 2, 2)\n        c = int(_r.integers(0, 2))\n        if c == 1:\n            m = (np.abs(xx - cx) <= s / 2) & (np.abs(yy - cy) <= s / 2)\n        else:\n            m = (xx - cx) ** 2 + (yy - cy) ** 2 <= (s / 2) ** 2\n        X[i][m] = _r.integers(150, 256, 3)\n        T.append((np.array([[cx - s / 2, cy - s / 2, cx + s / 2, cy + s / 2]], np.float32), np.array([c], np.int64)))\n    return X, T\n_Xa, _Ta = _make(600)\n_Xb, _Tb = _make(100)\n_m = train(_Xa, _Ta, 20.0)\n_P = predict(_m, _Xb)\ndef _np(a):\n    return a.detach().cpu().numpy() if hasattr(a, 'detach') else np.asarray(a)\nprint(all(_np(e[0]).reshape(-1, 4).shape[0] == len(_np(e[1]).reshape(-1)) == len(_np(e[2]).reshape(-1)) for e in _P))","expected_output":"True"},{"test":"import numpy as np\n_r = np.random.default_rng(0)\ndef _make(n):\n    X = _r.integers(0, 40, (n, 64, 64, 3)).astype(np.uint8)\n    T = []\n    yy, xx = np.mgrid[0:64, 0:64] + 0.5\n    for i in range(n):\n        s = _r.uniform(12, 24)\n        cx, cy = _r.uniform(s / 2 + 1, 63 - s / 2, 2)\n        c = int(_r.integers(0, 2))\n        if c == 1:\n            m = (np.abs(xx - cx) <= s / 2) & (np.abs(yy - cy) <= s / 2)\n        else:\n            m = (xx - cx) ** 2 + (yy - cy) ** 2 <= (s / 2) ** 2\n        X[i][m] = _r.integers(150, 256, 3)\n        T.append((np.array([[cx - s / 2, cy - s / 2, cx + s / 2, cy + s / 2]], np.float32), np.array([c], np.int64)))\n    return X, T\n_Xa, _Ta = _make(600)\n_Xb, _Tb = _make(100)\n_m = train(_Xa, _Ta, 20.0)\n_P = predict(_m, _Xb)\ndef _np(a):\n    return a.detach().cpu().numpy() if hasattr(a, 'detach') else np.asarray(a)\ndef _hit(i):\n    b, s, l = (_np(a) for a in _P[i])\n    if len(s) == 0:\n        return False\n    j = int(np.argmax(s))\n    g = _Tb[i][0][0]\n    bb = np.asarray(b, float).reshape(-1, 4)[j]\n    iw = max(0.0, min(bb[2], g[2]) - max(bb[0], g[0]))\n    ih = max(0.0, min(bb[3], g[3]) - max(bb[1], g[1]))\n    inter = iw * ih\n    u = (bb[2] - bb[0]) * (bb[3] - bb[1]) + (g[2] - g[0]) * (g[3] - g[1]) - inter\n    return inter / u >= 0.5 and int(np.asarray(l).reshape(-1)[j]) == int(_Tb[i][1][0])\nprint(sum(_hit(i) for i in range(100)) >= 80)","expected_output":"True"}],"lower_is_better":false,"approved_user_libraries":["numpy","torch","scipy","sklearn"],"data_info":"Synthetic scenes drawn by the grader from seeds that only the grader holds; there is no dataset file. Each scene is a 64x64 RGB uint8 image with objects of five classes (0 ellipse, 1 rectangle, 2 triangle, 3 ring, 4 cross), rotated, coloured and sometimes striped, on smooth backgrounds with line and dot clutter, blur and noise.\n\ntrain receives 5,000 scenes as uint8 (n, 64, 64, 3) plus a list of (boxes float32 (k, 4) as x1, y1, x2, y2 in pixels, labels int64 (k,)). predict receives the scored scenes as uint8 (m, 64, 64, 3) in random order, without boxes.\n\nRun scores 1,200 scenes (600 like training, 300 noisy and blurred, 300 crowded). Submit uses different seeds and scores 2,000 scenes: 800 like training plus 300 each of four kinds Run never shows (objects outside the training size range, busy textured backgrounds, low colour contrast, extra clutter with hollow outlines).","time_limits":{"test":180,"dev":180},"gpu":true,"description":"## Best Object Detector on Synthetic Scenes\n\nYou get 5,000 small synthetic scenes with every object boxed and labelled, one GPU and about 25 seconds. Train whatever detector you like, then find the objects in scenes you have never seen, some of them unlike anything you trained on. The highest COCO-style mAP wins.\n\nAny method is allowed: a neural network, a classical pipeline, or both. What counts is the mAP you reach and whether you finish on time.\n\n### The scenes\n\nEach scene is a 64 x 64 RGB image with a few objects from five classes:\n\n- `0` ellipse (including circles), `1` rectangle (including squares), `2` triangle, `3` ring, `4` cross.\n\nAn object can have any rotation and any colour, a flat or striped fill, and a size from about 9 to 30 pixels (the longer side of its box). Objects may overlap a little, and one can hide part of another. Backgrounds are smooth colour gradients. Thin lines and small dots are clutter, not objects. Every scene has some blur and noise.\n\nA box is the tight, axis-aligned box around the whole shape, including any part another object hides, given as `(x1, y1, x2, y2)` in pixels. `x` runs left to right and `y` top to bottom, and pixel column `j` covers `x` from `j` to `j + 1`, so a box can have fractional coordinates.\n\n### What you write\n\n```python\ndef train(images, targets, budget_seconds):\n    ...\n    return model                        # anything you like\n\ndef predict(model, images):\n    ...\n    return detections                   # one (boxes, scores, labels) per image\n```\n\n- `images`: `uint8` array of shape `(n, 64, 64, 3)`, channels last.\n- `targets`: a list of `n` pairs `(boxes, labels)`: `boxes` is a `float32` array of shape `(k, 4)`, `labels` an `int64` array of shape `(k,)` with class ids 0 to 4.\n- `budget_seconds`: a float, how long `train` may run on this machine (see below).\n- `predict` returns a list with one entry per image, in the order given. Each entry is `(boxes, scores, labels)`: `boxes` of shape `(k, 4)` with `x2 >= x1` and `y2 >= y1`, `scores` of shape `(k,)` (higher means more confident), and `labels` of shape `(k,)` with whole numbers 0 to 4. numpy arrays or torch tensors both work, and `k` may differ between images, including 0.\n- Up to 100 detections per image are scored, the 100 with the highest scores.\n\n### How it is graded\n\nYour score is the **COCO-style box mAP@[.50:.95]**, the main number the COCO benchmark reports. For each class and each IoU threshold 0.50, 0.55, ..., 0.95, all detections of that class over all scored scenes are sorted by score, and each one is matched to the best still-unmatched true box of its class whose IoU reaches the threshold. A match counts as a true positive and anything else as a false positive. The average precision (AP) is the area under the precision-recall curve, sampled at 101 recall levels, and the score averages it over the 5 classes and the 10 thresholds. It is the same number `pycocotools` reports as bbox AP with 100 detections per image, and we checked the grader against it. **Higher is better**, and the lab is passed at **0.15 or above**. The report also gives AP at IoU 0.50 and 0.75, the mAP of each kind of scene, and the AP of each class. None of these affect passing.\n\n- **Run**: train on 5,000 scenes, then score 1,200 new ones: 600 like the training scenes, 300 noisier and blurrier, and 300 crowded with 7 to 11 smaller objects.\n- **Submit**: a different 5,000 training scenes and 2,000 scored scenes, from seeds Run never uses. 800 are like the training scenes. The other 1,200 come in four kinds that neither the training scenes nor Run show you, 300 of each: objects smaller and larger than any in training, busy striped or checkered backgrounds, objects whose colour is close to their background, and extra clutter, including hollow square outlines, which are not objects. All 2,000 are pooled into one mAP.\n\nThe scored scenes reach `predict` in a random order, with nothing that says which kind a scene is. Your process never sees their true boxes.\n\n**The score moves a little between runs.** Training on a GPU is not exactly repeatable, and the machine's speed changes how much training a budget buys. In calibration, three Submits of the same code moved the reference solution's score by about 0.002 and a small grid detector's by about 0.01. A detector whose training is unstable can move far more: one anchor-based detector ranged from 0.40 to 0.48. Compare ideas over more than one run.\n\n### The budget\n\n- `train` gets about **25 seconds**. `predict` gets 15 seconds for all the scored scenes together.\n- Before your file loads, the grader times a fixed training workload on the GPU it was given and scales `budget_seconds` to match, so a slower machine gets more seconds and a faster one fewer. Read `budget_seconds`, do not hard-code it. Your program should buy about the same amount of training on any machine. The prediction budget is fixed.\n- The clock is the grader's. It runs from the moment `train` is called until it returns, and GPU work that `train` started but did not wait for still counts. Importing libraries and loading your file are free, but a file that takes over 20 s to load is stopped. Turning what `predict` returns into arrays counts as prediction time.\n- Stay inside your budgets. Machines still differ a little after scaling, so the grader only stops a call at 15% past its budget. A stopped call scores 0 for the whole run.\n- You get a Tesla T4 GPU and PyTorch. If a run does not get a GPU, or the GPU is far from the expected speed, the grader says it did **not score** the run. That is a platform problem, not your code, so run it again.\n\n### Rules\n\n- Libraries: numpy, torch, scipy and scikit-learn, plus small standard-library helpers (math, random, time, collections, itertools, copy, heapq, bisect, statistics, warnings, typing, enum, abc). torchvision is not available here.\n- The harness owns the data: reading or writing files, dataset loaders, network access, `dml_data`, serialization (`torch.save`, `torch.load`, `np.load`, `pickle`) and pretrained weights are all refused. Weights have to come from your `train`.\n- Write classes the ordinary way: `self.fc = nn.Linear(...)` inside a method is fine, and so are `torch.backends.cudnn.benchmark` and `.deterministic`. Outside a method, assigning to any other attribute is refused, so use `p.requires_grad_(False)` rather than `p.requires_grad = False`, and keep other state in local variables, lists or dicts.\n- Dynamic access is refused (`getattr`, `setattr`, `vars`, `globals`, `exec`, names starting with two underscores other than the usual methods such as `__init__`, and private attributes such as `torch._foreach_add_`), and so are `os`, `sys`, `multiprocessing` and text or byte converters (`ord`, `chr`, `tobytes`, `format`).\n- A file can carry at most 12,000 characters of code (comments and docstrings do not count), 500 numbers of at most 8 characters each, 600 characters of strings, 200 names you define, each up to 24 characters, and 32 items in any one list, tuple, set or dict you write out. That leaves ordinary code plenty of room and no room for weights trained somewhere else.\n\nA refused file, an exception, a malformed result or a missed budget sets the score to 0 and fails the run.\n","tags":["object-detection","map","iou","centernet","anchors","nms","data-augmentation","distribution-shift","time-budget","competitive","computer-vision"],"id":"835fcd76-d6b2-4d5b-8dad-bc8bc053c1ae","img_type":"full","dataset_id":"synthetic","evaluation_metric":"map","difficulty":"hard","min_eval_metric":0.15,"category":"Computer Vision","title":"Best Object Detector on Synthetic Scenes","dataset":"Synthetic shape scenes generated by the grader","time_limits_seconds":{"dev":180,"test":180}},{"created_at":"2026-10-27T19:36:55.482000+00:00","type":"general","test_cases":[{"test":"def _dml_uop_lib():\n    \"\"\"The UOp class plus the exact evaluator the grader uses (hash-consed, immutable UOp(op, src, arg)).\"\"\"\n    import math\n    import struct\n\n    import numpy as np\n\n    I32_MIN, I32_MAX = -(2 ** 31), 2 ** 31 - 1\n    FULL = (I32_MIN, I32_MAX)\n    DTYPES = (\"bool\", \"i32\", \"f32\")\n    ALU = (\"CAST\", \"RECIP\", \"TRUNC\", \"ADD\", \"MUL\", \"MAX\", \"XOR\", \"CMPLT\", \"SHL\", \"DIV\", \"MOD\", \"WHERE\")\n    OPS = frozenset((\"CONST\", \"PARAM\", \"CALL\", \"STACK\", \"INDEX\", \"SHRINK\") + ALU)\n    MAX_NODES = 20000\n    MAX_CALL_DEPTH = 64\n\n    # ------------------------------------------------------------------ exact value semantics\n    def f32_bits(v):\n        return struct.unpack(\"<I\", struct.pack(\"<f\", v))[0]\n\n    def norm_dtype(d):\n        for c in DTYPES:\n            if type(d) is str and d == c:\n                return c\n        raise ValueError(f\"unknown dtype {d!r} (use 'bool', 'i32' or 'f32')\")\n\n    def norm_const(v):\n        if isinstance(v, (bool, np.bool_)):\n            return bool(v)\n        if isinstance(v, (int, np.integer)):\n            v = int(v)\n            if not I32_MIN <= v <= I32_MAX:\n                raise ValueError(f\"i32 CONST {v} is out of range\")\n            return v\n        if isinstance(v, (float, np.floating)):\n            v = float(v)\n            if not math.isnan(v):\n                with np.errstate(over=\"ignore\"):\n                    if float(np.float32(v)) != v:\n                        raise ValueError(f\"f32 CONST {v!r} is not exactly representable as float32\")\n            return v\n        raise ValueError(f\"CONST arg must be a bool, int or float, not {type(v).__name__}\")\n\n    def const_dtype(v):\n        return \"bool\" if type(v) is bool else \"i32\" if type(v) is int else \"f32\"\n\n    def norm_arg(op, arg):\n        \"\"\"Returns (normalized arg, hashable key).\"\"\"\n        if op == \"CONST\":\n            v = norm_const(arg)\n            return v, (const_dtype(v), f32_bits(v) if type(v) is float else v)\n        if op == \"PARAM\":\n            if not isinstance(arg, tuple) or len(arg) not in (2, 4):\n                raise ValueError(\"PARAM arg must be (slot, dtype) or (slot, dtype, lo, hi)\")\n            slot, dt = arg[0], norm_dtype(arg[1])\n            lo, hi = (arg[2], arg[3]) if len(arg) == 4 else (None, None)\n            if type(slot) is not int or not 0 <= slot < 64:\n                raise ValueError(\"PARAM slot must be an int in 0..63\")\n            if dt == \"i32\":\n                if (lo is None) != (hi is None):\n                    raise ValueError(\"PARAM bounds must give both lo and hi, or neither\")\n                if lo is not None:\n                    if type(lo) is not int or type(hi) is not int or not I32_MIN <= lo <= hi <= I32_MAX:\n                        raise ValueError(\"PARAM bounds must be ints with lo <= hi inside the i32 range\")\n            elif lo is not None or hi is not None:\n                raise ValueError(\"only i32 PARAMs take bounds\")\n            a = (slot, dt, lo, hi)\n            return a, a\n        if op == \"CAST\":\n            d = norm_dtype(arg)\n            return d, d\n        if op == \"SHRINK\":\n            if type(arg) is not int or arg < 1:\n                raise ValueError(\"SHRINK arg is the window size, an int >= 1\")\n            return arg, arg\n        if arg is not None:\n            raise ValueError(f\"{op} takes no arg\")\n        return None, None\n\n    def infer(op, arg, srcs):\n        \"\"\"srcs: list of (dtype, shape). Returns (dtype, shape) or raises ValueError.\"\"\"\n        n = len(srcs)\n        if op in (\"CONST\", \"PARAM\"):\n            if n:\n                raise ValueError(f\"{op} has no srcs\")\n            return (const_dtype(arg) if op == \"CONST\" else arg[1]), ()\n        if op == \"STACK\":\n            if n < 1:\n                raise ValueError(\"STACK needs at least one src\")\n            if any(s[1] != () for s in srcs) or len({s[0] for s in srcs}) != 1:\n                raise ValueError(\"STACK srcs must be scalars of one dtype\")\n            return srcs[0][0], (n,)\n        if op == \"INDEX\":\n            if n != 2 or len(srcs[0][1]) != 1 or srcs[1] != (\"i32\", ()):\n                raise ValueError(\"INDEX takes a rank-1 value and one i32 scalar index\")\n            return srcs[0][0], ()\n        if op == \"SHRINK\":\n            if n != 2 or len(srcs[0][1]) != 1 or srcs[1] != (\"i32\", ()):\n                raise ValueError(\"SHRINK takes a rank-1 value and an i32 scalar offset\")\n            if arg > srcs[0][1][0]:\n                raise ValueError(\"SHRINK window is larger than its input\")\n            return srcs[0][0], (arg,)\n        if op == \"CALL\":\n            raise ValueError(\"internal: CALL handled separately\")\n        if any(s[1] != () for s in srcs):\n            raise ValueError(f\"{op} operands must be scalars\")\n        dts = [s[0] for s in srcs]\n        if op == \"CAST\":\n            if n != 1:\n                raise ValueError(\"CAST takes one src\")\n            return arg, ()\n        if op in (\"RECIP\", \"TRUNC\"):\n            if n != 1 or dts[0] != \"f32\":\n                raise ValueError(f\"{op} takes one f32 src\")\n            return \"f32\", ()\n        if op == \"WHERE\":\n            if n != 3 or dts[0] != \"bool\" or dts[1] != dts[2]:\n                raise ValueError(\"WHERE takes (bool, x, y) with x and y of the same dtype\")\n            return dts[1], ()\n        if n != 2 or dts[0] != dts[1]:\n            raise ValueError(f\"{op} takes two srcs of the same dtype\")\n        d = dts[0]\n        if op in (\"ADD\", \"MUL\") and d == \"bool\":\n            raise ValueError(f\"{op} is not defined on bool\")\n        if op in (\"SHL\", \"DIV\", \"MOD\") and d != \"i32\":\n            raise ValueError(f\"{op} is i32 only\")\n        if op == \"XOR\" and d == \"f32\":\n            raise ValueError(\"XOR is not defined on f32\")\n        if op == \"CMPLT\":\n            return \"bool\", ()\n        return d, ()\n\n    def call_check(body_dt, body_shape, body_free, arg_infos):\n        if body_shape != ():\n            raise ValueError(\"a CALL body must be a scalar\")\n        slots = {}\n        for (slot, dt, lo, hi) in body_free:\n            if slot in slots:\n                raise ValueError(f\"a CALL body has two different PARAMs with slot {slot}\")\n            slots[slot] = dt\n        for slot, dt in slots.items():\n            if slot >= len(arg_infos):\n                raise ValueError(f\"CALL passes {len(arg_infos)} args but its body uses PARAM slot {slot}\")\n            if arg_infos[slot] != (dt, ()):\n                raise ValueError(f\"CALL arg {slot} must be a scalar {dt}\")\n        return body_dt, ()\n\n    # ------------------------------------------------------------------ interval bounds (sound, conservative)\n    def clampb(lo, hi):\n        return (lo, hi) if I32_MIN <= lo and hi <= I32_MAX else FULL\n\n    def fdiv(a, b):\n        return a // b\n\n    def bounds_of(op, arg, dtype, srcb, srcd):\n        if dtype == \"f32\":\n            return None\n        if op == \"CONST\":\n            return (int(arg), int(arg))\n        if op == \"PARAM\":\n            if dtype == \"bool\":\n                return (0, 1)\n            return (arg[2], arg[3]) if arg[2] is not None else FULL\n        if op in (\"STACK\",):\n            return (min(b[0] for b in srcb), max(b[1] for b in srcb))\n        if op in (\"INDEX\", \"SHRINK\"):\n            return srcb[0]\n        if op == \"CALL\":\n            return srcb[0]\n        if op == \"CAST\":\n            sd = srcd[0]\n            if dtype == \"i32\":\n                return srcb[0] if sd in (\"bool\", \"i32\") else FULL\n            if dtype == \"bool\":\n                if sd == \"f32\":\n                    return (0, 1)\n                lo, hi = srcb[0]\n                if lo == 0 and hi == 0:\n                    return (0, 0)\n                if lo > 0 or hi < 0:\n                    return (1, 1)\n                return (0, 1)\n        if op == \"WHERE\":\n            c, a, b = srcb\n            if c == (1, 1):\n                return a\n            if c == (0, 0):\n                return b\n            return (min(a[0], b[0]), max(a[1], b[1]))\n        if op == \"CMPLT\":\n            if srcd[0] == \"f32\":\n                return (0, 1)\n            (alo, ahi), (blo, bhi) = srcb\n            if ahi < blo:\n                return (1, 1)\n            if alo >= bhi:\n                return (0, 0)\n            return (0, 1)\n        (alo, ahi), (blo, bhi) = srcb[0], srcb[1]\n        if dtype == \"bool\":\n            if op == \"MAX\":\n                return (max(alo, blo), max(ahi, bhi))\n            if op == \"XOR\":\n                if alo == ahi and blo == bhi:\n                    return (alo ^ blo, alo ^ blo)\n                return (0, 1)\n            return (0, 1)\n        if op == \"ADD\":\n            return clampb(alo + blo, ahi + bhi)\n        if op == \"MUL\":\n            c = (alo * blo, alo * bhi, ahi * blo, ahi * bhi)\n            return clampb(min(c), max(c))\n        if op == \"MAX\":\n            return (max(alo, blo), max(ahi, bhi))\n        if op == \"XOR\":\n            if alo >= 0 and blo >= 0:\n                return (0, (1 << max(ahi, bhi).bit_length()) - 1)\n            return FULL\n        if op == \"SHL\":\n            if blo < 0 or bhi > 31:\n                return FULL\n            c = (alo << blo, alo << bhi, ahi << blo, ahi << bhi)\n            return clampb(min(c), max(c))\n        if op == \"DIV\":\n            if blo <= 0 <= bhi:\n                return FULL\n            if alo == I32_MIN and blo <= -1 <= bhi:\n                return FULL\n            c = (fdiv(alo, blo), fdiv(alo, bhi), fdiv(ahi, blo), fdiv(ahi, bhi))\n            return clampb(min(c), max(c))\n        if op == \"MOD\":\n            if blo > 0:\n                if alo >= 0 and ahi < blo:\n                    return (alo, ahi)\n                if blo == bhi and alo // blo == ahi // blo:\n                    return (alo % blo, ahi % blo)\n                return (0, bhi - 1)\n            if bhi < 0:\n                return (blo + 1, 0)\n            return FULL\n        return FULL\n\n    # ------------------------------------------------------------------ the public UOp class\n    _cache = {}\n\n    class UOp:\n        \"\"\"Hash-consed, immutable UOp(op, src, arg). See the lab description for the API.\"\"\"\n        __slots__ = (\"op\", \"src\", \"arg\", \"dtype\", \"shape\", \"_bounds\", \"_free\")\n\n        def __new__(cls, op, src=(), arg=None):\n            if not isinstance(op, str):\n                raise TypeError(\"op must be a string such as 'ADD'\")\n            op = op.upper()\n            if op not in OPS:\n                raise ValueError(f\"unknown op {op!r}\")\n            src = tuple(src)\n            for s in src:\n                if type(s) is not UOp:\n                    raise TypeError(f\"every src must be a UOp, got {type(s).__name__}\")\n            arg, akey = norm_arg(op, arg)\n            key = (op, tuple(id(s) for s in src), akey)\n            hit = _cache.get(key)\n            if hit is not None:\n                return hit\n            infos = [(s.dtype, s.shape) for s in src]\n            if op == \"CALL\":\n                if len(src) < 1:\n                    raise ValueError(\"CALL needs a body\")\n                b = src[0]\n                dtype, shape = call_check(b.dtype, b.shape, b._free, infos[1:])\n                free = frozenset().union(*[s._free for s in src[1:]]) if len(src) > 1 else frozenset()\n            else:\n                dtype, shape = infer(op, arg, infos)\n                if op == \"PARAM\":\n                    free = frozenset((arg,))\n                else:\n                    free = frozenset().union(*[s._free for s in src]) if src else frozenset()\n            bnd = bounds_of(op, arg, dtype, [s._bounds for s in src], [s.dtype for s in src])\n            self = object.__new__(cls)\n            for k, v in ((\"op\", op), (\"src\", src), (\"arg\", arg), (\"dtype\", dtype), (\"shape\", shape),\n                         (\"_bounds\", bnd), (\"_free\", free)):\n                object.__setattr__(self, k, v)\n            _cache[key] = self\n            return self\n\n        def __setattr__(self, k, v):\n            raise AttributeError(\"UOps are immutable; build a new one\")\n\n        def __delattr__(self, k):\n            raise AttributeError(\"UOps are immutable\")\n\n        @property\n        def bounds(self):\n            return self._bounds\n\n        @property\n        def params(self):\n            \"\"\"The PARAM args (slot, dtype, lo, hi) this value depends on, not looking inside CALL bodies.\"\"\"\n            return self._free\n\n        @staticmethod\n        def const(value, dtype=None):\n            if dtype is not None:\n                dtype = norm_dtype(dtype)\n                value = bool(value) if dtype == \"bool\" else int(value) if dtype == \"i32\" else \\\n                    float(np.float32(value))\n            return UOp(\"CONST\", (), value)\n\n        @staticmethod\n        def param(slot, dtype, lo=None, hi=None):\n            return UOp(\"PARAM\", (), (slot, dtype, lo, hi))\n\n        def toposort(self):\n            out, seen, stack = [], set(), [(self, False)]\n            while stack:\n                n, done = stack.pop()\n                if done:\n                    out.append(n)\n                    continue\n                if id(n) in seen:\n                    continue\n                seen.add(id(n))\n                stack.append((n, True))\n                for s in reversed(n.src):\n                    if id(s) not in seen:\n                        stack.append((s, False))\n            return out\n\n        def size(self):\n            return len(self.toposort())\n\n        def evaluate(self, inputs=None):\n            nodes, root = ingest(self)\n            info = check(nodes)\n            env = {}\n            for (slot, dt, lo, hi) in info[root][2]:\n                if inputs is None or slot not in inputs:\n                    raise ValueError(f\"evaluate needs inputs[{slot}] for PARAM slot {slot}\")\n                env[slot] = to_array(dt, [inputs[slot]])\n            v = evaluate(nodes, info, root, env, 1)\n            if v.ndim == 2:\n                return [py_value(info[root][0], x[0]) for x in v]\n            return py_value(info[root][0], v[0])\n\n        def render(self):\n            names, lines = {}, []\n            for n in self.toposort():\n                name = f\"%{len(names)}\"\n                names[id(n)] = name\n                a = [names[id(s)] for s in n.src]\n                if n.op == \"CONST\":\n                    v = n.arg\n                    txt = (\"true\" if v else \"false\") if type(v) is bool else repr(v)\n                    lines.append(f\"{name} = const {txt} : dtype={n.dtype}\")\n                elif n.op == \"PARAM\":\n                    slot, dt, lo, hi = n.arg\n                    extra = f\" min={lo} max={hi}\" if lo is not None else \"\"\n                    lines.append(f\"{name} = param [] : dtype={dt} slot={slot}{extra}\")\n                elif n.op == \"CAST\":\n                    lines.append(f\"{name} = cast {a[0]} : dtype={n.arg}\")\n                elif n.op == \"SHRINK\":\n                    lines.append(f\"{name} = shrink {a[0]} {a[1]} {n.arg}\")\n                else:\n                    lines.append(f\"{name} = {n.op.lower()} \" + \" \".join(a))\n            return \"\\n\".join(lines)\n\n        def __repr__(self):\n            if self.op == \"CONST\":\n                return f\"UOp.const({self.arg!r})\"\n            if self.op == \"PARAM\":\n                return f\"UOp.param{self.arg!r}\"\n            return f\"UOp({self.op!r}, <{len(self.src)} srcs>, {self.arg!r}) : {self.dtype}{list(self.shape) or ''}\"\n\n    _OP, _SRC, _ARG = UOp.__dict__[\"op\"], UOp.__dict__[\"src\"], UOp.__dict__[\"arg\"]\n\n    # ------------------------------------------------------------------ grading: ingest, check, evaluate\n    class Invalid(Exception):\n        pass\n\n    def ingest(root):\n        \"\"\"Walk a graph of UOp objects reading raw slots, re-intern structurally. Returns (nodes, root_idx);\n        nodes[i] = (op, srcs(tuple of idx), arg) in topological order.\"\"\"\n        if type(root) is not UOp:\n            raise Invalid(f\"optimize must return a UOp, not {type(root).__name__}\")\n        index, nodes, intern = {}, [], {}\n        stack = [(root, False)]\n        visited = 0\n        while stack:\n            obj, done = stack.pop()\n            oid = id(obj)\n            if done:\n                if oid in index:\n                    continue\n                op, src, arg = _OP.__get__(obj, UOp), _SRC.__get__(obj, UOp), _ARG.__get__(obj, UOp)\n                try:\n                    arg, akey = norm_arg(op, arg)\n                except ValueError as e:\n                    raise Invalid(str(e))\n                key = (op, tuple(index[id(s)] for s in src), akey)\n                if key not in intern:\n                    intern[key] = len(nodes)\n                    nodes.append((op, key[1], arg))\n                index[oid] = intern[key]\n                continue\n            if oid in index:\n                continue\n            visited += 1\n            if visited > MAX_NODES:\n                raise Invalid(f\"the program has more than {MAX_NODES} nodes\")\n            if type(obj) is not UOp:\n                raise Invalid(f\"a src is a {type(obj).__name__}, not a UOp\")\n            op, src = _OP.__get__(obj, UOp), _SRC.__get__(obj, UOp)\n            if not isinstance(op, str) or op not in OPS:\n                raise Invalid(f\"unknown op {op!r}\")\n            if type(src) is not tuple:\n                raise Invalid(\"src must be a tuple\")\n            stack.append((obj, True))\n            for s in reversed(src):\n                if type(s) is not UOp:\n                    raise Invalid(f\"a src is a {type(s).__name__}, not a UOp\")\n                if id(s) not in index:\n                    stack.append((s, False))\n        return nodes, index[id(root)]\n\n    def check(nodes):\n        \"\"\"Per node: (dtype, shape, free params). Raises Invalid.\"\"\"\n        info = []\n        for op, srcs, arg in nodes:\n            si = [info[s] for s in srcs]\n            try:\n                if op == \"CALL\":\n                    if not srcs:\n                        raise ValueError(\"CALL needs a body\")\n                    dt, sh = call_check(si[0][0], si[0][1], si[0][2], [(x[0], x[1]) for x in si[1:]])\n                    free = frozenset().union(*[x[2] for x in si[1:]]) if len(si) > 1 else frozenset()\n                else:\n                    dt, sh = infer(op, arg, [(x[0], x[1]) for x in si])\n                    free = frozenset((arg,)) if op == \"PARAM\" else \\\n                        (frozenset().union(*[x[2] for x in si]) if si else frozenset())\n            except ValueError as e:\n                raise Invalid(f\"{op}: {e}\")\n            info.append((dt, sh, free))\n        return info\n\n    def wrap(x):\n        return (x + 2147483648) % 4294967296 - 2147483648\n\n    def to_array(dt, vals):\n        if dt == \"i32\":\n            return np.array([int(v) for v in vals], dtype=np.int64)\n        if dt == \"f32\":\n            return np.array([float(v) for v in vals], dtype=np.float64).astype(np.float32)\n        return np.array([bool(v) for v in vals], dtype=bool)\n\n    def py_value(dt, x):\n        return int(x) if dt == \"i32\" else bool(x) if dt == \"bool\" else float(x)\n\n    def evaluate(nodes, info, root, env, N, depth=0, reach_cache=None):\n        if depth > MAX_CALL_DEPTH:\n            raise Invalid(\"CALLs are nested too deeply\")\n        if reach_cache is None:\n            reach_cache = {}\n        key = root\n        order = reach_cache.get(key)\n        if order is None:\n            seen, order, stack = set(), [], [(root, False)]\n            while stack:\n                i, done = stack.pop()\n                if done:\n                    order.append(i)\n                    continue\n                if i in seen:\n                    continue\n                seen.add(i)\n                stack.append((i, True))\n                op, srcs, _ = nodes[i]\n                for s in (srcs[1:] if op == \"CALL\" else srcs):\n                    if s not in seen:\n                        stack.append((s, False))\n            reach_cache[key] = order\n        val = {}\n        with np.errstate(all=\"ignore\"):\n            for i in order:\n                op, srcs, arg = nodes[i]\n                dt = info[i][0]\n                v = [val[s] for s in (srcs[1:] if op == \"CALL\" else srcs)]\n                if op == \"CONST\":\n                    r = np.full(N, np.float32(arg), dtype=np.float32) if dt == \"f32\" else \\\n                        np.full(N, arg, dtype=np.int64 if dt == \"i32\" else bool)\n                elif op == \"PARAM\":\n                    slot, pdt, lo, hi = arg\n                    if slot not in env:\n                        raise Invalid(f\"PARAM slot {slot} has no value here\")\n                    r = env[slot]\n                    if lo is not None and (r.min() < lo or r.max() > hi):\n                        raise Invalid(f\"a value outside the declared bounds [{lo}, {hi}] reaches PARAM slot {slot}\")\n                elif op == \"CALL\":\n                    body = srcs[0]\n                    benv = {}\n                    for (slot, pdt, lo, hi) in info[body][2]:\n                        benv[slot] = v[slot]\n                    r = evaluate(nodes, info, body, benv, N, depth + 1, reach_cache)\n                elif op == \"STACK\":\n                    r = np.stack(v)\n                elif op == \"INDEX\":\n                    x, ix = v\n                    if ix.min() < 0 or ix.max() >= x.shape[0]:\n                        raise Invalid(\"INDEX out of range\")\n                    r = x[ix, np.arange(N)]\n                elif op == \"SHRINK\":\n                    x, off = v\n                    if off.min() < 0 or off.max() + arg > x.shape[0]:\n                        raise Invalid(\"SHRINK window out of range\")\n                    rows = off[None, :] + np.arange(arg)[:, None]\n                    r = x[rows, np.arange(N)[None, :]]\n                elif op == \"CAST\":\n                    x, sd = v[0], info[srcs[0]][0]\n                    if dt == sd:\n                        r = x\n                    elif dt == \"f32\":\n                        r = x.astype(np.float32)\n                    elif dt == \"bool\":\n                        r = x != 0\n                    elif sd == \"bool\":\n                        r = x.astype(np.int64)\n                    else:\n                        t = np.trunc(x.astype(np.float64))\n                        if np.isnan(t).any() or t.min() < I32_MIN or t.max() > I32_MAX:\n                            raise Invalid(\"CAST f32 -> i32 of NaN or of a value outside the i32 range\")\n                        r = t.astype(np.int64)\n                elif op == \"RECIP\":\n                    r = (np.float32(1.0) / v[0]).astype(np.float32)\n                elif op == \"TRUNC\":\n                    r = np.trunc(v[0]).astype(np.float32)\n                elif op == \"WHERE\":\n                    r = np.where(v[0], v[1], v[2])\n                else:\n                    a, b = v\n                    if dt == \"bool\" and op != \"CMPLT\":\n                        r = (a | b) if op == \"MAX\" else (a ^ b)\n                    elif op == \"CMPLT\":\n                        r = (~a & b) if info[srcs[0]][0] == \"bool\" else (a < b)\n                    elif op == \"ADD\":\n                        r = wrap(a + b) if dt == \"i32\" else (a + b).astype(np.float32)\n                    elif op == \"MUL\":\n                        r = wrap(a * b) if dt == \"i32\" else (a * b).astype(np.float32)\n                    elif op == \"MAX\":\n                        if dt == \"i32\":\n                            r = np.maximum(a, b)\n                        else:\n                            r = np.maximum(a, b).astype(np.float32)\n                            z = (a == 0) & (b == 0)\n                            if z.any():\n                                both_neg = np.signbit(a) & np.signbit(b)\n                                r = np.where(z, np.where(both_neg, np.float32(-0.0), np.float32(0.0)), r).astype(np.float32)\n                    elif op == \"XOR\":\n                        r = a ^ b\n                    elif op == \"SHL\":\n                        if b.min() < 0 or b.max() > 31:\n                            raise Invalid(\"SHL amount outside 0..31\")\n                        r = wrap(a * np.left_shift(np.int64(1), b))\n                    elif op == \"DIV\":\n                        if (b == 0).any():\n                            raise Invalid(\"DIV by zero\")\n                        r = wrap(np.floor_divide(a, b))\n                    elif op == \"MOD\":\n                        if (b == 0).any():\n                            raise Invalid(\"MOD by zero\")\n                        r = np.mod(a, b)\n                    else:\n                        raise Invalid(f\"cannot evaluate {op}\")\n                val[i] = r\n        return val[root]\n\n    def same(dt, a, b):\n        if a.shape != b.shape:\n            return np.zeros(a.shape[-1], bool)\n        if dt == \"f32\":\n            ok = (a.view(np.uint32) == b.view(np.uint32)) | (np.isnan(a) & np.isnan(b))\n        else:\n            ok = a == b\n        return ok if ok.ndim == 1 else ok.all(axis=0)\n\n    return {\"UOp\": UOp, \"Invalid\": Invalid, \"ingest\": ingest, \"check\": check, \"evaluate\": evaluate,\n            \"same\": same, \"py_value\": py_value, \"to_array\": to_array}\n\n\nUOp = _dml_uop_lib()[\"UOp\"]\np = UOp.param(0, \"i32\", 0, 9)\nq = UOp.param(1, \"f32\")\nr1 = optimize(UOp(\"ADD\", (UOp(\"MUL\", (p, UOp.const(3))), UOp.const(4))))\nr2 = optimize(UOp(\"MUL\", (q, UOp.const(2.0))))\nok = type(r1) is UOp and type(r2) is UOp\nok = ok and all(r1.evaluate({0: v}) == 3 * v + 4 for v in range(10))\nok = ok and all(r2.evaluate({1: x}) == 2.0 * x for x in (0.5, -3.0, 1.25))\nprint(ok)","expected_output":"True"},{"test":"def _dml_uop_lib():\n    \"\"\"The UOp class plus the exact evaluator the grader uses (hash-consed, immutable UOp(op, src, arg)).\"\"\"\n    import math\n    import struct\n\n    import numpy as np\n\n    I32_MIN, I32_MAX = -(2 ** 31), 2 ** 31 - 1\n    FULL = (I32_MIN, I32_MAX)\n    DTYPES = (\"bool\", \"i32\", \"f32\")\n    ALU = (\"CAST\", \"RECIP\", \"TRUNC\", \"ADD\", \"MUL\", \"MAX\", \"XOR\", \"CMPLT\", \"SHL\", \"DIV\", \"MOD\", \"WHERE\")\n    OPS = frozenset((\"CONST\", \"PARAM\", \"CALL\", \"STACK\", \"INDEX\", \"SHRINK\") + ALU)\n    MAX_NODES = 20000\n    MAX_CALL_DEPTH = 64\n\n    # ------------------------------------------------------------------ exact value semantics\n    def f32_bits(v):\n        return struct.unpack(\"<I\", struct.pack(\"<f\", v))[0]\n\n    def norm_dtype(d):\n        for c in DTYPES:\n            if type(d) is str and d == c:\n                return c\n        raise ValueError(f\"unknown dtype {d!r} (use 'bool', 'i32' or 'f32')\")\n\n    def norm_const(v):\n        if isinstance(v, (bool, np.bool_)):\n            return bool(v)\n        if isinstance(v, (int, np.integer)):\n            v = int(v)\n            if not I32_MIN <= v <= I32_MAX:\n                raise ValueError(f\"i32 CONST {v} is out of range\")\n            return v\n        if isinstance(v, (float, np.floating)):\n            v = float(v)\n            if not math.isnan(v):\n                with np.errstate(over=\"ignore\"):\n                    if float(np.float32(v)) != v:\n                        raise ValueError(f\"f32 CONST {v!r} is not exactly representable as float32\")\n            return v\n        raise ValueError(f\"CONST arg must be a bool, int or float, not {type(v).__name__}\")\n\n    def const_dtype(v):\n        return \"bool\" if type(v) is bool else \"i32\" if type(v) is int else \"f32\"\n\n    def norm_arg(op, arg):\n        \"\"\"Returns (normalized arg, hashable key).\"\"\"\n        if op == \"CONST\":\n            v = norm_const(arg)\n            return v, (const_dtype(v), f32_bits(v) if type(v) is float else v)\n        if op == \"PARAM\":\n            if not isinstance(arg, tuple) or len(arg) not in (2, 4):\n                raise ValueError(\"PARAM arg must be (slot, dtype) or (slot, dtype, lo, hi)\")\n            slot, dt = arg[0], norm_dtype(arg[1])\n            lo, hi = (arg[2], arg[3]) if len(arg) == 4 else (None, None)\n            if type(slot) is not int or not 0 <= slot < 64:\n                raise ValueError(\"PARAM slot must be an int in 0..63\")\n            if dt == \"i32\":\n                if (lo is None) != (hi is None):\n                    raise ValueError(\"PARAM bounds must give both lo and hi, or neither\")\n                if lo is not None:\n                    if type(lo) is not int or type(hi) is not int or not I32_MIN <= lo <= hi <= I32_MAX:\n                        raise ValueError(\"PARAM bounds must be ints with lo <= hi inside the i32 range\")\n            elif lo is not None or hi is not None:\n                raise ValueError(\"only i32 PARAMs take bounds\")\n            a = (slot, dt, lo, hi)\n            return a, a\n        if op == \"CAST\":\n            d = norm_dtype(arg)\n            return d, d\n        if op == \"SHRINK\":\n            if type(arg) is not int or arg < 1:\n                raise ValueError(\"SHRINK arg is the window size, an int >= 1\")\n            return arg, arg\n        if arg is not None:\n            raise ValueError(f\"{op} takes no arg\")\n        return None, None\n\n    def infer(op, arg, srcs):\n        \"\"\"srcs: list of (dtype, shape). Returns (dtype, shape) or raises ValueError.\"\"\"\n        n = len(srcs)\n        if op in (\"CONST\", \"PARAM\"):\n            if n:\n                raise ValueError(f\"{op} has no srcs\")\n            return (const_dtype(arg) if op == \"CONST\" else arg[1]), ()\n        if op == \"STACK\":\n            if n < 1:\n                raise ValueError(\"STACK needs at least one src\")\n            if any(s[1] != () for s in srcs) or len({s[0] for s in srcs}) != 1:\n                raise ValueError(\"STACK srcs must be scalars of one dtype\")\n            return srcs[0][0], (n,)\n        if op == \"INDEX\":\n            if n != 2 or len(srcs[0][1]) != 1 or srcs[1] != (\"i32\", ()):\n                raise ValueError(\"INDEX takes a rank-1 value and one i32 scalar index\")\n            return srcs[0][0], ()\n        if op == \"SHRINK\":\n            if n != 2 or len(srcs[0][1]) != 1 or srcs[1] != (\"i32\", ()):\n                raise ValueError(\"SHRINK takes a rank-1 value and an i32 scalar offset\")\n            if arg > srcs[0][1][0]:\n                raise ValueError(\"SHRINK window is larger than its input\")\n            return srcs[0][0], (arg,)\n        if op == \"CALL\":\n            raise ValueError(\"internal: CALL handled separately\")\n        if any(s[1] != () for s in srcs):\n            raise ValueError(f\"{op} operands must be scalars\")\n        dts = [s[0] for s in srcs]\n        if op == \"CAST\":\n            if n != 1:\n                raise ValueError(\"CAST takes one src\")\n            return arg, ()\n        if op in (\"RECIP\", \"TRUNC\"):\n            if n != 1 or dts[0] != \"f32\":\n                raise ValueError(f\"{op} takes one f32 src\")\n            return \"f32\", ()\n        if op == \"WHERE\":\n            if n != 3 or dts[0] != \"bool\" or dts[1] != dts[2]:\n                raise ValueError(\"WHERE takes (bool, x, y) with x and y of the same dtype\")\n            return dts[1], ()\n        if n != 2 or dts[0] != dts[1]:\n            raise ValueError(f\"{op} takes two srcs of the same dtype\")\n        d = dts[0]\n        if op in (\"ADD\", \"MUL\") and d == \"bool\":\n            raise ValueError(f\"{op} is not defined on bool\")\n        if op in (\"SHL\", \"DIV\", \"MOD\") and d != \"i32\":\n            raise ValueError(f\"{op} is i32 only\")\n        if op == \"XOR\" and d == \"f32\":\n            raise ValueError(\"XOR is not defined on f32\")\n        if op == \"CMPLT\":\n            return \"bool\", ()\n        return d, ()\n\n    def call_check(body_dt, body_shape, body_free, arg_infos):\n        if body_shape != ():\n            raise ValueError(\"a CALL body must be a scalar\")\n        slots = {}\n        for (slot, dt, lo, hi) in body_free:\n            if slot in slots:\n                raise ValueError(f\"a CALL body has two different PARAMs with slot {slot}\")\n            slots[slot] = dt\n        for slot, dt in slots.items():\n            if slot >= len(arg_infos):\n                raise ValueError(f\"CALL passes {len(arg_infos)} args but its body uses PARAM slot {slot}\")\n            if arg_infos[slot] != (dt, ()):\n                raise ValueError(f\"CALL arg {slot} must be a scalar {dt}\")\n        return body_dt, ()\n\n    # ------------------------------------------------------------------ interval bounds (sound, conservative)\n    def clampb(lo, hi):\n        return (lo, hi) if I32_MIN <= lo and hi <= I32_MAX else FULL\n\n    def fdiv(a, b):\n        return a // b\n\n    def bounds_of(op, arg, dtype, srcb, srcd):\n        if dtype == \"f32\":\n            return None\n        if op == \"CONST\":\n            return (int(arg), int(arg))\n        if op == \"PARAM\":\n            if dtype == \"bool\":\n                return (0, 1)\n            return (arg[2], arg[3]) if arg[2] is not None else FULL\n        if op in (\"STACK\",):\n            return (min(b[0] for b in srcb), max(b[1] for b in srcb))\n        if op in (\"INDEX\", \"SHRINK\"):\n            return srcb[0]\n        if op == \"CALL\":\n            return srcb[0]\n        if op == \"CAST\":\n            sd = srcd[0]\n            if dtype == \"i32\":\n                return srcb[0] if sd in (\"bool\", \"i32\") else FULL\n            if dtype == \"bool\":\n                if sd == \"f32\":\n                    return (0, 1)\n                lo, hi = srcb[0]\n                if lo == 0 and hi == 0:\n                    return (0, 0)\n                if lo > 0 or hi < 0:\n                    return (1, 1)\n                return (0, 1)\n        if op == \"WHERE\":\n            c, a, b = srcb\n            if c == (1, 1):\n                return a\n            if c == (0, 0):\n                return b\n            return (min(a[0], b[0]), max(a[1], b[1]))\n        if op == \"CMPLT\":\n            if srcd[0] == \"f32\":\n                return (0, 1)\n            (alo, ahi), (blo, bhi) = srcb\n            if ahi < blo:\n                return (1, 1)\n            if alo >= bhi:\n                return (0, 0)\n            return (0, 1)\n        (alo, ahi), (blo, bhi) = srcb[0], srcb[1]\n        if dtype == \"bool\":\n            if op == \"MAX\":\n                return (max(alo, blo), max(ahi, bhi))\n            if op == \"XOR\":\n                if alo == ahi and blo == bhi:\n                    return (alo ^ blo, alo ^ blo)\n                return (0, 1)\n            return (0, 1)\n        if op == \"ADD\":\n            return clampb(alo + blo, ahi + bhi)\n        if op == \"MUL\":\n            c = (alo * blo, alo * bhi, ahi * blo, ahi * bhi)\n            return clampb(min(c), max(c))\n        if op == \"MAX\":\n            return (max(alo, blo), max(ahi, bhi))\n        if op == \"XOR\":\n            if alo >= 0 and blo >= 0:\n                return (0, (1 << max(ahi, bhi).bit_length()) - 1)\n            return FULL\n        if op == \"SHL\":\n            if blo < 0 or bhi > 31:\n                return FULL\n            c = (alo << blo, alo << bhi, ahi << blo, ahi << bhi)\n            return clampb(min(c), max(c))\n        if op == \"DIV\":\n            if blo <= 0 <= bhi:\n                return FULL\n            if alo == I32_MIN and blo <= -1 <= bhi:\n                return FULL\n            c = (fdiv(alo, blo), fdiv(alo, bhi), fdiv(ahi, blo), fdiv(ahi, bhi))\n            return clampb(min(c), max(c))\n        if op == \"MOD\":\n            if blo > 0:\n                if alo >= 0 and ahi < blo:\n                    return (alo, ahi)\n                if blo == bhi and alo // blo == ahi // blo:\n                    return (alo % blo, ahi % blo)\n                return (0, bhi - 1)\n            if bhi < 0:\n                return (blo + 1, 0)\n            return FULL\n        return FULL\n\n    # ------------------------------------------------------------------ the public UOp class\n    _cache = {}\n\n    class UOp:\n        \"\"\"Hash-consed, immutable UOp(op, src, arg). See the lab description for the API.\"\"\"\n        __slots__ = (\"op\", \"src\", \"arg\", \"dtype\", \"shape\", \"_bounds\", \"_free\")\n\n        def __new__(cls, op, src=(), arg=None):\n            if not isinstance(op, str):\n                raise TypeError(\"op must be a string such as 'ADD'\")\n            op = op.upper()\n            if op not in OPS:\n                raise ValueError(f\"unknown op {op!r}\")\n            src = tuple(src)\n            for s in src:\n                if type(s) is not UOp:\n                    raise TypeError(f\"every src must be a UOp, got {type(s).__name__}\")\n            arg, akey = norm_arg(op, arg)\n            key = (op, tuple(id(s) for s in src), akey)\n            hit = _cache.get(key)\n            if hit is not None:\n                return hit\n            infos = [(s.dtype, s.shape) for s in src]\n            if op == \"CALL\":\n                if len(src) < 1:\n                    raise ValueError(\"CALL needs a body\")\n                b = src[0]\n                dtype, shape = call_check(b.dtype, b.shape, b._free, infos[1:])\n                free = frozenset().union(*[s._free for s in src[1:]]) if len(src) > 1 else frozenset()\n            else:\n                dtype, shape = infer(op, arg, infos)\n                if op == \"PARAM\":\n                    free = frozenset((arg,))\n                else:\n                    free = frozenset().union(*[s._free for s in src]) if src else frozenset()\n            bnd = bounds_of(op, arg, dtype, [s._bounds for s in src], [s.dtype for s in src])\n            self = object.__new__(cls)\n            for k, v in ((\"op\", op), (\"src\", src), (\"arg\", arg), (\"dtype\", dtype), (\"shape\", shape),\n                         (\"_bounds\", bnd), (\"_free\", free)):\n                object.__setattr__(self, k, v)\n            _cache[key] = self\n            return self\n\n        def __setattr__(self, k, v):\n            raise AttributeError(\"UOps are immutable; build a new one\")\n\n        def __delattr__(self, k):\n            raise AttributeError(\"UOps are immutable\")\n\n        @property\n        def bounds(self):\n            return self._bounds\n\n        @property\n        def params(self):\n            \"\"\"The PARAM args (slot, dtype, lo, hi) this value depends on, not looking inside CALL bodies.\"\"\"\n            return self._free\n\n        @staticmethod\n        def const(value, dtype=None):\n            if dtype is not None:\n                dtype = norm_dtype(dtype)\n                value = bool(value) if dtype == \"bool\" else int(value) if dtype == \"i32\" else \\\n                    float(np.float32(value))\n            return UOp(\"CONST\", (), value)\n\n        @staticmethod\n        def param(slot, dtype, lo=None, hi=None):\n            return UOp(\"PARAM\", (), (slot, dtype, lo, hi))\n\n        def toposort(self):\n            out, seen, stack = [], set(), [(self, False)]\n            while stack:\n                n, done = stack.pop()\n                if done:\n                    out.append(n)\n                    continue\n                if id(n) in seen:\n                    continue\n                seen.add(id(n))\n                stack.append((n, True))\n                for s in reversed(n.src):\n                    if id(s) not in seen:\n                        stack.append((s, False))\n            return out\n\n        def size(self):\n            return len(self.toposort())\n\n        def evaluate(self, inputs=None):\n            nodes, root = ingest(self)\n            info = check(nodes)\n            env = {}\n            for (slot, dt, lo, hi) in info[root][2]:\n                if inputs is None or slot not in inputs:\n                    raise ValueError(f\"evaluate needs inputs[{slot}] for PARAM slot {slot}\")\n                env[slot] = to_array(dt, [inputs[slot]])\n            v = evaluate(nodes, info, root, env, 1)\n            if v.ndim == 2:\n                return [py_value(info[root][0], x[0]) for x in v]\n            return py_value(info[root][0], v[0])\n\n        def render(self):\n            names, lines = {}, []\n            for n in self.toposort():\n                name = f\"%{len(names)}\"\n                names[id(n)] = name\n                a = [names[id(s)] for s in n.src]\n                if n.op == \"CONST\":\n                    v = n.arg\n                    txt = (\"true\" if v else \"false\") if type(v) is bool else repr(v)\n                    lines.append(f\"{name} = const {txt} : dtype={n.dtype}\")\n                elif n.op == \"PARAM\":\n                    slot, dt, lo, hi = n.arg\n                    extra = f\" min={lo} max={hi}\" if lo is not None else \"\"\n                    lines.append(f\"{name} = param [] : dtype={dt} slot={slot}{extra}\")\n                elif n.op == \"CAST\":\n                    lines.append(f\"{name} = cast {a[0]} : dtype={n.arg}\")\n                elif n.op == \"SHRINK\":\n                    lines.append(f\"{name} = shrink {a[0]} {a[1]} {n.arg}\")\n                else:\n                    lines.append(f\"{name} = {n.op.lower()} \" + \" \".join(a))\n            return \"\\n\".join(lines)\n\n        def __repr__(self):\n            if self.op == \"CONST\":\n                return f\"UOp.const({self.arg!r})\"\n            if self.op == \"PARAM\":\n                return f\"UOp.param{self.arg!r}\"\n            return f\"UOp({self.op!r}, <{len(self.src)} srcs>, {self.arg!r}) : {self.dtype}{list(self.shape) or ''}\"\n\n    _OP, _SRC, _ARG = UOp.__dict__[\"op\"], UOp.__dict__[\"src\"], UOp.__dict__[\"arg\"]\n\n    # ------------------------------------------------------------------ grading: ingest, check, evaluate\n    class Invalid(Exception):\n        pass\n\n    def ingest(root):\n        \"\"\"Walk a graph of UOp objects reading raw slots, re-intern structurally. Returns (nodes, root_idx);\n        nodes[i] = (op, srcs(tuple of idx), arg) in topological order.\"\"\"\n        if type(root) is not UOp:\n            raise Invalid(f\"optimize must return a UOp, not {type(root).__name__}\")\n        index, nodes, intern = {}, [], {}\n        stack = [(root, False)]\n        visited = 0\n        while stack:\n            obj, done = stack.pop()\n            oid = id(obj)\n            if done:\n                if oid in index:\n                    continue\n                op, src, arg = _OP.__get__(obj, UOp), _SRC.__get__(obj, UOp), _ARG.__get__(obj, UOp)\n                try:\n                    arg, akey = norm_arg(op, arg)\n                except ValueError as e:\n                    raise Invalid(str(e))\n                key = (op, tuple(index[id(s)] for s in src), akey)\n                if key not in intern:\n                    intern[key] = len(nodes)\n                    nodes.append((op, key[1], arg))\n                index[oid] = intern[key]\n                continue\n            if oid in index:\n                continue\n            visited += 1\n            if visited > MAX_NODES:\n                raise Invalid(f\"the program has more than {MAX_NODES} nodes\")\n            if type(obj) is not UOp:\n                raise Invalid(f\"a src is a {type(obj).__name__}, not a UOp\")\n            op, src = _OP.__get__(obj, UOp), _SRC.__get__(obj, UOp)\n            if not isinstance(op, str) or op not in OPS:\n                raise Invalid(f\"unknown op {op!r}\")\n            if type(src) is not tuple:\n                raise Invalid(\"src must be a tuple\")\n            stack.append((obj, True))\n            for s in reversed(src):\n                if type(s) is not UOp:\n                    raise Invalid(f\"a src is a {type(s).__name__}, not a UOp\")\n                if id(s) not in index:\n                    stack.append((s, False))\n        return nodes, index[id(root)]\n\n    def check(nodes):\n        \"\"\"Per node: (dtype, shape, free params). Raises Invalid.\"\"\"\n        info = []\n        for op, srcs, arg in nodes:\n            si = [info[s] for s in srcs]\n            try:\n                if op == \"CALL\":\n                    if not srcs:\n                        raise ValueError(\"CALL needs a body\")\n                    dt, sh = call_check(si[0][0], si[0][1], si[0][2], [(x[0], x[1]) for x in si[1:]])\n                    free = frozenset().union(*[x[2] for x in si[1:]]) if len(si) > 1 else frozenset()\n                else:\n                    dt, sh = infer(op, arg, [(x[0], x[1]) for x in si])\n                    free = frozenset((arg,)) if op == \"PARAM\" else \\\n                        (frozenset().union(*[x[2] for x in si]) if si else frozenset())\n            except ValueError as e:\n                raise Invalid(f\"{op}: {e}\")\n            info.append((dt, sh, free))\n        return info\n\n    def wrap(x):\n        return (x + 2147483648) % 4294967296 - 2147483648\n\n    def to_array(dt, vals):\n        if dt == \"i32\":\n            return np.array([int(v) for v in vals], dtype=np.int64)\n        if dt == \"f32\":\n            return np.array([float(v) for v in vals], dtype=np.float64).astype(np.float32)\n        return np.array([bool(v) for v in vals], dtype=bool)\n\n    def py_value(dt, x):\n        return int(x) if dt == \"i32\" else bool(x) if dt == \"bool\" else float(x)\n\n    def evaluate(nodes, info, root, env, N, depth=0, reach_cache=None):\n        if depth > MAX_CALL_DEPTH:\n            raise Invalid(\"CALLs are nested too deeply\")\n        if reach_cache is None:\n            reach_cache = {}\n        key = root\n        order = reach_cache.get(key)\n        if order is None:\n            seen, order, stack = set(), [], [(root, False)]\n            while stack:\n                i, done = stack.pop()\n                if done:\n                    order.append(i)\n                    continue\n                if i in seen:\n                    continue\n                seen.add(i)\n                stack.append((i, True))\n                op, srcs, _ = nodes[i]\n                for s in (srcs[1:] if op == \"CALL\" else srcs):\n                    if s not in seen:\n                        stack.append((s, False))\n            reach_cache[key] = order\n        val = {}\n        with np.errstate(all=\"ignore\"):\n            for i in order:\n                op, srcs, arg = nodes[i]\n                dt = info[i][0]\n                v = [val[s] for s in (srcs[1:] if op == \"CALL\" else srcs)]\n                if op == \"CONST\":\n                    r = np.full(N, np.float32(arg), dtype=np.float32) if dt == \"f32\" else \\\n                        np.full(N, arg, dtype=np.int64 if dt == \"i32\" else bool)\n                elif op == \"PARAM\":\n                    slot, pdt, lo, hi = arg\n                    if slot not in env:\n                        raise Invalid(f\"PARAM slot {slot} has no value here\")\n                    r = env[slot]\n                    if lo is not None and (r.min() < lo or r.max() > hi):\n                        raise Invalid(f\"a value outside the declared bounds [{lo}, {hi}] reaches PARAM slot {slot}\")\n                elif op == \"CALL\":\n                    body = srcs[0]\n                    benv = {}\n                    for (slot, pdt, lo, hi) in info[body][2]:\n                        benv[slot] = v[slot]\n                    r = evaluate(nodes, info, body, benv, N, depth + 1, reach_cache)\n                elif op == \"STACK\":\n                    r = np.stack(v)\n                elif op == \"INDEX\":\n                    x, ix = v\n                    if ix.min() < 0 or ix.max() >= x.shape[0]:\n                        raise Invalid(\"INDEX out of range\")\n                    r = x[ix, np.arange(N)]\n                elif op == \"SHRINK\":\n                    x, off = v\n                    if off.min() < 0 or off.max() + arg > x.shape[0]:\n                        raise Invalid(\"SHRINK window out of range\")\n                    rows = off[None, :] + np.arange(arg)[:, None]\n                    r = x[rows, np.arange(N)[None, :]]\n                elif op == \"CAST\":\n                    x, sd = v[0], info[srcs[0]][0]\n                    if dt == sd:\n                        r = x\n                    elif dt == \"f32\":\n                        r = x.astype(np.float32)\n                    elif dt == \"bool\":\n                        r = x != 0\n                    elif sd == \"bool\":\n                        r = x.astype(np.int64)\n                    else:\n                        t = np.trunc(x.astype(np.float64))\n                        if np.isnan(t).any() or t.min() < I32_MIN or t.max() > I32_MAX:\n                            raise Invalid(\"CAST f32 -> i32 of NaN or of a value outside the i32 range\")\n                        r = t.astype(np.int64)\n                elif op == \"RECIP\":\n                    r = (np.float32(1.0) / v[0]).astype(np.float32)\n                elif op == \"TRUNC\":\n                    r = np.trunc(v[0]).astype(np.float32)\n                elif op == \"WHERE\":\n                    r = np.where(v[0], v[1], v[2])\n                else:\n                    a, b = v\n                    if dt == \"bool\" and op != \"CMPLT\":\n                        r = (a | b) if op == \"MAX\" else (a ^ b)\n                    elif op == \"CMPLT\":\n                        r = (~a & b) if info[srcs[0]][0] == \"bool\" else (a < b)\n                    elif op == \"ADD\":\n                        r = wrap(a + b) if dt == \"i32\" else (a + b).astype(np.float32)\n                    elif op == \"MUL\":\n                        r = wrap(a * b) if dt == \"i32\" else (a * b).astype(np.float32)\n                    elif op == \"MAX\":\n                        if dt == \"i32\":\n                            r = np.maximum(a, b)\n                        else:\n                            r = np.maximum(a, b).astype(np.float32)\n                            z = (a == 0) & (b == 0)\n                            if z.any():\n                                both_neg = np.signbit(a) & np.signbit(b)\n                                r = np.where(z, np.where(both_neg, np.float32(-0.0), np.float32(0.0)), r).astype(np.float32)\n                    elif op == \"XOR\":\n                        r = a ^ b\n                    elif op == \"SHL\":\n                        if b.min() < 0 or b.max() > 31:\n                            raise Invalid(\"SHL amount outside 0..31\")\n                        r = wrap(a * np.left_shift(np.int64(1), b))\n                    elif op == \"DIV\":\n                        if (b == 0).any():\n                            raise Invalid(\"DIV by zero\")\n                        r = wrap(np.floor_divide(a, b))\n                    elif op == \"MOD\":\n                        if (b == 0).any():\n                            raise Invalid(\"MOD by zero\")\n                        r = np.mod(a, b)\n                    else:\n                        raise Invalid(f\"cannot evaluate {op}\")\n                val[i] = r\n        return val[root]\n\n    def same(dt, a, b):\n        if a.shape != b.shape:\n            return np.zeros(a.shape[-1], bool)\n        if dt == \"f32\":\n            ok = (a.view(np.uint32) == b.view(np.uint32)) | (np.isnan(a) & np.isnan(b))\n        else:\n            ok = a == b\n        return ok if ok.ndim == 1 else ok.all(axis=0)\n\n    return {\"UOp\": UOp, \"Invalid\": Invalid, \"ingest\": ingest, \"check\": check, \"evaluate\": evaluate,\n            \"same\": same, \"py_value\": py_value, \"to_array\": to_array}\n\n\nUOp = _dml_uop_lib()[\"UOp\"]\nc = UOp(\"ADD\", (UOp(\"MUL\", (UOp.const(6), UOp.const(7))), UOp.const(-2)))\nr = optimize(c)\nprint(r.size() == 1 and r.evaluate() == 40)","expected_output":"True"},{"test":"def _dml_uop_lib():\n    \"\"\"The UOp class plus the exact evaluator the grader uses (hash-consed, immutable UOp(op, src, arg)).\"\"\"\n    import math\n    import struct\n\n    import numpy as np\n\n    I32_MIN, I32_MAX = -(2 ** 31), 2 ** 31 - 1\n    FULL = (I32_MIN, I32_MAX)\n    DTYPES = (\"bool\", \"i32\", \"f32\")\n    ALU = (\"CAST\", \"RECIP\", \"TRUNC\", \"ADD\", \"MUL\", \"MAX\", \"XOR\", \"CMPLT\", \"SHL\", \"DIV\", \"MOD\", \"WHERE\")\n    OPS = frozenset((\"CONST\", \"PARAM\", \"CALL\", \"STACK\", \"INDEX\", \"SHRINK\") + ALU)\n    MAX_NODES = 20000\n    MAX_CALL_DEPTH = 64\n\n    # ------------------------------------------------------------------ exact value semantics\n    def f32_bits(v):\n        return struct.unpack(\"<I\", struct.pack(\"<f\", v))[0]\n\n    def norm_dtype(d):\n        for c in DTYPES:\n            if type(d) is str and d == c:\n                return c\n        raise ValueError(f\"unknown dtype {d!r} (use 'bool', 'i32' or 'f32')\")\n\n    def norm_const(v):\n        if isinstance(v, (bool, np.bool_)):\n            return bool(v)\n        if isinstance(v, (int, np.integer)):\n            v = int(v)\n            if not I32_MIN <= v <= I32_MAX:\n                raise ValueError(f\"i32 CONST {v} is out of range\")\n            return v\n        if isinstance(v, (float, np.floating)):\n            v = float(v)\n            if not math.isnan(v):\n                with np.errstate(over=\"ignore\"):\n                    if float(np.float32(v)) != v:\n                        raise ValueError(f\"f32 CONST {v!r} is not exactly representable as float32\")\n            return v\n        raise ValueError(f\"CONST arg must be a bool, int or float, not {type(v).__name__}\")\n\n    def const_dtype(v):\n        return \"bool\" if type(v) is bool else \"i32\" if type(v) is int else \"f32\"\n\n    def norm_arg(op, arg):\n        \"\"\"Returns (normalized arg, hashable key).\"\"\"\n        if op == \"CONST\":\n            v = norm_const(arg)\n            return v, (const_dtype(v), f32_bits(v) if type(v) is float else v)\n        if op == \"PARAM\":\n            if not isinstance(arg, tuple) or len(arg) not in (2, 4):\n                raise ValueError(\"PARAM arg must be (slot, dtype) or (slot, dtype, lo, hi)\")\n            slot, dt = arg[0], norm_dtype(arg[1])\n            lo, hi = (arg[2], arg[3]) if len(arg) == 4 else (None, None)\n            if type(slot) is not int or not 0 <= slot < 64:\n                raise ValueError(\"PARAM slot must be an int in 0..63\")\n            if dt == \"i32\":\n                if (lo is None) != (hi is None):\n                    raise ValueError(\"PARAM bounds must give both lo and hi, or neither\")\n                if lo is not None:\n                    if type(lo) is not int or type(hi) is not int or not I32_MIN <= lo <= hi <= I32_MAX:\n                        raise ValueError(\"PARAM bounds must be ints with lo <= hi inside the i32 range\")\n            elif lo is not None or hi is not None:\n                raise ValueError(\"only i32 PARAMs take bounds\")\n            a = (slot, dt, lo, hi)\n            return a, a\n        if op == \"CAST\":\n            d = norm_dtype(arg)\n            return d, d\n        if op == \"SHRINK\":\n            if type(arg) is not int or arg < 1:\n                raise ValueError(\"SHRINK arg is the window size, an int >= 1\")\n            return arg, arg\n        if arg is not None:\n            raise ValueError(f\"{op} takes no arg\")\n        return None, None\n\n    def infer(op, arg, srcs):\n        \"\"\"srcs: list of (dtype, shape). Returns (dtype, shape) or raises ValueError.\"\"\"\n        n = len(srcs)\n        if op in (\"CONST\", \"PARAM\"):\n            if n:\n                raise ValueError(f\"{op} has no srcs\")\n            return (const_dtype(arg) if op == \"CONST\" else arg[1]), ()\n        if op == \"STACK\":\n            if n < 1:\n                raise ValueError(\"STACK needs at least one src\")\n            if any(s[1] != () for s in srcs) or len({s[0] for s in srcs}) != 1:\n                raise ValueError(\"STACK srcs must be scalars of one dtype\")\n            return srcs[0][0], (n,)\n        if op == \"INDEX\":\n            if n != 2 or len(srcs[0][1]) != 1 or srcs[1] != (\"i32\", ()):\n                raise ValueError(\"INDEX takes a rank-1 value and one i32 scalar index\")\n            return srcs[0][0], ()\n        if op == \"SHRINK\":\n            if n != 2 or len(srcs[0][1]) != 1 or srcs[1] != (\"i32\", ()):\n                raise ValueError(\"SHRINK takes a rank-1 value and an i32 scalar offset\")\n            if arg > srcs[0][1][0]:\n                raise ValueError(\"SHRINK window is larger than its input\")\n            return srcs[0][0], (arg,)\n        if op == \"CALL\":\n            raise ValueError(\"internal: CALL handled separately\")\n        if any(s[1] != () for s in srcs):\n            raise ValueError(f\"{op} operands must be scalars\")\n        dts = [s[0] for s in srcs]\n        if op == \"CAST\":\n            if n != 1:\n                raise ValueError(\"CAST takes one src\")\n            return arg, ()\n        if op in (\"RECIP\", \"TRUNC\"):\n            if n != 1 or dts[0] != \"f32\":\n                raise ValueError(f\"{op} takes one f32 src\")\n            return \"f32\", ()\n        if op == \"WHERE\":\n            if n != 3 or dts[0] != \"bool\" or dts[1] != dts[2]:\n                raise ValueError(\"WHERE takes (bool, x, y) with x and y of the same dtype\")\n            return dts[1], ()\n        if n != 2 or dts[0] != dts[1]:\n            raise ValueError(f\"{op} takes two srcs of the same dtype\")\n        d = dts[0]\n        if op in (\"ADD\", \"MUL\") and d == \"bool\":\n            raise ValueError(f\"{op} is not defined on bool\")\n        if op in (\"SHL\", \"DIV\", \"MOD\") and d != \"i32\":\n            raise ValueError(f\"{op} is i32 only\")\n        if op == \"XOR\" and d == \"f32\":\n            raise ValueError(\"XOR is not defined on f32\")\n        if op == \"CMPLT\":\n            return \"bool\", ()\n        return d, ()\n\n    def call_check(body_dt, body_shape, body_free, arg_infos):\n        if body_shape != ():\n            raise ValueError(\"a CALL body must be a scalar\")\n        slots = {}\n        for (slot, dt, lo, hi) in body_free:\n            if slot in slots:\n                raise ValueError(f\"a CALL body has two different PARAMs with slot {slot}\")\n            slots[slot] = dt\n        for slot, dt in slots.items():\n            if slot >= len(arg_infos):\n                raise ValueError(f\"CALL passes {len(arg_infos)} args but its body uses PARAM slot {slot}\")\n            if arg_infos[slot] != (dt, ()):\n                raise ValueError(f\"CALL arg {slot} must be a scalar {dt}\")\n        return body_dt, ()\n\n    # ------------------------------------------------------------------ interval bounds (sound, conservative)\n    def clampb(lo, hi):\n        return (lo, hi) if I32_MIN <= lo and hi <= I32_MAX else FULL\n\n    def fdiv(a, b):\n        return a // b\n\n    def bounds_of(op, arg, dtype, srcb, srcd):\n        if dtype == \"f32\":\n            return None\n        if op == \"CONST\":\n            return (int(arg), int(arg))\n        if op == \"PARAM\":\n            if dtype == \"bool\":\n                return (0, 1)\n            return (arg[2], arg[3]) if arg[2] is not None else FULL\n        if op in (\"STACK\",):\n            return (min(b[0] for b in srcb), max(b[1] for b in srcb))\n        if op in (\"INDEX\", \"SHRINK\"):\n            return srcb[0]\n        if op == \"CALL\":\n            return srcb[0]\n        if op == \"CAST\":\n            sd = srcd[0]\n            if dtype == \"i32\":\n                return srcb[0] if sd in (\"bool\", \"i32\") else FULL\n            if dtype == \"bool\":\n                if sd == \"f32\":\n                    return (0, 1)\n                lo, hi = srcb[0]\n                if lo == 0 and hi == 0:\n                    return (0, 0)\n                if lo > 0 or hi < 0:\n                    return (1, 1)\n                return (0, 1)\n        if op == \"WHERE\":\n            c, a, b = srcb\n            if c == (1, 1):\n                return a\n            if c == (0, 0):\n                return b\n            return (min(a[0], b[0]), max(a[1], b[1]))\n        if op == \"CMPLT\":\n            if srcd[0] == \"f32\":\n                return (0, 1)\n            (alo, ahi), (blo, bhi) = srcb\n            if ahi < blo:\n                return (1, 1)\n            if alo >= bhi:\n                return (0, 0)\n            return (0, 1)\n        (alo, ahi), (blo, bhi) = srcb[0], srcb[1]\n        if dtype == \"bool\":\n            if op == \"MAX\":\n                return (max(alo, blo), max(ahi, bhi))\n            if op == \"XOR\":\n                if alo == ahi and blo == bhi:\n                    return (alo ^ blo, alo ^ blo)\n                return (0, 1)\n            return (0, 1)\n        if op == \"ADD\":\n            return clampb(alo + blo, ahi + bhi)\n        if op == \"MUL\":\n            c = (alo * blo, alo * bhi, ahi * blo, ahi * bhi)\n            return clampb(min(c), max(c))\n        if op == \"MAX\":\n            return (max(alo, blo), max(ahi, bhi))\n        if op == \"XOR\":\n            if alo >= 0 and blo >= 0:\n                return (0, (1 << max(ahi, bhi).bit_length()) - 1)\n            return FULL\n        if op == \"SHL\":\n            if blo < 0 or bhi > 31:\n                return FULL\n            c = (alo << blo, alo << bhi, ahi << blo, ahi << bhi)\n            return clampb(min(c), max(c))\n        if op == \"DIV\":\n            if blo <= 0 <= bhi:\n                return FULL\n            if alo == I32_MIN and blo <= -1 <= bhi:\n                return FULL\n            c = (fdiv(alo, blo), fdiv(alo, bhi), fdiv(ahi, blo), fdiv(ahi, bhi))\n            return clampb(min(c), max(c))\n        if op == \"MOD\":\n            if blo > 0:\n                if alo >= 0 and ahi < blo:\n                    return (alo, ahi)\n                if blo == bhi and alo // blo == ahi // blo:\n                    return (alo % blo, ahi % blo)\n                return (0, bhi - 1)\n            if bhi < 0:\n                return (blo + 1, 0)\n            return FULL\n        return FULL\n\n    # ------------------------------------------------------------------ the public UOp class\n    _cache = {}\n\n    class UOp:\n        \"\"\"Hash-consed, immutable UOp(op, src, arg). See the lab description for the API.\"\"\"\n        __slots__ = (\"op\", \"src\", \"arg\", \"dtype\", \"shape\", \"_bounds\", \"_free\")\n\n        def __new__(cls, op, src=(), arg=None):\n            if not isinstance(op, str):\n                raise TypeError(\"op must be a string such as 'ADD'\")\n            op = op.upper()\n            if op not in OPS:\n                raise ValueError(f\"unknown op {op!r}\")\n            src = tuple(src)\n            for s in src:\n                if type(s) is not UOp:\n                    raise TypeError(f\"every src must be a UOp, got {type(s).__name__}\")\n            arg, akey = norm_arg(op, arg)\n            key = (op, tuple(id(s) for s in src), akey)\n            hit = _cache.get(key)\n            if hit is not None:\n                return hit\n            infos = [(s.dtype, s.shape) for s in src]\n            if op == \"CALL\":\n                if len(src) < 1:\n                    raise ValueError(\"CALL needs a body\")\n                b = src[0]\n                dtype, shape = call_check(b.dtype, b.shape, b._free, infos[1:])\n                free = frozenset().union(*[s._free for s in src[1:]]) if len(src) > 1 else frozenset()\n            else:\n                dtype, shape = infer(op, arg, infos)\n                if op == \"PARAM\":\n                    free = frozenset((arg,))\n                else:\n                    free = frozenset().union(*[s._free for s in src]) if src else frozenset()\n            bnd = bounds_of(op, arg, dtype, [s._bounds for s in src], [s.dtype for s in src])\n            self = object.__new__(cls)\n            for k, v in ((\"op\", op), (\"src\", src), (\"arg\", arg), (\"dtype\", dtype), (\"shape\", shape),\n                         (\"_bounds\", bnd), (\"_free\", free)):\n                object.__setattr__(self, k, v)\n            _cache[key] = self\n            return self\n\n        def __setattr__(self, k, v):\n            raise AttributeError(\"UOps are immutable; build a new one\")\n\n        def __delattr__(self, k):\n            raise AttributeError(\"UOps are immutable\")\n\n        @property\n        def bounds(self):\n            return self._bounds\n\n        @property\n        def params(self):\n            \"\"\"The PARAM args (slot, dtype, lo, hi) this value depends on, not looking inside CALL bodies.\"\"\"\n            return self._free\n\n        @staticmethod\n        def const(value, dtype=None):\n            if dtype is not None:\n                dtype = norm_dtype(dtype)\n                value = bool(value) if dtype == \"bool\" else int(value) if dtype == \"i32\" else \\\n                    float(np.float32(value))\n            return UOp(\"CONST\", (), value)\n\n        @staticmethod\n        def param(slot, dtype, lo=None, hi=None):\n            return UOp(\"PARAM\", (), (slot, dtype, lo, hi))\n\n        def toposort(self):\n            out, seen, stack = [], set(), [(self, False)]\n            while stack:\n                n, done = stack.pop()\n                if done:\n                    out.append(n)\n                    continue\n                if id(n) in seen:\n                    continue\n                seen.add(id(n))\n                stack.append((n, True))\n                for s in reversed(n.src):\n                    if id(s) not in seen:\n                        stack.append((s, False))\n            return out\n\n        def size(self):\n            return len(self.toposort())\n\n        def evaluate(self, inputs=None):\n            nodes, root = ingest(self)\n            info = check(nodes)\n            env = {}\n            for (slot, dt, lo, hi) in info[root][2]:\n                if inputs is None or slot not in inputs:\n                    raise ValueError(f\"evaluate needs inputs[{slot}] for PARAM slot {slot}\")\n                env[slot] = to_array(dt, [inputs[slot]])\n            v = evaluate(nodes, info, root, env, 1)\n            if v.ndim == 2:\n                return [py_value(info[root][0], x[0]) for x in v]\n            return py_value(info[root][0], v[0])\n\n        def render(self):\n            names, lines = {}, []\n            for n in self.toposort():\n                name = f\"%{len(names)}\"\n                names[id(n)] = name\n                a = [names[id(s)] for s in n.src]\n                if n.op == \"CONST\":\n                    v = n.arg\n                    txt = (\"true\" if v else \"false\") if type(v) is bool else repr(v)\n                    lines.append(f\"{name} = const {txt} : dtype={n.dtype}\")\n                elif n.op == \"PARAM\":\n                    slot, dt, lo, hi = n.arg\n                    extra = f\" min={lo} max={hi}\" if lo is not None else \"\"\n                    lines.append(f\"{name} = param [] : dtype={dt} slot={slot}{extra}\")\n                elif n.op == \"CAST\":\n                    lines.append(f\"{name} = cast {a[0]} : dtype={n.arg}\")\n                elif n.op == \"SHRINK\":\n                    lines.append(f\"{name} = shrink {a[0]} {a[1]} {n.arg}\")\n                else:\n                    lines.append(f\"{name} = {n.op.lower()} \" + \" \".join(a))\n            return \"\\n\".join(lines)\n\n        def __repr__(self):\n            if self.op == \"CONST\":\n                return f\"UOp.const({self.arg!r})\"\n            if self.op == \"PARAM\":\n                return f\"UOp.param{self.arg!r}\"\n            return f\"UOp({self.op!r}, <{len(self.src)} srcs>, {self.arg!r}) : {self.dtype}{list(self.shape) or ''}\"\n\n    _OP, _SRC, _ARG = UOp.__dict__[\"op\"], UOp.__dict__[\"src\"], UOp.__dict__[\"arg\"]\n\n    # ------------------------------------------------------------------ grading: ingest, check, evaluate\n    class Invalid(Exception):\n        pass\n\n    def ingest(root):\n        \"\"\"Walk a graph of UOp objects reading raw slots, re-intern structurally. Returns (nodes, root_idx);\n        nodes[i] = (op, srcs(tuple of idx), arg) in topological order.\"\"\"\n        if type(root) is not UOp:\n            raise Invalid(f\"optimize must return a UOp, not {type(root).__name__}\")\n        index, nodes, intern = {}, [], {}\n        stack = [(root, False)]\n        visited = 0\n        while stack:\n            obj, done = stack.pop()\n            oid = id(obj)\n            if done:\n                if oid in index:\n                    continue\n                op, src, arg = _OP.__get__(obj, UOp), _SRC.__get__(obj, UOp), _ARG.__get__(obj, UOp)\n                try:\n                    arg, akey = norm_arg(op, arg)\n                except ValueError as e:\n                    raise Invalid(str(e))\n                key = (op, tuple(index[id(s)] for s in src), akey)\n                if key not in intern:\n                    intern[key] = len(nodes)\n                    nodes.append((op, key[1], arg))\n                index[oid] = intern[key]\n                continue\n            if oid in index:\n                continue\n            visited += 1\n            if visited > MAX_NODES:\n                raise Invalid(f\"the program has more than {MAX_NODES} nodes\")\n            if type(obj) is not UOp:\n                raise Invalid(f\"a src is a {type(obj).__name__}, not a UOp\")\n            op, src = _OP.__get__(obj, UOp), _SRC.__get__(obj, UOp)\n            if not isinstance(op, str) or op not in OPS:\n                raise Invalid(f\"unknown op {op!r}\")\n            if type(src) is not tuple:\n                raise Invalid(\"src must be a tuple\")\n            stack.append((obj, True))\n            for s in reversed(src):\n                if type(s) is not UOp:\n                    raise Invalid(f\"a src is a {type(s).__name__}, not a UOp\")\n                if id(s) not in index:\n                    stack.append((s, False))\n        return nodes, index[id(root)]\n\n    def check(nodes):\n        \"\"\"Per node: (dtype, shape, free params). Raises Invalid.\"\"\"\n        info = []\n        for op, srcs, arg in nodes:\n            si = [info[s] for s in srcs]\n            try:\n                if op == \"CALL\":\n                    if not srcs:\n                        raise ValueError(\"CALL needs a body\")\n                    dt, sh = call_check(si[0][0], si[0][1], si[0][2], [(x[0], x[1]) for x in si[1:]])\n                    free = frozenset().union(*[x[2] for x in si[1:]]) if len(si) > 1 else frozenset()\n                else:\n                    dt, sh = infer(op, arg, [(x[0], x[1]) for x in si])\n                    free = frozenset((arg,)) if op == \"PARAM\" else \\\n                        (frozenset().union(*[x[2] for x in si]) if si else frozenset())\n            except ValueError as e:\n                raise Invalid(f\"{op}: {e}\")\n            info.append((dt, sh, free))\n        return info\n\n    def wrap(x):\n        return (x + 2147483648) % 4294967296 - 2147483648\n\n    def to_array(dt, vals):\n        if dt == \"i32\":\n            return np.array([int(v) for v in vals], dtype=np.int64)\n        if dt == \"f32\":\n            return np.array([float(v) for v in vals], dtype=np.float64).astype(np.float32)\n        return np.array([bool(v) for v in vals], dtype=bool)\n\n    def py_value(dt, x):\n        return int(x) if dt == \"i32\" else bool(x) if dt == \"bool\" else float(x)\n\n    def evaluate(nodes, info, root, env, N, depth=0, reach_cache=None):\n        if depth > MAX_CALL_DEPTH:\n            raise Invalid(\"CALLs are nested too deeply\")\n        if reach_cache is None:\n            reach_cache = {}\n        key = root\n        order = reach_cache.get(key)\n        if order is None:\n            seen, order, stack = set(), [], [(root, False)]\n            while stack:\n                i, done = stack.pop()\n                if done:\n                    order.append(i)\n                    continue\n                if i in seen:\n                    continue\n                seen.add(i)\n                stack.append((i, True))\n                op, srcs, _ = nodes[i]\n                for s in (srcs[1:] if op == \"CALL\" else srcs):\n                    if s not in seen:\n                        stack.append((s, False))\n            reach_cache[key] = order\n        val = {}\n        with np.errstate(all=\"ignore\"):\n            for i in order:\n                op, srcs, arg = nodes[i]\n                dt = info[i][0]\n                v = [val[s] for s in (srcs[1:] if op == \"CALL\" else srcs)]\n                if op == \"CONST\":\n                    r = np.full(N, np.float32(arg), dtype=np.float32) if dt == \"f32\" else \\\n                        np.full(N, arg, dtype=np.int64 if dt == \"i32\" else bool)\n                elif op == \"PARAM\":\n                    slot, pdt, lo, hi = arg\n                    if slot not in env:\n                        raise Invalid(f\"PARAM slot {slot} has no value here\")\n                    r = env[slot]\n                    if lo is not None and (r.min() < lo or r.max() > hi):\n                        raise Invalid(f\"a value outside the declared bounds [{lo}, {hi}] reaches PARAM slot {slot}\")\n                elif op == \"CALL\":\n                    body = srcs[0]\n                    benv = {}\n                    for (slot, pdt, lo, hi) in info[body][2]:\n                        benv[slot] = v[slot]\n                    r = evaluate(nodes, info, body, benv, N, depth + 1, reach_cache)\n                elif op == \"STACK\":\n                    r = np.stack(v)\n                elif op == \"INDEX\":\n                    x, ix = v\n                    if ix.min() < 0 or ix.max() >= x.shape[0]:\n                        raise Invalid(\"INDEX out of range\")\n                    r = x[ix, np.arange(N)]\n                elif op == \"SHRINK\":\n                    x, off = v\n                    if off.min() < 0 or off.max() + arg > x.shape[0]:\n                        raise Invalid(\"SHRINK window out of range\")\n                    rows = off[None, :] + np.arange(arg)[:, None]\n                    r = x[rows, np.arange(N)[None, :]]\n                elif op == \"CAST\":\n                    x, sd = v[0], info[srcs[0]][0]\n                    if dt == sd:\n                        r = x\n                    elif dt == \"f32\":\n                        r = x.astype(np.float32)\n                    elif dt == \"bool\":\n                        r = x != 0\n                    elif sd == \"bool\":\n                        r = x.astype(np.int64)\n                    else:\n                        t = np.trunc(x.astype(np.float64))\n                        if np.isnan(t).any() or t.min() < I32_MIN or t.max() > I32_MAX:\n                            raise Invalid(\"CAST f32 -> i32 of NaN or of a value outside the i32 range\")\n                        r = t.astype(np.int64)\n                elif op == \"RECIP\":\n                    r = (np.float32(1.0) / v[0]).astype(np.float32)\n                elif op == \"TRUNC\":\n                    r = np.trunc(v[0]).astype(np.float32)\n                elif op == \"WHERE\":\n                    r = np.where(v[0], v[1], v[2])\n                else:\n                    a, b = v\n                    if dt == \"bool\" and op != \"CMPLT\":\n                        r = (a | b) if op == \"MAX\" else (a ^ b)\n                    elif op == \"CMPLT\":\n                        r = (~a & b) if info[srcs[0]][0] == \"bool\" else (a < b)\n                    elif op == \"ADD\":\n                        r = wrap(a + b) if dt == \"i32\" else (a + b).astype(np.float32)\n                    elif op == \"MUL\":\n                        r = wrap(a * b) if dt == \"i32\" else (a * b).astype(np.float32)\n                    elif op == \"MAX\":\n                        if dt == \"i32\":\n                            r = np.maximum(a, b)\n                        else:\n                            r = np.maximum(a, b).astype(np.float32)\n                            z = (a == 0) & (b == 0)\n                            if z.any():\n                                both_neg = np.signbit(a) & np.signbit(b)\n                                r = np.where(z, np.where(both_neg, np.float32(-0.0), np.float32(0.0)), r).astype(np.float32)\n                    elif op == \"XOR\":\n                        r = a ^ b\n                    elif op == \"SHL\":\n                        if b.min() < 0 or b.max() > 31:\n                            raise Invalid(\"SHL amount outside 0..31\")\n                        r = wrap(a * np.left_shift(np.int64(1), b))\n                    elif op == \"DIV\":\n                        if (b == 0).any():\n                            raise Invalid(\"DIV by zero\")\n                        r = wrap(np.floor_divide(a, b))\n                    elif op == \"MOD\":\n                        if (b == 0).any():\n                            raise Invalid(\"MOD by zero\")\n                        r = np.mod(a, b)\n                    else:\n                        raise Invalid(f\"cannot evaluate {op}\")\n                val[i] = r\n        return val[root]\n\n    def same(dt, a, b):\n        if a.shape != b.shape:\n            return np.zeros(a.shape[-1], bool)\n        if dt == \"f32\":\n            ok = (a.view(np.uint32) == b.view(np.uint32)) | (np.isnan(a) & np.isnan(b))\n        else:\n            ok = a == b\n        return ok if ok.ndim == 1 else ok.all(axis=0)\n\n    return {\"UOp\": UOp, \"Invalid\": Invalid, \"ingest\": ingest, \"check\": check, \"evaluate\": evaluate,\n            \"same\": same, \"py_value\": py_value, \"to_array\": to_array}\n\n\nUOp = _dml_uop_lib()[\"UOp\"]\nimport math\nx = UOp.param(0, \"f32\")\nr = optimize(UOp(\"ADD\", (x, UOp.const(0.0))))\nprint(math.copysign(1.0, r.evaluate({0: -0.0})) == 1.0 and r.evaluate({0: 2.5}) == 2.5)","expected_output":"True"}],"approved_user_libraries":["numpy","math","collections","itertools","functools","random"],"lower_is_better":false,"data_info":"Synthetic programs generated inside the grader. Run: 29 programs from a fixed seed (index arithmetic, constant-heavy, redundant-layer and CALL-based programs). Submit: 120 programs drawn from a fresh random seed on every submit, including two kinds Run does not show. Inputs for checking are generated per program and always include edge values.","time_limits":{"test":240,"dev":120},"example":{"input":"root = UOp('ADD', (UOp('MUL', (UOp.param(0, 'i32', 0, 15), UOp.const(1))), UOp('ADD', (UOp.const(2), UOp.const(3)))))   # 7 unique nodes","output":"a UOp equal to root on every input, e.g. ADD(PARAM 0, CONST 5): 3 nodes, so ratio 3/7 for this program; the score is 100 * (1 - mean ratio) over all programs"},"gpu":false,"description":"Week 1 of a compiler course: your compiler holds a program as a graph of UOps and rewrites it. Write `optimize(root)` that returns a program computing **exactly** the same value as `root` for every input the program can receive, using as few nodes as you can. The leaderboard ranks by **percent of nodes removed, higher is better**.\n\n**Contract.** Define `optimize(root)`. It is called once per program with the program's root UOp and must return a UOp. The grader provides the class `UOp` before calling `optimize`; use it inside your functions, and do not define a module-level name `UOp` yourself.\n\n**The UOp.** `UOp(op, src, arg)` is immutable and hash-consed: building the same op with the same srcs and arg twice gives the same object, so a program is a DAG and an identical subexpression is one node.\n\n- `UOp(op, src=(), arg=None)` builds a node (op names are upper case, lower case is accepted). An invalid node raises `ValueError`.\n- `UOp.const(value, dtype=None)` and `UOp.param(slot, dtype, lo=None, hi=None)` are shortcuts.\n- `.op`, `.src` (a tuple of UOps), `.arg`, `.dtype` (`\"i32\"`, `\"f32\"` or `\"bool\"`), `.shape` (`()` or `(n,)`).\n- `.bounds`: an interval `(lo, hi)` proven to contain the value, for i32 and bool values (`None` for f32).\n- `.params`: the PARAM args `(slot, dtype, lo, hi)` the value depends on, not looking inside CALL bodies.\n- `.toposort()`, `.size()` (the node count the score uses), `.evaluate(inputs)` (the exact value; `inputs` maps slot to value) and `.render()` (the program as `.uir` text).\n\n**Ops and their exact meaning.**\n\n- `CONST`: arg is a Python `bool`, `int` (i32) or `float` (f32, exactly representable).\n- `PARAM`: arg is `(slot, dtype, lo, hi)`; `lo`/`hi` are `None` when unbounded. An i32 PARAM with bounds only ever receives values in `[lo, hi]`.\n- `CALL`: `src[0]` is a function body and `src[1:]` its arguments; the body's PARAM with slot `i` takes argument `i`. A CALL binds the PARAMs of its own body only, not those inside nested CALL bodies, and every argument must stay inside the bounds its PARAM declares.\n- `STACK s0 ... s(n-1)` makes a length-n vector of scalars, `INDEX(x, i)` reads element `i`, and `SHRINK(x, offset)` with arg `size` is the window `x[offset:offset+size]`. Indices and windows must stay in range.\n- i32 is 32-bit two's complement: `ADD`, `MUL` and `SHL` wrap modulo 2^32 (`SHL` amounts are 0..31). `DIV` and `MOD` are floor division and floor modulo, as Python's `//` and `%`; dividing by zero is invalid. `XOR` and `MAX` work as usual.\n- f32 is IEEE-754 single precision, rounded after every op. `RECIP` is `1/x` and `TRUNC` rounds toward zero. `MAX` is NaN if either input is NaN, and treats +0.0 as larger than -0.0.\n- On bool, `XOR` is logical xor and `MAX` is or. `CMPLT(a, b)` is `a < b` (on bool: not a and b). `WHERE(c, a, b)` picks `a` when `c` is true.\n- `CAST` to i32 from f32 truncates toward zero (NaN or out of range is invalid); to f32 from i32 rounds to nearest-even; from bool gives 0/1; to bool is `!= 0`.\n\n**The programs.** Each program is a scalar i32, f32 or bool value of a few inputs, from a few dozen to a few hundred nodes. Run shows 29 programs of four kinds: index arithmetic of the kind that lowering movement ops produces, constant-heavy expressions, expressions wrapped in redundant layers, and programs built from CALLed functions. Submit draws **120 fresh programs every time you submit** (the corpus seed is printed), including two kinds Run does not show.\n\n**Exactly the same.** Your result may use any ops, but may read only the program's own inputs (the same PARAM args). It is checked against the original on every input combination when the inputs' ranges are small, and otherwise on hundreds of inputs that always include each input's edge values: bounds endpoints, 0, ±1, the i32 extremes, ±0.0, ±inf, NaN and subnormals. Results must match bit for bit (any NaN matches any NaN). Any difference, invalid node, wrong dtype or new input sets the score to 0.\n\n**Score.** For each program, `ratio = min(nodes_after / nodes_before, 2)`, counting the unique nodes reachable from the root, CALL bodies included. The score is `100 * (1 - mean ratio)`. Returning the program unchanged scores 0. A score of at least **22** counts as solved; everything above that is leaderboard. Run also prints your two weakest programs before and after.\n\n**Budget and rules.** Total time inside `optimize` is capped at 40 s on Run and 90 s on Submit. Your code may import only `numpy`, `math`, `collections`, `itertools`, `functools`, `heapq`, `bisect`, `random`, `dataclasses`, `struct` and `fractions`, and may use an imported module only as `module.name`.\n\n**Gates.** The score is set to 0 and the run fails if any of these happen:\n- `optimize` raises or exits, or the time budget runs out.\n- A result is not a UOp, differs from the original on any checked input, or reads an input the program does not have.\n- Your code reads files, uses introspection (`globals`, `vars`, `getattr`/`setattr`, frames, tracebacks, `eval`/`exec`), defines `__del__` or `__new__`, or assigns to, aliases or reaches into the internals of an imported module.","tags":["compilers","uops","term-rewriting","symbolic-simplification","constant-folding","ml-compilers","open-ended","leaderboard"],"id":"8648a028-571b-4a78-89a7-3eb04f29963f","dataset_id":"synthetic","img_type":"full","difficulty":"hard","evaluation_metric":"pct_nodes_removed","min_eval_metric":22.0,"category":"Compilers","title":"Best Graph Optimizer","dataset":"Synthetic UOp programs (index arithmetic, constant folding, redundant layers, CALLs, bit tricks, tables)","time_limits_seconds":{"dev":120,"test":240}},{"created_at":"2026-10-28T19:09:48.806000+00:00","type":"general","test_cases":[{"test":"import numpy as np\n_r = np.random.default_rng(3)\n_Xa = (_r.random((800, 784)) < 0.15).astype(np.uint8)\n_Xb = (_r.random((5, 784)) < 0.15).astype(np.uint8)\n_m = train(_Xa)\n_ok_shape, _ok_range = True, True\nfor _d in range(784):\n    _p = np.asarray(cond_prob(_m, _Xb[:, :_d].copy()), dtype=float)\n    _ok_shape &= _p.shape == (5,)\n    _ok_range &= bool(np.all(np.isfinite(_p)) and np.all((_p >= 0) & (_p <= 1)))\nprint(_ok_shape, _ok_range)","expected_output":"True True"},{"test":"import numpy as np\n_r = np.random.default_rng(4)\n_rows = (_r.random((800, 28)) < 0.3).astype(np.uint8)\n_Xa = np.repeat(_rows, 28, axis=1)\n_m = train(_Xa)\n_Xb = np.zeros((2, 784), np.uint8)\n_Xb[0, :28] = 1\nfor _d in range(6):\n    _p = np.asarray(cond_prob(_m, _Xb[:, :_d].copy()), dtype=float)\nprint(\"pixel 5 follows its row:\", bool(_p[0] > 0.5 and _p[1] < 0.25))","expected_output":"pixel 5 follows its row: True"},{"test":"import numpy as np\n_r = np.random.default_rng(5)\n_Xa = (_r.random((800, 784)) < 0.15).astype(np.uint8)\n_Xb = (_r.random((4, 784)) < 0.15).astype(np.uint8)\n_m = train(_Xa)\n_runs = []\nfor _rep in range(2):\n    _runs.append(np.stack([np.asarray(cond_prob(_m, _Xb[:, :_d].copy()), dtype=float) for _d in range(784)], 1))\nprint(\"same probabilities on a second pass:\", bool(np.allclose(_runs[0], _runs[1], atol=1e-9)))","expected_output":"same probabilities on a second pass: True"}],"lower_is_better":true,"approved_user_libraries":["numpy","scipy","sklearn","torch","math","time","random","collections","itertools","functools","copy"],"data_info":"MNIST (dml_data id mnist), binarized at gray level > 127, flattened row by row to 784 pixels. Run: 5,000 training-split images to train on (permutation seed 42) and the next 1,000 training-split images to score. Submit: 10,000 training-split images (permutation seed 123) to train on and 2,000 test-split images to score. The grader reveals test pixels one prefix at a time through cond_prob.","time_limits":{"test":300,"dev":150},"example":{"input":"train(X_train uint8 (10000, 784)) once; then cond_prob(model, X_test[:, :d]) for d = 0..783","output":"p of shape (2000,) per call; Submit bits per pixel about 0.375 for independent pixels, 0.28 for a 20-component Bernoulli mixture"},"gpu":false,"description":"Build a probability model of handwritten digits and make it as unsurprised as possible by digits it has never seen. The book scores unsupervised models by the negative log-likelihood of held-out data, and fits a Bernoulli mixture to binarized MNIST. Here the held-out log-likelihood is computed **exactly** by the grader, and it is your leaderboard score.\n\n## The data\n\nMNIST digits, 28 x 28, binarized: a pixel is 1 when its gray level is above 127 (half of 255), else 0. Each image is flattened row by row into 784 pixels, so pixel `d` sits at row `d // 28`, column `d % 28`. You get the training images; the test images never leave the grader.\n\n## Your functions\n\n```python\ndef train(X_train):\n    ...\n    return model                 # any Python object\n\ndef cond_prob(model, X_prefix):\n    ...\n    return p                     # numpy array, shape (n,)\n```\n\n- `X_train`: uint8 array of shape `(N, 784)` with 0/1 pixels.\n- `X_prefix`: uint8 array of shape `(n, d)` holding pixels `0 .. d-1` of `n` test images. Return `p[i]` = your probability that pixel `d` of image `i` is 1, given those first `d` pixels.\n\nThe grader calls `cond_prob` 784 times, for `d = 0, 1, ..., 783` in that order, always on the same `n` test images and always with the same `model` object, so you may keep state on the model between calls. A call never sees pixel `d` or anything after it. By the chain rule the 784 answers multiply into a full, normalized probability of each test image, which is why any model you like (a mixture, an autoregressive model, a hand-built context model, a neural network) is scored on the same footing.\n\nApproved libraries: numpy, scipy, scikit-learn, torch (CPU), and small standard-library helpers (math, time, random, collections, itertools, functools, copy). Your code may not open files, load datasets or reach the network, and is limited to 30,000 characters.\n\n## Score (lower is better)\n\nWith `p` clipped to `[1e-6, 1 - 1e-6]`,\n\n$$\\text{bits per pixel} = -\\frac{1}{784\\,n} \\sum_{i=1}^{n} \\sum_{d=0}^{783} \\log_2 p\\left(x_{i,d} \\mid x_{i,0}, \\ldots, x_{i,d-1}\\right)$$\n\nwhich is the exact held-out negative log-likelihood in bits, divided by the number of pixels. **Run** trains on 5,000 images from MNIST's training split and scores 1,000 other training-split images. **Submit** trains on 10,000 training images (a different draw) and scores 2,000 images from MNIST's test split that Run never shows. You pass at **0.35** bits per pixel or lower; below that, lower ranks higher. Treating every pixel as an independent coin scores about 0.375.\n\n## Budgets and gates\n\nBudgets are process CPU time (every thread counts): `train` gets **60 s** on Run and **120 s** on Submit, and the 784 `cond_prob` calls together get **30 s** on Run and **60 s** on Submit. The run fails with a score of 99 if your code imports anything outside the approved set or touches files or datasets, if `train` or `cond_prob` raises, if a budget is exceeded, or if `cond_prob` returns the wrong shape, a NaN or inf, or a value outside [0, 1].\n\nThe report shows your bits per pixel, the same score in nats per image, the independent-pixel baseline on the same data, your bits per pixel on the top, middle and bottom thirds of the image, how many of your probabilities were clipped, and your CPU and wall seconds.","tags":["density-estimation","bernoulli-mixture","autoregressive","chain-rule","mnist","compression","open-ended","leaderboard"],"id":"86da6dad-91de-4017-80fc-adaa7f292d77","img_type":"full","dataset_id":"mnist","evaluation_metric":"bits_per_pixel","difficulty":"medium","min_eval_metric":0.35,"category":"Machine Learning","title":"Fewest Bits per Pixel on Binarized Digits","dataset":"MNIST (binarized)","time_limits_seconds":{"dev":150,"test":300}},{"created_at":"2026-11-05T02:11:07.369000+00:00","type":"general","constraints":["estimate(pts1, pts2) returns a finite 3x3 homography; a fresh process per task","1.5 s of CPU per task counting all threads and child processes, 5 s wall; over budget scores 30 px","module level and class bodies hold only imports, constants, and function and class definitions; no calls there","numpy, scipy, math, itertools, collections, heapq, bisect, random, statistics, time, warnings, typing, copy only; attributes may be assigned only on self, inside a method defined in a class body","source capped at 30000 characters, 600 numeric literals, 2000 characters of string constants"],"test_cases":[{"test":"import numpy as np\n_tc_rng = np.random.default_rng(5)\n_tc_H = np.array([[1.02, 0.05, 30.0], [-0.03, 0.98, -12.0], [2e-5, -1e-5, 1.0]])\ndef _tc_map(M, p):\n    q = np.c_[p, np.ones(len(p))] @ np.asarray(M, dtype=float).T\n    return q[:, :2] / q[:, 2:3]\n_tc_X = _tc_rng.uniform(0, 640, (120, 2))\n_tc_Y = _tc_map(_tc_H, _tc_X)\ndef _tc_err(M):\n    return float(np.sqrt(((_tc_map(M, _tc_X) - _tc_Y) ** 2).sum(1).mean()))\ndef _tc_corrupt(share, noise):\n    a = _tc_X + noise * 0.7 * _tc_rng.normal(size=_tc_X.shape)\n    b = _tc_Y + noise * _tc_rng.normal(size=_tc_Y.shape)\n    k = int(share * len(a))\n    b[:k] = _tc_rng.uniform(0, 640, (k, 2))\n    return a, b\nprint(np.asarray(estimate(_tc_X.copy(), _tc_Y.copy())).shape)","expected_output":"(3, 3)"},{"test":"import numpy as np\n_tc_rng = np.random.default_rng(5)\n_tc_H = np.array([[1.02, 0.05, 30.0], [-0.03, 0.98, -12.0], [2e-5, -1e-5, 1.0]])\ndef _tc_map(M, p):\n    q = np.c_[p, np.ones(len(p))] @ np.asarray(M, dtype=float).T\n    return q[:, :2] / q[:, 2:3]\n_tc_X = _tc_rng.uniform(0, 640, (120, 2))\n_tc_Y = _tc_map(_tc_H, _tc_X)\ndef _tc_err(M):\n    return float(np.sqrt(((_tc_map(M, _tc_X) - _tc_Y) ** 2).sum(1).mean()))\ndef _tc_corrupt(share, noise):\n    a = _tc_X + noise * 0.7 * _tc_rng.normal(size=_tc_X.shape)\n    b = _tc_Y + noise * _tc_rng.normal(size=_tc_Y.shape)\n    k = int(share * len(a))\n    b[:k] = _tc_rng.uniform(0, 640, (k, 2))\n    return a, b\nprint(_tc_err(estimate(_tc_X.copy(), _tc_Y.copy())) < 0.01)","expected_output":"True"},{"test":"import numpy as np\n_tc_rng = np.random.default_rng(5)\n_tc_H = np.array([[1.02, 0.05, 30.0], [-0.03, 0.98, -12.0], [2e-5, -1e-5, 1.0]])\ndef _tc_map(M, p):\n    q = np.c_[p, np.ones(len(p))] @ np.asarray(M, dtype=float).T\n    return q[:, :2] / q[:, 2:3]\n_tc_X = _tc_rng.uniform(0, 640, (120, 2))\n_tc_Y = _tc_map(_tc_H, _tc_X)\ndef _tc_err(M):\n    return float(np.sqrt(((_tc_map(M, _tc_X) - _tc_Y) ** 2).sum(1).mean()))\ndef _tc_corrupt(share, noise):\n    a = _tc_X + noise * 0.7 * _tc_rng.normal(size=_tc_X.shape)\n    b = _tc_Y + noise * _tc_rng.normal(size=_tc_Y.shape)\n    k = int(share * len(a))\n    b[:k] = _tc_rng.uniform(0, 640, (k, 2))\n    return a, b\n_a, _b = _tc_corrupt(0.3, 0.0)\nprint(_tc_err(estimate(_a, _b)) < 0.5)","expected_output":"True"},{"test":"import numpy as np\n_tc_rng = np.random.default_rng(5)\n_tc_H = np.array([[1.02, 0.05, 30.0], [-0.03, 0.98, -12.0], [2e-5, -1e-5, 1.0]])\ndef _tc_map(M, p):\n    q = np.c_[p, np.ones(len(p))] @ np.asarray(M, dtype=float).T\n    return q[:, :2] / q[:, 2:3]\n_tc_X = _tc_rng.uniform(0, 640, (120, 2))\n_tc_Y = _tc_map(_tc_H, _tc_X)\ndef _tc_err(M):\n    return float(np.sqrt(((_tc_map(M, _tc_X) - _tc_Y) ** 2).sum(1).mean()))\ndef _tc_corrupt(share, noise):\n    a = _tc_X + noise * 0.7 * _tc_rng.normal(size=_tc_X.shape)\n    b = _tc_Y + noise * _tc_rng.normal(size=_tc_Y.shape)\n    k = int(share * len(a))\n    b[:k] = _tc_rng.uniform(0, 640, (k, 2))\n    return a, b\n_a, _b = _tc_corrupt(0.6, 1.0)\nprint(_tc_err(estimate(_a, _b)) < 1.0)","expected_output":"True"}],"lower_is_better":true,"approved_user_libraries":["numpy","scipy"],"data_info":"There is no dataset to read: the grader generates every task in a separate process, and your code receives only the two point arrays.\n\nEach task is one image pair. Images are 640 to 1280 pixels wide. The true homography comes from moving the four image corners by random amounts, then rotating, scaling and shifting the result, so the second view is a believable but sometimes strong change of viewpoint. Each task has 40 to 2,000 correspondences in random order.\n\n- **True inliers**: the image-1 positions of the inliers are mapped through the true homography, and both images then get random noise, Gaussian in the kinds of scene Run uses. The noise level is hidden. Its base value is between 0.3 and 4 pixels in image 2 (about 0.7 times that in image 1), and it differs from point to point, as it would for features found at different scales.\n- **Outliers**: random pairs of points anywhere in the two images, and near misses, which land a few to tens of pixels from where the inlier would be.\n\nRun uses 16 tasks, 8 from each of these 2 kinds of scene, with outlier shares from 15% to 75%:\n1. Inliers spread over the whole image\n2. Inliers in a few clusters\n\nSubmit uses 36 tasks with new seeds: 12 from these two kinds, and 24 from 6 more that are not listed here. Across Submit, outlier shares run from 15% to 90%.","time_limits":{"test":300,"dev":180},"gpu":false,"description":"## Most Accurate Homography Under Outliers\n\nTwo photos of the same flat surface are related by a homography: a 3x3 matrix $H$ that sends every point of the first image to its match in the second. A feature matcher gives you a list of correspondences, and many of them are wrong. Your job is to recover $H$ as precisely as you can from those matches alone. You are never told which matches are right, how noisy the right ones are, or what share of the list is wrong.\n\n### What you write\n\n```python\ndef estimate(pts1, pts2):\n    # pts1, pts2: float64 arrays of shape (N, 2), pixel coordinates (x, y)\n    # row i of pts1 was matched to row i of pts2\n    ...\n    return H        # 3x3 array: pts2 ~ H @ [x, y, 1], at any overall scale\n```\n\n`estimate` runs once per task, each time in a fresh process, so nothing carries over from one task to the next.\n\n### How it is graded\n\nEach task has a hidden true homography $H^*$ and a hidden set of true inliers, the matches that really are the same surface point seen twice. For each true inlier the grader takes its exact position $x_i$ in image 1, before any noise was added, and measures how far your homography sends it from where $H^*$ sends it:\n\n$$\ne = \\sqrt{ \\frac{1}{|I|} \\sum_{i \\in I} \\left\\| \\pi(H x_i) - \\pi(H^* x_i) \\right\\|^2 }\n$$\n\nHere $\\pi$ divides by the third coordinate, and the error is in pixels of image 2. Each task's $e$ is clipped to [0.01, 30] pixels. Your score is the **geometric mean** of the clipped errors over all tasks, so halving the error on any one task helps as much as halving it on any other. **Lower is better**, and the lab is passed at **1.00 pixels or below**. The score is measured against the true homography, not against the noisy matches, so a fit that chases the noise does not help. For scale: the true homography itself would score 0.01, and a careful fit that is told which matches are inliers and how noisy each one is scores about 0.18 on Run and 0.26 on Submit.\n\n- **Run**: 16 tasks from 2 kinds of scene, listed under Data. Run shows the error, CPU time, noise level and outlier share of every task, plus your printed output.\n- **Submit**: 36 tasks drawn with different seeds: 12 from the kinds of scene Run uses, and 24 from 6 kinds that Run never shows. These include higher outlier shares, noise with heavier tails, wrong matches that agree with each other, and inlier layouts that pin $H$ down poorly. Submit reports your score with two parts, over the kinds of scene Run uses and over the rest, and hides per-task results and your printed output.\n\n### Budgets and rules\n\n- Each task gets **1.5 s of CPU time**, counting every thread and every process your code starts. `time.process_time()` inside `estimate` reads nearly the same clock. A task over budget scores 30 pixels, and so does a task still running after 5 s of wall time.\n- An exception, a result that is not a finite 3x3 array, or a homography that sends a true inlier to infinity scores 30 pixels for that task. Run shows the error message.\n- Libraries: numpy, scipy, math, itertools, collections, heapq, bisect, random, statistics, time, warnings, typing, copy. Everything else, including file access and any dataset, is refused.\n- Write classes as usual: `self.x = ...` works inside a method defined in a class body. Assigning to or deleting an attribute of anything else (`x.y = ...`) is refused, and so are names that reach modules or object internals (`getattr`, `__dict__` and so on).\n- Module level and class bodies may hold only imports from that list, constants, and function and class definitions (`@staticmethod`, `@classmethod` and `@property` work on methods without annotations). Calls, loops and conditions go inside your functions.\n- Your source is capped at 30,000 characters, 600 numeric literals and 2,000 characters of string constants.\n","tags":["computer-vision","homography","ransac","robust-estimation","geometry","competitive"],"id":"8ae972f5-639f-4585-a983-dd8df3f933c5","img_type":"full","dataset_id":"synthetic","evaluation_metric":"gm_transfer_px","difficulty":"hard","min_eval_metric":1.0,"category":"Computer Vision","title":"Most Accurate Homography Under Outliers","dataset":"Point correspondences generated in the grader: hidden homographies, noise and outliers","time_limits_seconds":{"dev":180,"test":300}},{"created_at":"2026-11-01T00:12:37.921000+00:00","type":"general","constraints":["fit + score <= 40 s per graph, CPU","score returns one finite number per pair","numpy, scipy, scikit-learn, torch, lightgbm, xgboost and small standard-library helpers only; the harness owns all data"],"test_cases":[{"test":"import numpy as np\ndef _ring_of_cliques(k, m):\n    e = []\n    for c in range(k):\n        o = c * m\n        e += [(o + i, o + j) for i in range(m) for j in range(i + 1, m)]\n        e.append((o, ((c + 1) % k) * m))\n    return np.array(sorted({(min(a, b), max(a, b)) for a, b in e}), dtype=np.int64).T\n_rng = np.random.default_rng(0)\n_e = _ring_of_cliques(4, 6)\n_X = _rng.normal(size=(24, 8)).astype(np.float32)\n_p = np.array([(0, 13), (5, 20), (7, 8), (1, 2)], dtype=np.int64)\n_s = np.asarray(score(fit(_e, 24, _X), _p), dtype=float)\nprint(_s.shape == (4,), bool(np.all(np.isfinite(_s))))","expected_output":"True True"},{"test":"import numpy as np\ndef _ring_of_cliques(k, m):\n    e = []\n    for c in range(k):\n        o = c * m\n        e += [(o + i, o + j) for i in range(m) for j in range(i + 1, m)]\n        e.append((o, ((c + 1) % k) * m))\n    return np.array(sorted({(min(a, b), max(a, b)) for a, b in e}), dtype=np.int64).T\n_rng = np.random.default_rng(0)\n_n = 120\n_a = np.arange(_n) % 2\n_u, _v = np.triu_indices(_n, 1)\n_keep = (_a[_u] != _a[_v]) & (_rng.random(_u.size) < 0.2)\n_e = np.stack([_u[_keep], _v[_keep]]).astype(np.int64)\n_X = _rng.normal(size=(_n, 8)).astype(np.float32)\n_miss = ~_keep & (_a[_u] != _a[_v])\n_same = _a[_u] == _a[_v]\n_p = np.stack([np.r_[_u[_miss], _u[_same]], np.r_[_v[_miss], _v[_same]]], 1).astype(np.int64)\n_s = np.asarray(score(fit(_e, _n, _X), _p), dtype=float)\nprint(\"across beats within:\", float(np.mean(_s[:int(_miss.sum())])) > float(np.mean(_s[int(_miss.sum()):])))","expected_output":"across beats within: True"},{"test":"import numpy as np\ndef _ring_of_cliques(k, m):\n    e = []\n    for c in range(k):\n        o = c * m\n        e += [(o + i, o + j) for i in range(m) for j in range(i + 1, m)]\n        e.append((o, ((c + 1) % k) * m))\n    return np.array(sorted({(min(a, b), max(a, b)) for a, b in e}), dtype=np.int64).T\n_rng = np.random.default_rng(0)\n_n = 400\n_X = _rng.normal(size=(_n, 6)).astype(np.float32)\n_u, _v = np.triu_indices(_n, 1)\n_same = np.sign(_X[_u, 0]) == np.sign(_X[_v, 0])\n_keep = _same & (_rng.random(_u.size) < 0.004)\n_e = np.stack([_u[_keep], _v[_keep]]).astype(np.int64)\n_rest = ~_keep\n_p = np.stack([_u[_rest], _v[_rest]], 1).astype(np.int64)\n_s = np.asarray(score(fit(_e, _n, _X), _p), dtype=float)\n_a, _b = np.sort(_s[~_same[_rest]]), _s[_same[_rest]]\n_auc = float(np.mean(np.searchsorted(_a, _b, side=\"left\") + np.searchsorted(_a, _b, side=\"right\")) * 0.5 / _a.size)\nprint(\"features help:\", _auc > 0.6)","expected_output":"features help: True"}],"lower_is_better":false,"approved_user_libraries":["numpy","scipy","sklearn","torch","lightgbm","xgboost"],"data_info":"No dataset: the grader generates every graph at run time from a hidden seed. Node ids are randomly permuted and feature columns randomly ordered and standardised on each graph.\n\nGraph sizes: about 1,400 to 1,800 nodes, mean degree 3 to 7, feature dimension 16 to 32, about 2,000 to 5,500 edges of which 10% are hidden.\n\nRun: 6 graphs. Submit: 12 different graphs from different seeds, 4 per family, with variants of each family that Run never shows.","time_limits":{"test":600,"dev":450},"example":{"input":"fit(edge_index (2, M), n_nodes, X (n_nodes, d)); score(model, pairs (K, 2))","output":"K finite numbers, one per pair, higher = more likely a link"},"gpu":false,"description":"## Best Link Predictor on Held-Out Edges\n\nSomeone has hidden 10% of the links of a graph. From what is left, and from the node features, rank the missing links above the pairs that were never linked. Your score is the AUC of that ranking, averaged over graphs whose structure you are not told.\n\nThe graphs come from three families, and each graph is generated fresh by the grader from a hidden seed:\n\n- **Community**: nodes belong to hidden groups, and the pair of groups sets the link rate.\n- **Hierarchical**: nodes sit in a hidden hierarchy (nested groups or a taxonomy), and the link rate falls with distance in it.\n- **Feature-driven**: a hidden function of two nodes' features sets the link rate, and the graph is sparse.\n\nYou are never told which family a graph belongs to. Node features are real signal on some graphs and pure noise on others.\n\n### What you write\n\n```python\ndef fit(edge_index, n_nodes, X):\n    ...\n    return model                 # anything you like\n\ndef score(model, pairs):\n    ...\n    return scores                # np.ndarray of shape (K,), finite, higher = link more likely\n```\n\n- `edge_index`: `int64` array of shape `(2, M)`. Each training edge appears once; the graph is undirected.\n- `n_nodes`: the number of nodes (node ids are `0 ... n_nodes - 1`, in random order).\n- `X`: `float32` array of shape `(n_nodes, d)`, standardised, columns in random order. `d` changes from graph to graph.\n- `pairs`: `int64` array of shape `(K, 2)` holding **every pair of nodes that is not a training edge**, shuffled, with random orientation. On these graphs `K` is about 1 to 1.6 million, so `score` has to be vectorised.\n\n### How it is graded\n\nFor each graph the harness removes 10% of the edges at random, calls `fit` on the rest, calls `score` once, and computes the **ROC AUC of the hidden edges against all pairs that are not edges**. Ties count half. Your score is the **mean AUC over the graphs**, higher is better, and the lab is passed at **0.80 or above**. Run reports the AUC per graph and per family; Submit reports it per family.\n\n- **Run**: 6 graphs from the three families.\n- **Submit**: 12 different graphs, 4 per family, including variants of each family that Run never shows.\n\n### Budgets and rules\n\n- `fit` plus `score` get **40 s per graph** on a CPU, with two threads for numerical libraries.\n- Each graph runs in a fresh process: nothing you compute on one graph carries over to the next.\n- Libraries: numpy, scipy, scikit-learn, torch, lightgbm, xgboost, plus small standard-library helpers (`math`, `random`, `time`, `collections`, `itertools`, `functools`, `heapq` and the like).\n- There is no data to read. Code that imports other modules, opens or loads files, or uses `getattr`, `globals` and similar is refused. Source is limited to 30,000 characters, string constants to 3,000 characters in total, and numeric literals to 600.\n- An exception, a broken budget, a wrong output shape or a non-finite score sets the score to 0 and fails the run.\n","tags":["link-prediction","graph-embeddings","graph-auto-encoder","matrix-factorization","random-walks","hyperbolic-embeddings","pml-book","open-ended","leaderboard"],"id":"8dcb1611-fb44-437a-875e-3418ba313a99","img_type":"full","dataset_id":"synthetic","difficulty":"hard","evaluation_metric":"auc","min_eval_metric":0.8,"category":"Graph Learning","title":"Best Link Predictor on Held-Out Edges","dataset":"Seeded graph generators (community, hierarchical, feature-driven)","time_limits_seconds":{"dev":450,"test":600}},{"created_at":"2026-11-01T02:28:21.635000+00:00","type":"general","constraints":["10 CPU seconds per dataset over all threads and worker processes, 270 s in total on Run and 420 s on Submit","logpdf is called only on the 256 x 256 lattice built from X_train; exp(logpdf) may not sum to more than 1.2 over it","numpy, scipy, sklearn, torch and small standard-library helpers only; attribute stores only on self in a method of a class","source capped at 30000 characters, 800 numeric literals, 3000 characters of string constants"],"test_cases":[{"test":"import numpy as np\n_r = np.random.default_rng(0)\ndef _ring(n):\n    t = _r.uniform(0.0, 2.0 * np.pi, n)\n    rad = 1.0 + 0.04 * _r.normal(size=n)\n    return np.stack([rad * np.cos(t), 0.2 * rad * np.sin(t)], 1)\n_X = _ring(800)\n_m = fit(_X.copy())\n_T = _ring(4000)\n_lq = np.asarray(logpdf(_m, _T), dtype=float)\n_h = 0.5 * np.log(2.0 * np.pi * np.e * 0.04 ** 2) + np.log(2.0 * np.pi) + np.log(0.2)\nprint(_lq.shape)","expected_output":"(4000,)"},{"test":"import numpy as np\n_r = np.random.default_rng(0)\ndef _ring(n):\n    t = _r.uniform(0.0, 2.0 * np.pi, n)\n    rad = 1.0 + 0.04 * _r.normal(size=n)\n    return np.stack([rad * np.cos(t), 0.2 * rad * np.sin(t)], 1)\n_X = _ring(800)\n_m = fit(_X.copy())\n_T = _ring(4000)\n_lq = np.asarray(logpdf(_m, _T), dtype=float)\n_h = 0.5 * np.log(2.0 * np.pi * np.e * 0.04 ** 2) + np.log(2.0 * np.pi) + np.log(0.2)\nprint(bool(np.isfinite(_lq).all()))","expected_output":"True"},{"test":"import numpy as np\n_r = np.random.default_rng(0)\ndef _ring(n):\n    t = _r.uniform(0.0, 2.0 * np.pi, n)\n    rad = 1.0 + 0.04 * _r.normal(size=n)\n    return np.stack([rad * np.cos(t), 0.2 * rad * np.sin(t)], 1)\n_X = _ring(800)\n_m = fit(_X.copy())\n_T = _ring(4000)\n_lq = np.asarray(logpdf(_m, _T), dtype=float)\n_h = 0.5 * np.log(2.0 * np.pi * np.e * 0.04 ** 2) + np.log(2.0 * np.pi) + np.log(0.2)\n_g = (np.arange(200) + 0.5) / 200\n_c = np.stack(np.meshgrid(-1.5 + 3.0 * _g, -0.3 + 0.6 * _g, indexing='ij'), -1).reshape(-1, 2)\n_v = np.concatenate([np.asarray(logpdf(_m, _c[s:s + 4096]), dtype=float) for s in range(0, len(_c), 4096)])\nprint(bool(np.exp(_v).sum() * (3.0 / 200) * (0.6 / 200) < 1.2))","expected_output":"True"},{"test":"import numpy as np\n_r = np.random.default_rng(0)\ndef _ring(n):\n    t = _r.uniform(0.0, 2.0 * np.pi, n)\n    rad = 1.0 + 0.04 * _r.normal(size=n)\n    return np.stack([rad * np.cos(t), 0.2 * rad * np.sin(t)], 1)\n_X = _ring(800)\n_m = fit(_X.copy())\n_T = _ring(4000)\n_lq = np.asarray(logpdf(_m, _T), dtype=float)\n_h = 0.5 * np.log(2.0 * np.pi * np.e * 0.04 ** 2) + np.log(2.0 * np.pi) + np.log(0.2)\nprint(bool(np.mean(_lq) > -_h - 0.6))","expected_output":"True"},{"test":"import numpy as np\n_r = np.random.default_rng(1)\ndef _two(n):\n    return _r.normal(size=(n, 2)) * np.where(_r.random(n) < 0.5, 0.02, 1.0)[:, None]\ndef _lp(a):\n    q = (a * a).sum(1)\n    return np.logaddexp(np.log(0.5) - q / (2 * 0.02 ** 2) - np.log(2 * np.pi * 0.02 ** 2), np.log(0.5) - q / 2 - np.log(2 * np.pi))\n_m = fit(_two(800))\n_T = _two(4000)\n_lq = np.asarray(logpdf(_m, _T), dtype=float)\nprint(bool(np.mean(_lp(_T) - _lq) < 0.8))","expected_output":"True"}],"approved_user_libraries":["numpy","scipy","sklearn","torch"],"lower_is_better":false,"data_info":"There is no dataset to read. The grader draws every dataset from a known density in a separate process and gives your code only `X_train`.\n\nRun uses 30 datasets, 3 from each of these 10 families, with `n` from 300 to 2000:\n1. Thin rings whose width and mass change along the curve\n2. Spirals whose arms widen towards the outside\n3. Anisotropic Gaussian blobs of very different sizes\n4. Many tiny clusters over a wide background\n5. Uniform regions with sharp edges: discs, annuli, polygons and bars at different density levels\n6. Hard walls, with density decaying away from a straight edge\n7. Heavy-tailed Student-t mixtures\n8. A smooth density with circular holes cut out of it\n9. A narrow wave with hard ends, whose width changes along it\n10. Networks of thin tubes\n\nSubmit uses 56 datasets, 4 from each of 14 families: these 10 with new seeds, plus 4 more that are not listed here.\n\nEvery dataset is then rotated, scaled by a different amount on each axis and shifted. Your code receives only the points.","time_limits":{"test":540,"dev":360},"gpu":false,"description":"## Highest Held-Out Log-Likelihood with a Nonparametric Density Estimator\n\nYou get a sample of 2-D points from a density you are never told, and you answer with a density. The hidden densities have thin rings and tubes, regions with hard edges, swarms of tiny clusters and heavy tails, and your code is never told which one it is facing. The grader knows each true density exactly, so it measures your expected held-out log-likelihood against the best possible value, with no test-set luck in the number.\n\n### What you write\n\n```python\ndef fit(X_train):\n    ...\n    return model            # anything you like\n\ndef logpdf(model, X):\n    ...\n    return log_density      # np.ndarray of shape (len(X),)\n```\n\n`X_train` has shape `(n, 2)`, with `n` from 300 to 2000. Every dataset is rotated, rescaled on each axis and shifted by unknown amounts, so a number that suits one dataset's units means nothing on the next.\n\n### How it is graded\n\nFor each dataset the grader builds a lattice from `X_train`. On each axis it takes the 0.5% to 99.5% quantile range and widens it by 25% of its length on both sides, then places the centres of a 256 by 256 grid of cells in that box. It calls `logpdf(model, X)` on those centres only, at most 4,096 rows per call. It normalises your values over the lattice into probabilities $Q_c$, mixes in a fraction $10^{-6}$ of the uniform distribution so one zero cannot be infinitely costly, and does the same for the true density to get $P_c$. Then\n\n$$\ns = \\sum_c P_c \\log Q_c - \\sum_c P_c \\log P_c = -\\mathrm{KL}(P \\,\\|\\, Q)\n$$\n\nThis is the average log-likelihood of an infinitely large test set from the true density, restricted to the box, minus the same average for the true density itself. It is in nats per test point, and $0$ means a perfect estimate. A dataset counts as at most $4$ nats below the truth. Your score is the mean of $s$ over all datasets. **Higher is better**, and the lab is passed at **-0.21 or above**.\n\nThe lattice comes from your own training data, so no hidden point ever reaches your code. Tall spikes on the points you have seen gain nothing, because the score sums over the whole box. Multiplying your density by a constant gains nothing either, because the grader normalises it.\n\n- **Run**: 30 datasets from 10 families, listed under Data, with per-dataset results and your printed output shown.\n- **Submit**: 56 hidden datasets from 14 families, 4 of which never appear in Run, with different seeds. Submit reports means only and hides your printed output.\n\n### Budgets and rules\n\n- 10 seconds of CPU time per dataset, covering `fit` and every `logpdf` call and counted over all threads and worker processes, so `n_jobs` and extra threads buy no extra compute. Every dataset starts on one thread. In total your code may use 270 CPU seconds on Run and 420 on Submit. A dataset also stops at 30 seconds of wall-clock time.\n- `logpdf` has to be a log density: the sum of `exp(logpdf)` times the cell area over the lattice may not exceed 1.2. Less is fine, since a real density can have mass outside the box. `-inf` is allowed and means density zero. NaN and `+inf` are not.\n- Libraries: numpy, scipy, sklearn, torch, math, itertools, collections, heapq, bisect, random, statistics, time, warnings, typing, copy, enum, abc. Everything else, including file access and any dataset, is refused.\n- Assigning to or deleting an attribute (`x.y = ...`) is allowed only on `self` inside a method of a class, so ordinary classes work. Names that reach modules or object internals (`getattr`, `__dict__` and so on) are refused, and so is `str.format`, because it can read attributes from inside a string. f-strings are fine.\n- Your source is capped at 30,000 characters, 800 numeric literals and 3,000 characters of string constants.\n- An exception out of `fit` or `logpdf`, a wrong shape, or a broken cap or time limit fails the run with a score of -99.\n","tags":["density-estimation","kde","kernel-density","nonparametric","competitive","pml-book"],"id":"8f67a19c-16b8-4585-afd4-03438ddd052d","img_type":"full","dataset_id":"synthetic","difficulty":"hard","evaluation_metric":"heldout_ll_vs_truth","min_eval_metric":-0.21,"category":"Statistics","dataset":"Hidden 2-D densities with known exact form, sampled in the grader","title":"Highest Held-Out Log-Likelihood with a Nonparametric Density Estimator","time_limits_seconds":{"dev":360,"test":540}},{"created_at":"2026-10-20T16:10:32.666000+00:00","type":"general","test_cases":[{"test":"import numpy as np\nrng = np.random.default_rng(0)\ntrain = {'feats': rng.uniform(0, 1, size=(3, 64, 5, 6)).astype(np.float32), 'accept': rng.uniform(size=(3, 64, 5)) < 0.6}\ntrain['feats'][..., 3] = np.arange(5)\npolicy = fit(train, 9.7, 0.013)\nL = np.asarray(plan(policy, train['feats'][0]))\nprint(L.shape == (64,) and bool(np.all(L == np.round(L))) and 0 <= L.min() and L.max() <= 5)","expected_output":"True"},{"test":"import numpy as np\nrng = np.random.default_rng(1)\ntrain = {'feats': rng.uniform(0, 1, size=(3, 64, 5, 6)).astype(np.float32), 'accept': rng.uniform(size=(3, 64, 5)) < 0.6}\ntrain['feats'][..., 3] = np.arange(5)\npolicy = fit(train, 9.7, 0.013)\na = np.asarray(plan(policy, train['feats'][1])); b = np.asarray(plan(policy, train['feats'][1].copy()))\nprint(bool(np.array_equal(a, b)))","expected_output":"True"},{"test":"import numpy as np\nrng = np.random.default_rng(2)\nfeats = rng.uniform(0, 1, size=(6, 64, 5, 6)).astype(np.float32)\nfeats[..., 3] = np.arange(5)\naccept = feats[..., 0] > 0.5\npolicy = fit({'feats': feats, 'accept': accept}, 9.7, 0.013)\nhi = feats[0].copy(); hi[..., 0] = 0.99\nlo = feats[0].copy(); lo[..., 0] = 0.01\nprint(int(np.asarray(plan(policy, hi)).sum()) > int(np.asarray(plan(policy, lo)).sum()))","expected_output":"True"},{"test":"import numpy as np\nrng = np.random.default_rng(3)\nfeats = rng.uniform(0, 1, size=(6, 64, 5, 6)).astype(np.float32)\nfeats[..., 3] = np.arange(5)\naccept = feats[..., 0] > 0.5\npolicy = fit({'feats': feats, 'accept': accept}, 9.7, 0.013)\nL = np.asarray(plan(policy, feats[2]))\nprint(bool(np.any(L < 5)))","expected_output":"True"}],"lower_is_better":false,"approved_user_libraries":["numpy","torch","math","time","random"],"data_info":"Decode steps of 64 sequences with 5 Pythia-70m draft tokens each, contexts of 64 tokens from TinyStories and Pride and Prejudice, six draft features per token, greedy acceptance labels from Pythia-160m. Train: 192 steps with labels. Hidden replay: 128 later steps (Submit) or 40 (Run). The harness reports tokens per second for the policy, for fixed-length verification and for the oracle, with mean verified and accepted drafts per sequence and the mean step time under the curve t0 + kappa * tokens.","time_limits":{"test":300,"dev":120},"example":{"input":"fit(train, 9.7, 0.013) on the labelled steps, then plan(policy, feats) for one step of 64 sequences","output":"64 integers in 0..5, e.g. [5, 3, 0, 4, 5, 1, ...]; the harness scores accepted tokens per second against verifying 5 everywhere"},"gpu":false,"description":"Decide how many draft tokens each sequence in a decode step gets verified, and beat fixed-length verification by as much as you can. The data is real: a Pythia-70m draft model proposed 5 tokens for each of 64 sequences per step on story and novel text, and a Pythia-160m target checked them greedily. For every draft token you get six features from the draft model (its probability for the token, the top-1 to top-2 log-probability margin, the draft distribution's entropy, the position in the draft, whether the token starts a word, its length in characters). You never see the target. The leaderboard ranks by **throughput gain over fixed-length verification**, in percent, higher is better.\n\n**Contract.** Implement two functions:\n\n- `fit(train, t0, kappa) -> policy` receives `train[\"feats\"]`, float32 of shape `(steps, 64, 5, 6)`, and `train[\"accept\"]`, bool of shape `(steps, 64, 5)` saying whether the target accepted each draft token, plus the throughput curve's intercept `t0` (ms) and slope `kappa` (ms per token). Return any object.\n- `plan(policy, feats) -> lengths` receives one step's features, float32 `(64, 5, 6)`, and returns 64 integers in `0..5`: how many leading drafts each sequence verifies. `plan` must be deterministic and must use nothing but its arguments.\n\n**Scoring.** The harness replays hidden steps. A sequence that verifies `n` drafts produces its leading accepted drafts among those `n` plus one token from the target. A step with `V` verified drafts in total costs `t0 + kappa * (64 + V)` milliseconds. Your throughput is accepted tokens per second over the whole replay; the score is the percentage gain over verifying all 5 drafts for every sequence. The harness also reports the oracle that knows the outcomes. Submit: `fit` gets 192 training steps and 60 seconds; scoring replays 128 steps with 30 seconds of total `plan` time. Run: 20 seconds to fit, 40 steps, 10 seconds of `plan` time. Clearing 3.0% counts as solved; everything above that is leaderboard.\n\n**Gates.** The score is set to 0 if `plan` returns the wrong shape, non-integers or lengths outside `0..5`, if it is not deterministic, or if `fit` or the total `plan` time runs over budget.","tags":["inference","speculative-decoding","scheduling","calibration","open-ended","leaderboard"],"id":"8f72b129-ec9e-4842-9500-c6c367227548","img_type":"pytorch","dataset_id":"dspark-verify","evaluation_metric":"throughput_gain_pct","difficulty":"hard","min_eval_metric":3.0,"category":"Inference","title":"Best Speculative Verification Policy","dataset":"Pythia-70m drafts verified by Pythia-160m","time_limits_seconds":{"dev":120,"test":300}},{"description":"Implement an **activation function** for a neural network using only NumPy. Your `activation(x)` function takes an array of values and returns the activated outputs.\n\nThe training harness handles everything else (forward pass, backpropagation, weight updates). You just define **how neurons transform their inputs**.\n\nYou may implement **ANY activation function** you like: ReLU, sigmoid, tanh, or something creative. Your activation will be used in a simple neural network trained on MNIST.","constraints":["Use ONLY numpy - no PyTorch, TensorFlow, or other libraries","activation(x) must return an array of the SAME shape as input","Must be a non-linear function (not just returning x unchanged)","Should work element-wise on arrays of any shape","Any activation function is valid!"],"id":"9","test_cases":[{"test":"import numpy as np\nx = np.array([-2.0, -1.0, 0.0, 1.0, 2.0])\ny = activation(x)\nprint(y.shape == x.shape)","expected_output":"True"},{"test":"import numpy as np\nx = np.array([-2.0, -1.0, 0.0, 1.0, 2.0])\ny = activation(x)\n# Should not be identity function\nprint(not np.allclose(y, x))","expected_output":"True"},{"test":"import numpy as np\nx = np.array([[1.0, -1.0], [2.0, -2.0]])\ny = activation(x)\n# Should work on 2D arrays\nprint(y.shape == (2, 2))","expected_output":"True"},{"test":"import numpy as np\n# Should be deterministic\nx = np.array([1.0, 2.0, 3.0])\ny1 = activation(x)\ny2 = activation(x)\nprint(np.allclose(y1, y2))","expected_output":"True"}],"approved_user_libraries":["numpy"],"difficulty":"easy","evaluation_metric":"Accuracy","data_info":"MNIST 28x28 grayscale digits flattened to 784-dim vectors, scaled to [0,1]. Trained with a 3-layer neural network (784→128→128→10).","time_limits":{"test":"180 seconds","dev":"90 seconds"},"schema":"practical_question_v1","min_eval_metric":0.8,"example":{"input":{"x":"numpy array of any shape, e.g., [-2.0, -1.0, 0.0, 1.0, 2.0]"},"output":{"activated":"numpy array of same shape with activation applied element-wise"}},"category":"Activation Functions","title":"Design Your Own Activation Function","model_specs":"3-layer neural network (784→128→128→10). Your activation is applied after each hidden layer (used twice).","memory_limit":"1 GB","dataset":"MNIST","createdAt":"2026-05-13T21:01:44.529000+00:00","time_limits_seconds":{"dev":90,"test":180},"type":"epoch","lower_is_better":false,"gpu":false},{"created_at":"2026-07-29T03:03:59.885000+00:00","type":"general","constraints":["CPU only: do not call .cuda(), .to('cuda'), or .to(device)","Use only numpy and torch (no sklearn, no torchvision datasets, no network I/O)","Implement build_model and train_model with the specified signatures","Model must include Conv2d -> ReLU -> pool -> Linear (extras allowed)","Seed randomness inside train_model when shuffling","Return logits of shape (N, n_classes); harness uses argmax for accuracy","Keep total runtime well under the time limit on CPU"],"lower_is_better":false,"approved_user_libraries":["numpy","torch"],"time_limits":{"test":200,"dev":60},"data_info":"Harness synthesizes a seeded two-class dataset with numpy/torch only (no downloads). Class 0: horizontal stripe patterns on an 8x8 grid (random 0/1 phase). Class 1: vertical stripes. Independent Gaussian noise (std~0.12) is added per image. Default split: 320 train / 80 test, balanced classes, shuffled with RandomState(42). Pixel values are float32; labels int64.","example":{"input":"build_model(img_size=8, n_classes=2) then train_model(model, train_x, train_y, epochs=12) where train_x is FloatTensor (320, 1, 8, 8) and train_y is LongTensor (320,) with labels 0/1 (horizontal vs vertical stripes + light noise).","output":"Trained nn.Module; harness evaluates on held-out test set and reports JSON like {\"test_acc\": 0.975}"},"pytorch_starter_code":"import torch\nimport torch.nn as nn\nimport torch.optim as optim\n\n\nclass TinyCNN(nn.Module):\n    \"\"\"Small CNN: Conv2d -> ReLU -> pool -> (optional extras) -> Linear.\"\"\"\n\n    def __init__(self, img_size=8, n_classes=2):\n        super().__init__()\n        # TODO: define conv, activation, pooling, and classifier layers\n        # Input shape: (N, 1, img_size, img_size)\n        raise NotImplementedError\n\n    def forward(self, x):\n        # TODO: implement forward pass; return logits of shape (N, n_classes)\n        raise NotImplementedError\n\n\ndef build_model(img_size=8, n_classes=2):\n    \"\"\"Return an instance of your TinyCNN (or equivalent nn.Module).\"\"\"\n    # TODO: return TinyCNN(img_size=img_size, n_classes=n_classes)\n    raise NotImplementedError\n\n\ndef train_model(model, train_x, train_y, epochs=15, lr=0.01, batch_size=32, seed=0):\n    \"\"\"Train model on train_x/train_y and return the trained model.\n\n    Args:\n        model: nn.Module from build_model\n        train_x: FloatTensor (N, 1, H, W)\n        train_y: LongTensor (N,)\n        epochs: number of full passes over the data\n        lr: optimizer learning rate\n        batch_size: mini-batch size\n        seed: RNG seed for shuffling / init determinism\n\n    Returns:\n        Trained model (same instance is fine).\n    \"\"\"\n    # TODO:\n    # - torch.manual_seed(seed)\n    # - CrossEntropyLoss + Adam (or SGD)\n    # - mini-batch loop for `epochs` epochs\n    # - model.train(); zero_grad -> forward -> loss -> backward -> step\n    raise NotImplementedError\n","model_specs":"CPU-only torch.nn.Module CNN. Required pattern: at least one Conv2d, ReLU, spatial pool (e.g. MaxPool2d), then Linear classifier to n_classes logits. Single-channel input. No Dropout/BatchNorm required. No .cuda() or .to(device). Cross-entropy training with a torch optimizer for several epochs.","gpu":false,"description":"# Train a Tiny CNN Image Classifier\n\nBuild and train a small convolutional neural network to classify tiny synthetic images into two pattern classes (horizontal vs vertical stripes).\n\n## What you implement\n\n1. **`build_model(img_size=8, n_classes=2)`**  \n   Return a `torch.nn.Module` CNN with at least: `Conv2d -> ReLU -> pool -> Linear` (you may add a second conv block). Input images are single-channel `(N, 1, img_size, img_size)`.\n\n2. **`train_model(model, train_x, train_y, epochs=15, lr=0.01, batch_size=32, seed=0)`**  \n   Train `model` in place on the provided tensors with a standard classification loss and an optimizer. Return the trained model. Keep everything on CPU (no `.cuda()` / `.to(device)`).\n\n## Data (provided by the harness)\n\n- `train_x`: `FloatTensor` shape `(N_train, 1, H, W)`\n- `train_y`: `LongTensor` shape `(N_train,)` with labels in `{0, 1}`\n- Test split is held by the harness; it will call your APIs, then measure accuracy.\n\n## Success criteria\n\nTest accuracy must clearly beat chance on this easy synthetic task (see grader floor). Seed all randomness you introduce so runs are deterministic.","tags":["pytorch","cnn","convolution","image-classification","training","pooling"],"id":"91c76ab2-7d3a-43a7-98ce-385aab6f1691","evaluation_metric":"accuracy","difficulty":"hard","schema":"Learner APIs receive: train_x FloatTensor (N, 1, H, W) with H=W=img_size (default 8); train_y LongTensor (N,) in {0,1}. build_model(img_size, n_classes) -> nn.Module. train_model(model, train_x, train_y, epochs, lr, batch_size, seed) -> trained nn.Module. Harness owns test_x/test_y and computes accuracy.","min_eval_metric":0.85,"category":"Model Architecture","title":"Train a Tiny CNN Image Classifier","time_limits_seconds":{"dev":60,"test":200}},{"created_at":"2026-10-28T18:55:06.752000+00:00","type":"general","test_cases":[{"test":"import numpy as np\nrng = np.random.default_rng(0)\nt = np.sort(rng.uniform(0, 12, 300))\nt = t[(t < 5) | (t > 6.5)]\nf = lambda s: 0.8 * s + 2.0 * np.sin(2 * np.pi * s / 0.9)\ny = f(t) + 0.2 * rng.standard_normal(len(t))\nfit(t, y)\nm, v = predict(np.array([2.5, 5.7, 13.0]))\nm, v = np.asarray(m, dtype=float), np.asarray(v, dtype=float)\nprint(m.shape == (3,) and v.shape == (3,) and bool(np.all(np.isfinite(m))) and bool(np.all(v > 0)))","expected_output":"True"},{"test":"import numpy as np\nrng = np.random.default_rng(0)\nt = np.sort(rng.uniform(0, 12, 300))\nt = t[(t < 5) | (t > 6.5)]\nf = lambda s: 0.8 * s + 2.0 * np.sin(2 * np.pi * s / 0.9)\ny = f(t) + 0.2 * rng.standard_normal(len(t))\nfit(t, y)\n# the cycle and trend continue through the gap 5 < t < 6.5\ntq = np.linspace(5.1, 6.4, 20)\nm, v = predict(tq)\nprint(float(np.sqrt(np.mean((np.asarray(m, dtype=float) - f(tq)) ** 2))) < 0.6)","expected_output":"True"},{"test":"import numpy as np\nrng = np.random.default_rng(0)\nt = np.sort(rng.uniform(0, 12, 300))\nt = t[(t < 5) | (t > 6.5)]\nf = lambda s: 0.8 * s + 2.0 * np.sin(2 * np.pi * s / 0.9)\ny = f(t) + 0.2 * rng.standard_normal(len(t))\nfit(t, y)\n# predictive variance should be larger two units past the data than in the middle of it\nm, v = predict(np.array([3.0, 14.0]))\nv = np.asarray(v, dtype=float)\nprint(bool(v[1] > v[0]))","expected_output":"True"}],"approved_user_libraries":["numpy","scipy"],"lower_is_better":false,"data_info":"Synthetic seasonal series generated inside the grader (no dataset). Per series: 500 training points at random sorted times in [0, 30] minus two interior gaps of length 1.5-2.5; 120 hidden points (40 in each gap, 40 in [30, 32]). Smooth curved trend + seasonal cycle (period 0.7-1.4, non-sinusoidal, slowly drifting amplitude and shape) + medium-term irregular wiggles + Gaussian noise. Run = 2 series, Submit = 8 held-out series.","time_limits":{"test":360,"dev":150},"example":{"input":"fit(t_train, y_train) with t_train.shape == (500,), then predict(t_query) with t_query.shape == (120,)","output":"(mean, var), two float arrays of shape (120,), e.g. mean [31.2, 30.7, ...], var [0.35, 0.41, ...]; the grader reports the mean log predictive density over all hidden points, e.g. -0.71 nats"},"gpu":false,"description":"Predict a noisy seasonal time series where you have no data, and say how sure you are. The leaderboard ranks by the **mean log predictive density of the hidden observations, in nats per point, higher is better**: a sharp prediction in the right place scores high, a confident miss is punished hard, and a vague prediction scores low everywhere.\n\n**Contract.** Define two functions:\n\n- `fit(t_train, y_train)` receives one series: float arrays of shape `(n,)` with the observation times (sorted) and the noisy values. It returns nothing; keep what you need in module-level state. It is called once per series and replaces anything learned before.\n- `predict(t_query)` receives float times of shape `(m,)`, in no particular order, and returns `(mean, var)`: two float arrays of shape `(m,)` with the predictive mean and the predictive variance of a **noisy observation** $y$ at each time.\n\n**The data.** Every series is simulated inside the grader and looks like an atmospheric CO$_2$ record: a smooth rising trend that may curve, a seasonal cycle that is not a pure sine wave and whose amplitude and shape drift slowly over the years, medium-term irregular wiggles lasting about a season to a year and a half, and independent Gaussian observation noise. The period of the cycle is the same within a series but differs between series, somewhere between 0.7 and 1.4 time units; nothing about the generating parameters is passed to you. Each series has $n = 500$ observations at random times in $[0, 30]$ except for two interior gaps, each 1.5 to 2.5 units long. The hidden points are 40 inside each gap (interpolation) and 40 between 30 and 32 (forecasting past the end), 120 per series.\n\n- Run: 2 series.\n- Submit: 8 held-out series drawn from the same family with different random draws.\n\n**Score.** For every hidden point,\n\n$$\\ell = \\log \\mathcal{N}\\big(y \\mid \\mu,\\ v\\big) = -\\tfrac{1}{2}\\log(2\\pi v) - \\frac{(y - \\mu)^2}{2v}, \\qquad v = \\max\\big(\\text{var},\\ 10^{-4}\\,\\mathrm{Var}(y_{\\text{train}})\\big)$$\n\nand the score is the mean of $\\ell$ over all hidden points of all series. The report also gives, per series, the mean over the gaps and over the forecast window, the RMSE of your mean, the share of points inside your 95% interval, and the score of an oracle that knows the true noise-free function and the noise level. A score of **-1.60 or more** counts as solved; everything above that is leaderboard.\n\n**Budget and rules.** Your total time inside `fit` and `predict` is capped at 60 s on Run and 180 s on Submit (all series together). Your code may import only `numpy`, `scipy` and standard-library helpers (`math`, `itertools`, `functools`, `collections`, `heapq`, `bisect`, `random`, `warnings`, `dataclasses`, `typing`, `statistics`, `operator`, `copy`, `cmath`, `time`); ready-made model libraries such as scikit-learn are not allowed.\n\n**Gates.** The score is void and the run fails if any of these happen:\n- `predict` returns anything but two finite arrays of shape `(m,)`, or a negative variance.\n- `fit` or `predict` raises.\n- The time budget runs out.\n- Your code imports a module outside the list above.\n- The score beats the oracle by more than 0.1 nats per point, which no model learned from the training data can do.","tags":["gaussian-processes","kernels","marginal-likelihood","time-series","uncertainty","probabilistic-ml","open-ended","leaderboard"],"id":"92a8f37c-3bec-475a-bdcd-6b49b498a8ce","img_type":"full","dataset_id":"synthetic","difficulty":"hard","evaluation_metric":"log_predictive_density","min_eval_metric":-1.6,"category":"Regression","title":"Best Predictive Density on a Seasonal Time Series","dataset":"Synthetic CO2-like seasonal time series","time_limits_seconds":{"dev":150,"test":360}},{"created_at":"2026-10-27T14:22:16.808000+00:00","type":"general","test_cases":[{"test":"import numpy as np\nag = Agent(5, 10, 1000)\nx = np.asarray(ag.act())\nprint(x.shape == (5,) and x.dtype.kind in 'iu' and int(x.min()) >= 0 and int(x.max()) < 10)","expected_output":"True"},{"test":"import numpy as np\nag = Agent(3, 4, 200)\nrng = np.random.default_rng(0)\nok = True\nfor t in range(200):\n    a = np.asarray(ag.act()).astype(np.int64)\n    ok = ok and a.shape == (3,) and int(a.min()) >= 0 and int(a.max()) < 4\n    ag.update(a, rng.normal(size=3))\nprint(ok)","expected_output":"True"},{"test":"import numpy as np\n# one 2-armed problem: arm 0 pays 1 for 5,000 steps, then arm 1 does\nag = Agent(1, 2, 8000)\nlate = 0\nfor t in range(8000):\n    a = np.asarray(ag.act()).astype(np.int64)\n    good = 0 if t < 5000 else 1\n    ag.update(a, np.where(a == good, 1.0, 0.0))\n    if t >= 7000:\n        late += int(a[0] == 1)\nprint(late >= 800)","expected_output":"True"}],"approved_user_libraries":["numpy","math","collections","itertools","functools","random"],"lower_is_better":false,"time_limits":{"test":300,"dev":150},"data_info":"Synthetic bandit problems generated inside the grader from fixed seeds. Run = walk (64 problems); mean-reverting, k=15 (64 problems). Submit = four held-out regimes of 100 problems (classic random walk, faster values that wander around a long-run level, the same with k = 30, sudden jumps with k = 20). 200,000 steps per regime; rewards are the pulled arm's true value plus N(0, 1) noise.","example":{"input":"Agent(n_problems=100, k=10, n_steps=200000); each step act() -> e.g. array([3, 7, 0, ...]) and update(actions, rewards) with rewards like array([4.81, -0.37, 5.62, ...])","output":"The grader plays every regime and reports the mean share of attainable reward captured over the last 100,000 steps, e.g. 88.4 (percent)"},"gpu":false,"description":"Earn as much reward as you can on k-armed bandit problems whose true action values never stop changing. This is the nonstationary testbed of two classic Sutton and Barto exercises, extended to harder variants. The leaderboard ranks by the **share of the attainable reward you capture over the second half of each 200,000-step run, in percent, higher is better**.\n\n**Contract.** Define a class `Agent`:\n\n- `Agent(n_problems, k, n_steps)` is created once per regime. One agent plays `n_problems` independent bandit problems side by side, each with `k` arms, for `n_steps` = 200,000 steps.\n- `act() -> array` returns one action per problem: integers of shape `(n_problems,)` with values in `0..k-1`.\n- `update(actions, rewards)` is called right after every `act()` with the actions as played (int64, shape `(n_problems,)`) and the reward each problem paid (float64, shape `(n_problems,)`).\n\nCalls alternate `act`, `update`, `act`, `update`,... 200,000 times per regime. The problems are independent: an action in one never affects another.\n\n**The problems.** Arm $a$ of a problem has a true value $q_t^*(a)$ at step $t$. Pulling it pays $q_t^*(a)$ plus Gaussian noise with mean 0 and standard deviation 1. After every step the true values move. Your agent only ever sees its own rewards.\n\n- Run: two regimes of 64 problems. The first is the classic random walk: $k = 10$, all values start at 0, and each value takes an independent $\\mathcal{N}(0, 0.01^2)$ step on every time step. The second has values that wander around a long-run level instead of drifting away, with $k = 15$.\n- Submit: four held-out regimes of 100 problems with fresh seeds. They are the classic random walk; faster values that wander around a long-run level; the same kind of values with $k = 30$; and values that jump suddenly to new levels, with $k = 20$.\n\n**Score.** For each regime, over steps 100,001 to 200,000 and all its problems:\n\n$$\\text{captured} = 100 \\cdot \\frac{\\sum_t \\big(q_t^*(A_t) - \\bar q_t\\big)}{\\sum_t \\big(\\max_a q_t^*(a) - \\bar q_t\\big)}, \\qquad \\bar q_t = \\tfrac{1}{k}\\sum_a q_t^*(a)$$\n\nThis puts the expected reward of the arms you pulled on a scale where choosing uniformly at random scores 0 and always pulling the arm that is best right now scores 100. It uses the true value $q_t^*(A_t)$ of the arm you pulled rather than the noisy reward, so reward noise adds no luck. The score is the mean over regimes. For every regime the report also shows the book's own measure (your average reward over the last 100,000 steps), the same average for the always-best oracle and for uniform random choice, and how often you pulled the best arm. A score of **80 or more** counts as solved; everything above that is leaderboard.\n\n**Budget and rules.** The total time spent inside your `Agent` (constructor, `act`, `update`) is capped at 60 s on Run and 150 s on Submit, so work on all problems at once with array operations. `random` and `numpy.random` are seeded before each regime. Your code may import only `numpy`, `math`, `collections`, `itertools`, `functools`, `random`, `heapq` and `bisect`, and may use an imported module only as `module.name`.\n\n**Gates.** The score is set to 0 and the run fails if any of these happen:\n- `act` returns anything but integers of shape `(n_problems,)` in `0..k-1`.\n- Any method raises.\n- The time budget runs out.\n- Your code reads files, uses introspection (`globals`, `vars`, `getattr`/`setattr`, frames, tracebacks, `eval`/`exec`), or assigns to, aliases or reaches into the internals of an imported module.","tags":["reinforcement-learning","bandits","exploration","nonstationary","sutton-barto","open-ended","leaderboard"],"id":"9ca26f44-66b3-4bba-b396-ccf3c55e6932","img_type":"full","dataset_id":"synthetic","difficulty":"medium","evaluation_metric":"reward_captured_pct","min_eval_metric":80.0,"category":"Reinforcement Learning","dataset":"Synthetic nonstationary k-armed bandit testbeds","title":"Most Reward on a Drifting Bandit","time_limits_seconds":{"dev":150,"test":300}},{"created_at":"2026-07-29T03:03:59.579000+00:00","type":"general","constraints":["CPU-only tensors; no .cuda() or .to(device)","Do not use torch.optim or torch.nn","Do not use closed-form / normal-equation solutions","Only numpy and torch may be imported","Must use autograd (loss.backward) for gradients","Return detached tensors for w and b","Keep runtime well under 120s on CPU"],"lower_is_better":true,"approved_user_libraries":["numpy","torch"],"time_limits":{"test":200,"dev":60},"data_info":"Harness synthesizes data with torch.manual_seed(42): X ~ N(0,1) of shape (200, 3), w_true=[1.5,-2.0,0.5], b_true=0.3, y = X @ w_true + b_true + 0.1*N(0,1). A seeded randperm holds out 40 samples for test; the learner fits on the remaining 160.","example":{"input":"X shape (160, 3), y shape (160,), lr=0.1, steps=500 on seeded y = X @ [1.5, -2.0, 0.5] + 0.3 + noise","output":"w ~= [1.5, -2.0, 0.5], b ~= 0.3; held-out MSE typically near noise floor (~0.01)"},"pytorch_starter_code":"import torch\nimport numpy as np\n\n\ndef fit_linear_regression(X, y, lr=0.1, steps=500):\n    \"\"\"Fit y ~= X @ w + b with full-batch GD using only autograd.\n\n    Args:\n        X: Float tensor (N, D)\n        y: Float tensor (N,) or (N, 1)\n        lr: learning rate\n        steps: number of gradient descent iterations\n\n    Returns:\n        w: Float tensor (D,) learned weights (no grad)\n        b: Float tensor scalar learned bias (no grad)\n    \"\"\"\n    # TODO: ensure y is shape (N,)\n    # TODO: initialize w (D,) and b with requires_grad=True\n    # TODO: for each step:\n    #   - predict, compute MSE loss\n    #   - loss.backward()\n    #   - manual GD update under torch.no_grad()\n    #   - zero gradients\n    # TODO: return detached w, b\n    raise NotImplementedError\n","model_specs":"Manual full-batch gradient descent linear regressor: parameters w (D,) and b (scalar) with requires_grad=True; MSE loss; autograd backward; in-place GD updates only (no torch.optim, no torch.nn modules).","gpu":false,"description":"# Fit Linear Regression with Autograd\n\nImplement ordinary least squares linear regression using **only** PyTorch autograd. Do **not** use `torch.optim` or closed-form solvers.\n\n## Task\n\nWrite `fit_linear_regression(X, y, lr=0.1, steps=500)` that:\n\n1. Initializes parameters `w` (shape `(D,)`) and `b` (scalar) with `requires_grad=True`.\n2. Runs full-batch gradient descent for `steps` iterations minimizing mean squared error (MSE):\n   `L = mean((X @ w + b - y)^2)`.\n3. Uses autograd (`loss.backward()`) to obtain gradients and manually updates parameters with the learning rate `lr`.\n4. Returns the learned `(w, b)` as tensors **without** gradient tracking (detached).\n\nThe harness builds a seeded synthetic dataset `y = X @ w_true + b_true + noise`, holds out a test split, calls your function on the train split, and scores **test MSE** (lower is better).\n\n## Rules\n\n- Use CPU tensors only (no `.cuda()` / `.to(device)`).\n- Only `numpy` and `torch` are available.\n- Do not use `torch.optim`, `torch.nn`, or analytic normal equations.","tags":["pytorch","autograd","gradients","linear-regression","mse"],"id":"9ff596ea-672e-4101-9ce4-0856c55b62c9","evaluation_metric":"mse","difficulty":"medium","schema":"fit_linear_regression(X, y, lr=0.1, steps=500) receives X: float tensor (N, D), y: float tensor (N,) or (N, 1). Returns w: float tensor (D,), b: scalar float tensor. Test harness uses D=3.","min_eval_metric":0.25,"category":"PyTorch Fundamentals","title":"Fit Linear Regression with Autograd","time_limits_seconds":{"dev":60,"test":200}},{"created_at":"2026-09-23T04:17:13.154388+00:00","type":"general","constraints":["numpy only; no network access","Implement class EvictionPolicy(capacity_blocks) with admit(block, depth, prompt_blocks) -> bool, touch(block, depth, prompt_blocks, t, hit) and victim() -> a resident block","victim() must return a block that is currently in the cache; more than one percent invalid victims fails the run"],"last_updated":"2026-09-23T04:17:13.154388+00:00","test_cases":[{"test":"p = EvictionPolicy(4)\nprint(all(hasattr(p, m) for m in ('admit', 'touch', 'victim')))","expected_output":"True"},{"test":"p = EvictionPolicy(4)\nfor i in range(4):\n    p.touch(('b', i), i, 4, i, False)\nv = p.victim()\nprint(v in {('b', i) for i in range(4)})","expected_output":"True"},{"test":"p = EvictionPolicy(3)\nfor i in range(3):\n    p.touch(('b', i), 0, 1, i, False)\nfor t in range(3, 40):\n    p.touch(('b', 0), 0, 1, t, True)\nprint(p.victim() != ('b', 0))","expected_output":"True"}],"lower_is_better":false,"approved_user_libraries":["numpy"],"data_info":"Synthetic prompts as token-id lists generated inside the grader (no downloads): a shared 256-token system prompt, twelve multi-turn conversations, retrieval prompts over a pool of forty documents, and one-off prompts, interleaved at random; 1500 prompts through a 512-block cache on Submit, 600 through 384 blocks on Run.","time_limits":{"test":120,"dev":60},"example":{"input":"touch(block=<hash>, depth=3, prompt_blocks=20, t=412, hit=False) then admit(...) then, when the cache is full, victim()","output":"victim() returns one resident block; the grader reports hit_rate (yours), lru_hit_rate, invalid_fraction and test_acc = hit_rate"},"model_specs":"Your choice of admission and eviction policy. The grader owns the block-hash prefix cache and the workload; it reports the token hit rate and prints LRU's hit rate on the same stream for comparison.","gpu":false,"description":"# Design Your Own KV Cache Eviction Policy\n\nAn inference replica keeps a prefix cache of KV blocks so that a prompt whose beginning it has already processed can skip that part of prefill. The cache holds a fixed number of blocks, and when it is full something has to go. You decide what: which blocks are worth keeping, which are worth admitting in the first place, and which one to evict when space runs out. The grader replays a hidden stream of prompts through a cache driven by your policy and reports the token hit rate.\n\n```python\nclass EvictionPolicy:\n    def __init__(self, capacity_blocks):\n        ...\n\n    def admit(self, block, depth, prompt_blocks):\n        ...\n        return True   # False leaves the block uncached this time\n\n    def touch(self, block, depth, prompt_blocks, t, hit):\n        ...\n\n    def victim(self):\n        ...\n        return block  # a block currently in the cache\n```\n\n- A `block` is an opaque hashable key for sixteen tokens of a prompt; the key of a block depends on every token before it, so the same key always means the same prefix.\n- `depth` is the block's position within its prompt (`0` for the first block) and `prompt_blocks` the number of full blocks in that prompt.\n- The cache walks every prompt block by block, in order, with `t` the request index. For a block that is resident it calls `touch(..., hit=True)`. For a block that is not, it first calls `admit`; returning `False` skips the block entirely. Otherwise, if the cache is full it calls `victim` and removes the block you return, which must be resident; then it inserts the new block and calls `touch(..., hit=False)`. So `touch` only ever reports blocks that are in the cache, and the block returned by `victim` leaves it.\n\n## How it is graded\n\nThe grader owns the cache and the workload. The workload is a hidden interleaving of a chat application with a shared system prompt, several multi-turn conversations that resend their history, retrieval prompts that shuffle documents, and one-off prompts that will never be seen again. The cache holds far fewer blocks than the traffic would like. The reported metric is the fraction of full prompt blocks that were resident when looked up, over the whole stream, and higher is better. The grader also runs plain LRU on the same stream and prints its hit rate next to yours; the bar is set above LRU. A `victim` that is not resident counts as an invalid decision, and more than one percent of those fails the run. Only numpy is available.\n","tags":["kv-cache","prefix-caching","eviction","lru","serving","inference","open-ended"],"id":"a41c9e77-5d2b-4f0e-8c3a-6b7d8e9f0a1b","difficulty":"medium","evaluation_metric":"token_hit_rate","schema":"EvictionPolicy(capacity_blocks: int); admit(block: hashable, depth: int, prompt_blocks: int) -> bool; touch(block: hashable, depth: int, prompt_blocks: int, t: int, hit: bool) -> None; victim() -> hashable","min_eval_metric":0.36,"category":"Inference","title":"Design Your Own KV Cache Eviction Policy","time_limits_seconds":{"dev":60,"test":120}},{"created_at":"2026-10-27T19:33:17.610000+00:00","type":"general","test_cases":[{"test":"\ndef _tiny(kind):\n    st = lambda name, ins=(), out=None, scratch=None, loads=(), stores=(), inplace=(): {\n        \"name\": name, \"op\": \"op\", \"ins\": list(ins), \"out\": out, \"scratch\": scratch,\n        \"loads\": list(loads), \"stores\": list(stores), \"inplace\": list(inplace)}\n    if kind == \"chain\":\n        temps = {\"t0\": 4096, \"t1\": 4096, \"t2\": 4096, \"t3\": 4096, \"t4\": 4096}\n        steps = [st(\"k0\", out=\"t0\", loads=[(\"x\", 0, 0, 4096)]), st(\"k1\", [\"t0\"], \"t1\"), st(\"k2\", [\"t1\"], \"t2\"),\n                 st(\"k3\", [\"t2\"], \"t3\"), st(\"k4\", [\"t3\"], \"t4\"), st(\"k5\", [\"t4\"], stores=[(\"y\", 1, 0, 4096)])]\n        return {\"name\": \"chain\", \"temps\": temps, \"buffers\": {\"x\": 4096, \"y\": 4096}, \"steps\": steps}\n    temps = {\"t0\": 64, \"t1\": 64, \"t2\": 64, \"t3\": 32, \"k3.scratch\": 16}\n    steps = [st(\"k0\", out=\"t0\", loads=[(\"x\", 0, 0, 64)]),\n             st(\"k1\", [\"t0\"], stores=[(\"ring\", 1, 0, 64)]),\n             st(\"k2\", out=\"t1\", loads=[(\"ring\", 1, 0, 64)]),\n             st(\"k3\", [\"t0\", \"t1\"], \"t2\", scratch=\"k3.scratch\", inplace=[\"t0\"]),\n             st(\"k4\", [\"t2\"], stores=[(\"ring\", 2, 32, 96)]),\n             st(\"k5\", out=\"t3\", loads=[(\"ring\", 2, 0, 96)]),\n             st(\"k6\", [\"t3\"], stores=[(\"y\", 1, 0, 32)])]\n    return {\"name\": \"effects\", \"temps\": temps, \"buffers\": {\"x\": 64, \"ring\": 96, \"y\": 32}, \"steps\": steps}\n\n\ndef _check(prog, order, offsets):\n    \"\"\"Returns the arena size of a valid plan, or a string saying what is wrong.\"\"\"\n    steps = {s[\"name\"]: s for s in prog[\"steps\"]}\n    if sorted(order) != sorted(steps):\n        return \"order must list every step once\"\n    at = {n: k for k, n in enumerate(order)}\n    prod, readers = {}, {t: [] for t in prog[\"temps\"]}\n    for s in prog[\"steps\"]:\n        for t in (s[\"out\"], s[\"scratch\"]):\n            if t is not None:\n                prod[t] = s[\"name\"]\n        for t in s[\"ins\"]:\n            readers[t].append(s[\"name\"])\n    for t, rs in readers.items():\n        if any(at[r] <= at[prod[t]] for r in rs):\n            return f\"{t} is read before it is written\"\n    for a in prog[\"steps\"]:\n        for (b, v, lo, hi) in a[\"stores\"]:\n            for c in prog[\"steps\"]:\n                if c is a:\n                    continue\n                for (b2, w, lo2, hi2) in c[\"loads\"]:\n                    if b2 == b and lo < hi2 and lo2 < hi and (at[a[\"name\"]] < at[c[\"name\"]]) != (v <= w):\n                        return f\"load in {c['name']} sees the wrong version of {b}\"\n                for (b2, w, lo2, hi2) in c[\"stores\"]:\n                    if b2 == b and lo < hi2 and lo2 < hi and v < w and at[a[\"name\"]] > at[c[\"name\"]]:\n                        return f\"stores to {b} out of order\"\n    life = {t: (at[prod[t]], max([at[r] for r in readers[t]], default=at[prod[t]])) for t in prog[\"temps\"]}\n    for t in prog[\"temps\"]:\n        if type(offsets.get(t)) is not int or offsets[t] < 0 or offsets[t] % 4:\n            return f\"bad offset for {t}\"\n    names = list(prog[\"temps\"])\n    for i, a in enumerate(names):\n        for b in names[i + 1:]:\n            (ba, da), (bb, db) = life[a], life[b]\n            if ba <= db and bb <= da and offsets[a] < offsets[b] + prog[\"temps\"][b] and \\\n                    offsets[b] < offsets[a] + prog[\"temps\"][a]:\n                ok = False\n                for s in prog[\"steps\"]:\n                    for x, y in ((a, b), (b, a)):\n                        if s[\"out\"] == x and y in s[\"inplace\"] and life[y][1] == at[s[\"name\"]] and offsets[x] == offsets[y]:\n                            ok = True\n                if not ok:\n                    return f\"{a} and {b} overlap while both are live\"\n    return max(offsets[t] + prog[\"temps\"][t] for t in names)\nout = plan(_tiny('chain'))\nprint(type(out) is tuple and len(out) == 2 and type(out[0]) is list and type(out[1]) is dict)","expected_output":"True"},{"test":"\ndef _tiny(kind):\n    st = lambda name, ins=(), out=None, scratch=None, loads=(), stores=(), inplace=(): {\n        \"name\": name, \"op\": \"op\", \"ins\": list(ins), \"out\": out, \"scratch\": scratch,\n        \"loads\": list(loads), \"stores\": list(stores), \"inplace\": list(inplace)}\n    if kind == \"chain\":\n        temps = {\"t0\": 4096, \"t1\": 4096, \"t2\": 4096, \"t3\": 4096, \"t4\": 4096}\n        steps = [st(\"k0\", out=\"t0\", loads=[(\"x\", 0, 0, 4096)]), st(\"k1\", [\"t0\"], \"t1\"), st(\"k2\", [\"t1\"], \"t2\"),\n                 st(\"k3\", [\"t2\"], \"t3\"), st(\"k4\", [\"t3\"], \"t4\"), st(\"k5\", [\"t4\"], stores=[(\"y\", 1, 0, 4096)])]\n        return {\"name\": \"chain\", \"temps\": temps, \"buffers\": {\"x\": 4096, \"y\": 4096}, \"steps\": steps}\n    temps = {\"t0\": 64, \"t1\": 64, \"t2\": 64, \"t3\": 32, \"k3.scratch\": 16}\n    steps = [st(\"k0\", out=\"t0\", loads=[(\"x\", 0, 0, 64)]),\n             st(\"k1\", [\"t0\"], stores=[(\"ring\", 1, 0, 64)]),\n             st(\"k2\", out=\"t1\", loads=[(\"ring\", 1, 0, 64)]),\n             st(\"k3\", [\"t0\", \"t1\"], \"t2\", scratch=\"k3.scratch\", inplace=[\"t0\"]),\n             st(\"k4\", [\"t2\"], stores=[(\"ring\", 2, 32, 96)]),\n             st(\"k5\", out=\"t3\", loads=[(\"ring\", 2, 0, 96)]),\n             st(\"k6\", [\"t3\"], stores=[(\"y\", 1, 0, 32)])]\n    return {\"name\": \"effects\", \"temps\": temps, \"buffers\": {\"x\": 64, \"ring\": 96, \"y\": 32}, \"steps\": steps}\n\n\ndef _check(prog, order, offsets):\n    \"\"\"Returns the arena size of a valid plan, or a string saying what is wrong.\"\"\"\n    steps = {s[\"name\"]: s for s in prog[\"steps\"]}\n    if sorted(order) != sorted(steps):\n        return \"order must list every step once\"\n    at = {n: k for k, n in enumerate(order)}\n    prod, readers = {}, {t: [] for t in prog[\"temps\"]}\n    for s in prog[\"steps\"]:\n        for t in (s[\"out\"], s[\"scratch\"]):\n            if t is not None:\n                prod[t] = s[\"name\"]\n        for t in s[\"ins\"]:\n            readers[t].append(s[\"name\"])\n    for t, rs in readers.items():\n        if any(at[r] <= at[prod[t]] for r in rs):\n            return f\"{t} is read before it is written\"\n    for a in prog[\"steps\"]:\n        for (b, v, lo, hi) in a[\"stores\"]:\n            for c in prog[\"steps\"]:\n                if c is a:\n                    continue\n                for (b2, w, lo2, hi2) in c[\"loads\"]:\n                    if b2 == b and lo < hi2 and lo2 < hi and (at[a[\"name\"]] < at[c[\"name\"]]) != (v <= w):\n                        return f\"load in {c['name']} sees the wrong version of {b}\"\n                for (b2, w, lo2, hi2) in c[\"stores\"]:\n                    if b2 == b and lo < hi2 and lo2 < hi and v < w and at[a[\"name\"]] > at[c[\"name\"]]:\n                        return f\"stores to {b} out of order\"\n    life = {t: (at[prod[t]], max([at[r] for r in readers[t]], default=at[prod[t]])) for t in prog[\"temps\"]}\n    for t in prog[\"temps\"]:\n        if type(offsets.get(t)) is not int or offsets[t] < 0 or offsets[t] % 4:\n            return f\"bad offset for {t}\"\n    names = list(prog[\"temps\"])\n    for i, a in enumerate(names):\n        for b in names[i + 1:]:\n            (ba, da), (bb, db) = life[a], life[b]\n            if ba <= db and bb <= da and offsets[a] < offsets[b] + prog[\"temps\"][b] and \\\n                    offsets[b] < offsets[a] + prog[\"temps\"][a]:\n                ok = False\n                for s in prog[\"steps\"]:\n                    for x, y in ((a, b), (b, a)):\n                        if s[\"out\"] == x and y in s[\"inplace\"] and life[y][1] == at[s[\"name\"]] and offsets[x] == offsets[y]:\n                            ok = True\n                if not ok:\n                    return f\"{a} and {b} overlap while both are live\"\n    return max(offsets[t] + prog[\"temps\"][t] for t in names)\nres = _check(_tiny('effects'), *plan(_tiny('effects')))\nprint(isinstance(res, int) or res)","expected_output":"True"},{"test":"\ndef _tiny(kind):\n    st = lambda name, ins=(), out=None, scratch=None, loads=(), stores=(), inplace=(): {\n        \"name\": name, \"op\": \"op\", \"ins\": list(ins), \"out\": out, \"scratch\": scratch,\n        \"loads\": list(loads), \"stores\": list(stores), \"inplace\": list(inplace)}\n    if kind == \"chain\":\n        temps = {\"t0\": 4096, \"t1\": 4096, \"t2\": 4096, \"t3\": 4096, \"t4\": 4096}\n        steps = [st(\"k0\", out=\"t0\", loads=[(\"x\", 0, 0, 4096)]), st(\"k1\", [\"t0\"], \"t1\"), st(\"k2\", [\"t1\"], \"t2\"),\n                 st(\"k3\", [\"t2\"], \"t3\"), st(\"k4\", [\"t3\"], \"t4\"), st(\"k5\", [\"t4\"], stores=[(\"y\", 1, 0, 4096)])]\n        return {\"name\": \"chain\", \"temps\": temps, \"buffers\": {\"x\": 4096, \"y\": 4096}, \"steps\": steps}\n    temps = {\"t0\": 64, \"t1\": 64, \"t2\": 64, \"t3\": 32, \"k3.scratch\": 16}\n    steps = [st(\"k0\", out=\"t0\", loads=[(\"x\", 0, 0, 64)]),\n             st(\"k1\", [\"t0\"], stores=[(\"ring\", 1, 0, 64)]),\n             st(\"k2\", out=\"t1\", loads=[(\"ring\", 1, 0, 64)]),\n             st(\"k3\", [\"t0\", \"t1\"], \"t2\", scratch=\"k3.scratch\", inplace=[\"t0\"]),\n             st(\"k4\", [\"t2\"], stores=[(\"ring\", 2, 32, 96)]),\n             st(\"k5\", out=\"t3\", loads=[(\"ring\", 2, 0, 96)]),\n             st(\"k6\", [\"t3\"], stores=[(\"y\", 1, 0, 32)])]\n    return {\"name\": \"effects\", \"temps\": temps, \"buffers\": {\"x\": 64, \"ring\": 96, \"y\": 32}, \"steps\": steps}\n\n\ndef _check(prog, order, offsets):\n    \"\"\"Returns the arena size of a valid plan, or a string saying what is wrong.\"\"\"\n    steps = {s[\"name\"]: s for s in prog[\"steps\"]}\n    if sorted(order) != sorted(steps):\n        return \"order must list every step once\"\n    at = {n: k for k, n in enumerate(order)}\n    prod, readers = {}, {t: [] for t in prog[\"temps\"]}\n    for s in prog[\"steps\"]:\n        for t in (s[\"out\"], s[\"scratch\"]):\n            if t is not None:\n                prod[t] = s[\"name\"]\n        for t in s[\"ins\"]:\n            readers[t].append(s[\"name\"])\n    for t, rs in readers.items():\n        if any(at[r] <= at[prod[t]] for r in rs):\n            return f\"{t} is read before it is written\"\n    for a in prog[\"steps\"]:\n        for (b, v, lo, hi) in a[\"stores\"]:\n            for c in prog[\"steps\"]:\n                if c is a:\n                    continue\n                for (b2, w, lo2, hi2) in c[\"loads\"]:\n                    if b2 == b and lo < hi2 and lo2 < hi and (at[a[\"name\"]] < at[c[\"name\"]]) != (v <= w):\n                        return f\"load in {c['name']} sees the wrong version of {b}\"\n                for (b2, w, lo2, hi2) in c[\"stores\"]:\n                    if b2 == b and lo < hi2 and lo2 < hi and v < w and at[a[\"name\"]] > at[c[\"name\"]]:\n                        return f\"stores to {b} out of order\"\n    life = {t: (at[prod[t]], max([at[r] for r in readers[t]], default=at[prod[t]])) for t in prog[\"temps\"]}\n    for t in prog[\"temps\"]:\n        if type(offsets.get(t)) is not int or offsets[t] < 0 or offsets[t] % 4:\n            return f\"bad offset for {t}\"\n    names = list(prog[\"temps\"])\n    for i, a in enumerate(names):\n        for b in names[i + 1:]:\n            (ba, da), (bb, db) = life[a], life[b]\n            if ba <= db and bb <= da and offsets[a] < offsets[b] + prog[\"temps\"][b] and \\\n                    offsets[b] < offsets[a] + prog[\"temps\"][a]:\n                ok = False\n                for s in prog[\"steps\"]:\n                    for x, y in ((a, b), (b, a)):\n                        if s[\"out\"] == x and y in s[\"inplace\"] and life[y][1] == at[s[\"name\"]] and offsets[x] == offsets[y]:\n                            ok = True\n                if not ok:\n                    return f\"{a} and {b} overlap while both are live\"\n    return max(offsets[t] + prog[\"temps\"][t] for t in names)\narena = _check(_tiny('chain'), *plan(_tiny('chain')))\nprint(isinstance(arena, int) and arena <= 8192)","expected_output":"True"}],"lower_is_better":true,"approved_user_libraries":["numpy","math","collections","itertools","functools","random"],"data_info":"Synthetic programs generated inside the grader from fixed seeds. Run: 6 programs (MLP, inception-style block, transformer, optimizer step with in-place parameter updates, two random layered graphs). Submit: 10 held-out programs of 30-180 steps, including convolutional, mixture-of-experts and KV-cache families and larger random graphs.","time_limits":{"test":300,"dev":150},"example":{"input":"plan({'temps': {'t0': 4096, 't1': 4096, ...}, 'buffers': {'b0': 4096, ...}, 'steps': [{'name': 'k0', 'op': 'load', 'ins': [], 'out': 't0', 'scratch': None, 'loads': [('b0', 0, 0, 4096)], 'stores': [], 'inplace': []}, ...]})","output":"(['k0', 'k1', ...], {'t0': 0, 't1': 4096, ...}); the grader reports e.g. arena 457,508 bytes vs a lower bound of 342,456 (1.34) for one program and the mean over all programs"},"gpu":false,"description":"In week 2 your compiler gets memory. Global buffers persist, temporaries live in one scratch arena, and loads and stores must stay in order. Write the **memory planner**: for each program, choose the order the steps run in and where every temporary sits in the arena. The leaderboard ranks by **arena size relative to a lower bound, lower is better**.\n\n**Contract.** Define `plan(program) -> (order, offsets)`:\n\n- `order` is a list naming every step exactly once, in the order the steps will run.\n- `offsets` is a dict giving every temporary an `int` byte offset in the arena (non-negative, a multiple of 4).\n\n**A program** is a dict:\n\n- `program[\"temps\"]` maps each temporary's name to its size in bytes.\n- `program[\"buffers\"]` maps each global buffer's name to its size in bytes. Global buffers are not in your arena.\n- `program[\"steps\"]` lists the steps in the order they were written, which is always a valid order. Each step is a dict with:\n  - `name`, plus `op`, a label only;\n  - `ins`, the temporaries it reads;\n  - `out`, the temporary it writes, or `None`;\n  - `scratch`, a temporary it uses only while it runs, or `None`;\n  - `loads` and `stores`, lists of `(buffer, version, lo, hi)`: the step reads or writes bytes `[lo, hi)` of a global buffer;\n  - `inplace`, inputs its output is allowed to overwrite.\n\n**Rules a plan must follow.**\n\n1. **Data:** a step runs after the steps that write its input temporaries.\n2. **Effects:** every global buffer starts at version 0, and each store creates the next version by writing its bytes `[lo, hi)`.\n   - A load of version `v` of bytes `[lo, hi)` runs after every store of version `<= v` that overlaps those bytes, and before every store of version `> v` that overlaps them.\n   - Two stores that overlap run in version order.\n   - Accesses to disjoint bytes are not ordered by these rules. A step that loads and stores the same buffer reads before it writes.\n3. **Liveness:** in your order, a temporary is live from the step that writes it through the last step that reads it. A `scratch` temporary is live only during its own step. Temporaries that are live at the same step must not overlap in the arena. There is one exception: a step's `out` may start at exactly the same offset as an input listed in that step's `inplace`, if this step is the last one in your order to read that input.\n\n**Checking.** The grader first checks the rules. It then runs the program with your order and offsets in a real arena, where each step's output is a deterministic function of everything it reads. It compares every global buffer with a reference run that never reuses memory; any difference fails the plan.\n\n**Score.** Your arena size is `max(offset + size)` over all temporaries. A program's score is `arena / lower_bound`. The lower bound is the most temporary memory that every valid order must hold at once: what one step needs, plus every temporary that is necessarily live across that step. The report shows the bound, your arena and the no-reuse size. The score is the mean over programs, and 1.0 would mean matching the bound everywhere, which is not always possible. A score of at most **4** counts as solved; below that is leaderboard.\n\n**Programs.** Run has 6 programs, and the report names each one's family:\n\n- an MLP;\n- an inception-style block;\n- a transformer;\n- an optimizer step that updates its parameter buffers in place;\n- two random layered graphs.\n\nSubmit has 10 held-out programs of 30 to 180 steps. They include families that are not in Run (convolutional networks, mixture of experts, a KV cache), plus larger random graphs.\n\n**Budget and rules.**\n\n- Total time inside `plan` is capped at 45 s on Run and 90 s on Submit.\n- `random` and `numpy.random` are seeded before every program.\n- Your code may import only `numpy`, `math`, `collections`, `heapq`, `bisect`, `itertools`, `functools`, `random`, `typing`, `dataclasses`, `copy` and `time`, and may use a module only as `module.name`.\n\n**Gates.** The score is set to 999 and the run fails if any of these happen:\n\n- `plan` returns anything but a list of step names and a plain dict of int offsets.\n- The plan breaks a rule.\n- `plan` raises or exits.\n- The time budget runs out.\n- Your code reads files, uses introspection (`globals`, `getattr`/`setattr`, frames, `eval`/`exec`), redefines a built-in name, or assigns to, aliases or reaches into the internals of an imported module.","tags":["compilers","memory-planning","liveness","scheduling","register-allocation","open-ended","leaderboard"],"id":"a6c854a0-d3b6-49cf-8045-a47347e10087","dataset_id":"synthetic","img_type":"full","difficulty":"hard","evaluation_metric":"arena_over_bound","min_eval_metric":4.0,"category":"Compilers","dataset":"Synthetic compiler programs with temporaries and versioned global buffers","title":"Lowest Peak Memory","time_limits_seconds":{"dev":150,"test":300}},{"created_at":"2026-11-01T02:56:13.056000+00:00","type":"general","constraints":["45 CPU seconds for train and threshold per split, all threads and workers counted; 0.25 per hidden image","embed returns (m, d) with 1 <= d <= 128; it is called on one image at a time in a throwaway copy of your process","one threshold, fixed before any hidden image is seen; no pretrained weights, downloads, datasets or file access","source capped at 10000 characters without comments, 300 constants, 400 characters of strings, 900 name uses"],"test_cases":[{"test":"import numpy as np\nif '_E' not in globals():\n    _r = np.random.default_rng(0)\n    _base = _r.normal(size=(14, 4096)) * 0.2 + 0.5\n    _X = np.clip(np.repeat(_base, 5, axis=0) + _r.normal(0, 0.03, (70, 4096)), 0, 1)\n    _y = np.repeat(np.arange(14), 5)\n    train(_X, _y)\n    _E = np.asarray(embed(_X[:1]), dtype=float)\n    _t = float(threshold())\nprint(_E.ndim, _E.shape[0])","expected_output":"2 1"},{"test":"import numpy as np\nif '_E' not in globals():\n    _r = np.random.default_rng(0)\n    _base = _r.normal(size=(14, 4096)) * 0.2 + 0.5\n    _X = np.clip(np.repeat(_base, 5, axis=0) + _r.normal(0, 0.03, (70, 4096)), 0, 1)\n    _y = np.repeat(np.arange(14), 5)\n    train(_X, _y)\n    _E = np.asarray(embed(_X[:1]), dtype=float)\n    _t = float(threshold())\nprint(bool(1 <= _E.shape[1] <= 128 and np.isfinite(_E).all() and np.linalg.norm(_E) > 0))","expected_output":"True"},{"test":"import numpy as np\nif '_E' not in globals():\n    _r = np.random.default_rng(0)\n    _base = _r.normal(size=(14, 4096)) * 0.2 + 0.5\n    _X = np.clip(np.repeat(_base, 5, axis=0) + _r.normal(0, 0.03, (70, 4096)), 0, 1)\n    _y = np.repeat(np.arange(14), 5)\n    train(_X, _y)\n    _E = np.asarray(embed(_X[:1]), dtype=float)\n    _t = float(threshold())\nprint(bool(np.isfinite(_t)))","expected_output":"True"},{"test":"import numpy as np\nif '_E' not in globals():\n    _r = np.random.default_rng(0)\n    _base = _r.normal(size=(14, 4096)) * 0.2 + 0.5\n    _X = np.clip(np.repeat(_base, 5, axis=0) + _r.normal(0, 0.03, (70, 4096)), 0, 1)\n    _y = np.repeat(np.arange(14), 5)\n    train(_X, _y)\n    _E = np.asarray(embed(_X[:1]), dtype=float)\n    _t = float(threshold())\nprint(bool(-1.0 < _t < 0.98))","expected_output":"True"}],"approved_user_libraries":["numpy","scipy","sklearn","torch"],"lower_is_better":false,"data_info":"Olivetti faces from the dataset registry: 40 people, 10 grayscale images each, 64 x 64 pixels, values in [0, 1]. The grader holds the images, and your code cannot load the dataset.\n\nYour code receives 25 people's images per split as flat rows of 4096 values, each already through that split's lens, with person labels shuffled per split. Hidden images arrive one at a time, through the same lens and then with their own random pose, contrast, brightness and noise. Run uses 3 splits and Submit uses 5 others, with different lenses and captures on each split.","time_limits":{"test":480,"dev":300},"gpu":false,"description":"## Recognise Faces You Have Never Seen\n\nA recognition system meets people it was never trained on. Some have just been enrolled with a single photo, and some have never been seen at all. It has to name the first group and refuse to name the second, and it gets one similarity threshold to do both.\n\nYou train on some people from the Olivetti faces. The grader then holds a matching session with other people, using nothing but your embedding and your threshold. The session's photos were not taken the way your training photos were.\n\n### What you write\n\n```python\ndef train(X_train, y_train): ...   # X_train: (n, 4096) floats in [0, 1]; y_train: (n,) integer person labels\ndef embed(X): ...                  # X: (m, 4096); returns (m, d) floats with 1 <= d <= 128\ndef threshold(): ...               # one float, a cosine similarity\n```\n\nReshape a row to `(64, 64)` to get the image. The labels are a fresh shuffle for each split, so they say nothing about who a person is.\n\n### How a session is graded\n\nFaces are held out by person. For each split, your code trains on 25 people, 10 images each, and the other 15 people are hidden. `threshold()` is called once, right after `train`, before your code has seen any hidden image.\n\nEach of the 150 hidden images is then embedded once, and the grader computes cosine similarities between the embeddings. It deals the hidden people 300 times. In each deal, 10 of them are enrolled with one randomly chosen image each (the gallery), and the other 5 are impostors. Every remaining image of an enrolled person, and every image of an impostor, is a probe:\n\n- An enrolled probe is **identified** if its most similar gallery image is its own person and that similarity is at least your threshold.\n- An impostor probe is **rejected** if its similarity to every gallery image is below your threshold.\n\n$$\n\\text{score} = \\frac{1}{2}\\left(\\text{fraction of enrolled probes identified} + \\text{fraction of impostor probes rejected}\\right)\n$$\n\naveraged over deals and splits. **Higher is better**, and the lab is passed at **0.540 or above**. Refusing everything scores exactly 0.5.\n\n### The two kinds of photo conditions\n\n**Each split has its own camera.** Every image in a split, training and hidden, first goes through that split's fixed but unknown lens: a smooth warp of the image, with control points 13 pixels apart and displacements of standard deviation 6 pixels, a smooth brightness gain whose logarithm has standard deviation 0.3 at the control points, and a gamma in the range 0.55 to 1.82.\n\n**Hidden images are also captured less carefully.** Each hidden image, and no training image, then gets its own random pose and exposure:\n\n- a shift of up to 4 pixels in each direction\n- a rotation of up to 8 degrees\n- a scale change of up to 8%\n- contrast multiplied by a factor within 25% of 1, around a mid-grey of 0.5\n- brightness shifted by up to 0.12\n- pixel noise of standard deviation 0.015\n\n### Run and Submit\n\n- **Run** grades 3 splits. It shows per-split results and your printed output, plus the best score any single threshold could have reached and the rank-1 rate with no threshold, so you can see where you are losing.\n- **Submit** grades 5 other splits with other camera and capture draws, and reports only means and rates. Across its splits every person is hidden at least once, so the score does not rest on who happens to be held out.\n\n### Budgets and rules\n\n- `train` and `threshold` together get 45 CPU seconds per split, in a fresh process. CPU time is counted over all threads and all worker processes, so `n_jobs` and `torch.set_num_threads` are allowed but buy no extra compute. Machines differ: the same training has measured anywhere from 19 to 38 CPU seconds, so going over on a slow machine fails the run even if it fit on Run. `time.process_time()` shows your own clock, though it does not include worker processes.\n- `embed` gets 0.25 CPU seconds per image on average and 5 seconds on any one image.\n- `embed` is always called with one image at a time (`m = 1`), in a throwaway copy of your process that is discarded right after the call. Nothing it does carries over to the next image.\n- Libraries: numpy, scipy, sklearn, torch, math, cmath, itertools, functools, collections, heapq, bisect, random, statistics, time, warnings, typing, copy, dataclasses, abc, enum, re. No pretrained weights, downloads, datasets or file access: the grader hands you all the data, so names such as `open`, `load` and `save` are refused, along with `getattr`, `setattr`, `globals` and the modules `os` and `sys`, which would get around that rule.\n- Assigning to an attribute is allowed only on `self`, directly in a method written in a class body, so ordinary classes and `nn.Module`s work. Keep other state in dicts, lists or module-level names.\n- Your source is capped, because this dataset is public and small: 10,000 characters without comments and blank lines, 300 numeric, `True`, `False` or `None` constants (600 characters in all, integers up to 9 digits), 400 characters of string and bytes constants, 900 uses of names, 1400 characters of names you define (each at most 40), 700 characters of keyword-argument names, and 64 items in any one list, tuple, set or dict literal. Comments and docstrings don't count against the string limit.\n- A crash, an all-zero or non-finite embedding, a wrong shape, a dimension that changes between images, a broken budget or cap, or a file written to disk fails the run with a score of 0.\n","tags":["metric-learning","open-set","face-recognition","contrastive","competitive","pml-book"],"id":"a6e4e413-5ed4-4115-b3f5-99f2711119d8","img_type":"full","dataset_id":"olivetti-faces","difficulty":"hard","evaluation_metric":"balanced_open_set_accuracy","min_eval_metric":0.54,"category":"Computer Vision","dataset":"Olivetti faces, held out by person, through a per-split camera and per-image capture","title":"Recognise Faces You Have Never Seen: Best Learned Metric for Open-Set Matching","time_limits_seconds":{"dev":300,"test":480}},{"created_at":"2026-10-26T20:58:00.869000+00:00","type":"general","test_cases":[{"test":"C = {\"workers\": 8, \"gpus_per_worker\": 8, \"prefill_tokens_per_second\": 40000.0, \"attention_tokens\": 131072.0, \"chunk_tokens\": 2048, \"decode_base_s\": 0.02, \"decode_per_sequence_s\": 0.0003, \"decode_per_100k_kv_s\": 0.004, \"max_batch\": 48, \"kv_capacity_tokens\": 900000, \"prefill_pool_cache_tokens_per_worker\": 2000000, \"transfer_fixed_s\": 0.005, \"transfer_per_token_s\": 1.4e-06, \"switch_seconds\": 30.0, \"rebalance_every_s\": 15.0, \"tps_slo\": 25.0, \"ttft_slo_base_s\": 0.4, \"ttft_slo_per_token_s\": 3.3333333333333335e-05}\ndef _w(i, role, cached=0, running=10):\n    if role == \"prefill\":\n        return {\"id\": i, \"role\": \"prefill\", \"status\": \"active\", \"busy\": True}\n    return {\"id\": i, \"role\": \"decode\", \"status\": \"active\", \"running\": running, \"kv_reserved\": 200000,\n            \"kv_capacity\": 900000, \"cached_prefix_tokens\": 300000, \"local_queue\": 0, \"local_queue_new_tokens\": 0,\n            \"awaiting_transfer\": 0, \"iteration_ms\": 32.0, \"cached_tokens\": cached}\ndef _state(n_prefill, cached_on=None, cached=0, backlog=0):\n    ws = [_w(i, \"prefill\") if i < n_prefill else _w(i, \"decode\", cached if i == cached_on else 0) for i in range(8)]\n    return {\"time\": 120.0, \"workers\": ws, \"prefill_queue\": backlog // 50000, \"prefill_queue_new_tokens\": backlog,\n            \"prefill_cached_tokens\": 0, \"recent\": {\"window_seconds\": 60.0, \"finished\": 0, \"ttft_met\": 0,\n            \"tps_met\": 0, \"mean_ttft\": None, \"mean_tps\": None}}\np = Policy(dict(C))\nn = p.rebalance(_state(2))\nprint(isinstance(n, int) and not isinstance(n, bool) and 0 <= n <= 7)","expected_output":"True"},{"test":"C = {\"workers\": 8, \"gpus_per_worker\": 8, \"prefill_tokens_per_second\": 40000.0, \"attention_tokens\": 131072.0, \"chunk_tokens\": 2048, \"decode_base_s\": 0.02, \"decode_per_sequence_s\": 0.0003, \"decode_per_100k_kv_s\": 0.004, \"max_batch\": 48, \"kv_capacity_tokens\": 900000, \"prefill_pool_cache_tokens_per_worker\": 2000000, \"transfer_fixed_s\": 0.005, \"transfer_per_token_s\": 1.4e-06, \"switch_seconds\": 30.0, \"rebalance_every_s\": 15.0, \"tps_slo\": 25.0, \"ttft_slo_base_s\": 0.4, \"ttft_slo_per_token_s\": 3.3333333333333335e-05}\ndef _w(i, role, cached=0, running=10):\n    if role == \"prefill\":\n        return {\"id\": i, \"role\": \"prefill\", \"status\": \"active\", \"busy\": True}\n    return {\"id\": i, \"role\": \"decode\", \"status\": \"active\", \"running\": running, \"kv_reserved\": 200000,\n            \"kv_capacity\": 900000, \"cached_prefix_tokens\": 300000, \"local_queue\": 0, \"local_queue_new_tokens\": 0,\n            \"awaiting_transfer\": 0, \"iteration_ms\": 32.0, \"cached_tokens\": cached}\ndef _state(n_prefill, cached_on=None, cached=0, backlog=0):\n    ws = [_w(i, \"prefill\") if i < n_prefill else _w(i, \"decode\", cached if i == cached_on else 0) for i in range(8)]\n    return {\"time\": 120.0, \"workers\": ws, \"prefill_queue\": backlog // 50000, \"prefill_queue_new_tokens\": backlog,\n            \"prefill_cached_tokens\": 0, \"recent\": {\"window_seconds\": 60.0, \"finished\": 0, \"ttft_met\": 0,\n            \"tps_met\": 0, \"mean_ttft\": None, \"mean_tps\": None}}\np = Policy(dict(C))\np.rebalance(_state(2))\nR = {\"id\": 0, \"arrival\": 120.0, \"session\": \"s1\", \"prompt_tokens\": 3000, \"max_new_tokens\": 1024, \"ttft_slo_s\": 0.5}\nm, w = p.place(R, _state(2))\nprint(m in (\"local\", \"remote\") and w in range(2, 8))","expected_output":"True"},{"test":"C = {\"workers\": 8, \"gpus_per_worker\": 8, \"prefill_tokens_per_second\": 40000.0, \"attention_tokens\": 131072.0, \"chunk_tokens\": 2048, \"decode_base_s\": 0.02, \"decode_per_sequence_s\": 0.0003, \"decode_per_100k_kv_s\": 0.004, \"max_batch\": 48, \"kv_capacity_tokens\": 900000, \"prefill_pool_cache_tokens_per_worker\": 2000000, \"transfer_fixed_s\": 0.005, \"transfer_per_token_s\": 1.4e-06, \"switch_seconds\": 30.0, \"rebalance_every_s\": 15.0, \"tps_slo\": 25.0, \"ttft_slo_base_s\": 0.4, \"ttft_slo_per_token_s\": 3.3333333333333335e-05}\ndef _w(i, role, cached=0, running=10):\n    if role == \"prefill\":\n        return {\"id\": i, \"role\": \"prefill\", \"status\": \"active\", \"busy\": True}\n    return {\"id\": i, \"role\": \"decode\", \"status\": \"active\", \"running\": running, \"kv_reserved\": 200000,\n            \"kv_capacity\": 900000, \"cached_prefix_tokens\": 300000, \"local_queue\": 0, \"local_queue_new_tokens\": 0,\n            \"awaiting_transfer\": 0, \"iteration_ms\": 32.0, \"cached_tokens\": cached}\ndef _state(n_prefill, cached_on=None, cached=0, backlog=0):\n    ws = [_w(i, \"prefill\") if i < n_prefill else _w(i, \"decode\", cached if i == cached_on else 0) for i in range(8)]\n    return {\"time\": 120.0, \"workers\": ws, \"prefill_queue\": backlog // 50000, \"prefill_queue_new_tokens\": backlog,\n            \"prefill_cached_tokens\": 0, \"recent\": {\"window_seconds\": 60.0, \"finished\": 0, \"ttft_met\": 0,\n            \"tps_met\": 0, \"mean_ttft\": None, \"mean_tps\": None}}\np = Policy(dict(C))\np.rebalance(_state(0))\nR = {\"id\": 0, \"arrival\": 120.0, \"session\": \"s1\", \"prompt_tokens\": 2500, \"max_new_tokens\": 1024, \"ttft_slo_s\": 0.4833}\nprint(p.place(R, _state(0))[0])  # no prefill worker exists, so a remote prefill would wait forever","expected_output":"local"},{"test":"C = {\"workers\": 8, \"gpus_per_worker\": 8, \"prefill_tokens_per_second\": 40000.0, \"attention_tokens\": 131072.0, \"chunk_tokens\": 2048, \"decode_base_s\": 0.02, \"decode_per_sequence_s\": 0.0003, \"decode_per_100k_kv_s\": 0.004, \"max_batch\": 48, \"kv_capacity_tokens\": 900000, \"prefill_pool_cache_tokens_per_worker\": 2000000, \"transfer_fixed_s\": 0.005, \"transfer_per_token_s\": 1.4e-06, \"switch_seconds\": 30.0, \"rebalance_every_s\": 15.0, \"tps_slo\": 25.0, \"ttft_slo_base_s\": 0.4, \"ttft_slo_per_token_s\": 3.3333333333333335e-05}\ndef _w(i, role, cached=0, running=10):\n    if role == \"prefill\":\n        return {\"id\": i, \"role\": \"prefill\", \"status\": \"active\", \"busy\": True}\n    return {\"id\": i, \"role\": \"decode\", \"status\": \"active\", \"running\": running, \"kv_reserved\": 200000,\n            \"kv_capacity\": 900000, \"cached_prefix_tokens\": 300000, \"local_queue\": 0, \"local_queue_new_tokens\": 0,\n            \"awaiting_transfer\": 0, \"iteration_ms\": 32.0, \"cached_tokens\": cached}\ndef _state(n_prefill, cached_on=None, cached=0, backlog=0):\n    ws = [_w(i, \"prefill\") if i < n_prefill else _w(i, \"decode\", cached if i == cached_on else 0) for i in range(8)]\n    return {\"time\": 120.0, \"workers\": ws, \"prefill_queue\": backlog // 50000, \"prefill_queue_new_tokens\": backlog,\n            \"prefill_cached_tokens\": 0, \"recent\": {\"window_seconds\": 60.0, \"finished\": 0, \"ttft_met\": 0,\n            \"tps_met\": 0, \"mean_ttft\": None, \"mean_tps\": None}}\np = Policy(dict(C))\np.rebalance(_state(2))\nS = _state(2)\nfor w in S[\"workers\"][2:]:\n    if w[\"id\"] != 6:\n        w.update(running=48, kv_reserved=900000, cached_prefix_tokens=0, iteration_ms=55.0)\n    else:\n        w.update(running=0, kv_reserved=0, cached_prefix_tokens=0, iteration_ms=20.0)\nR = {\"id\": 0, \"arrival\": 120.0, \"session\": \"s3\", \"prompt_tokens\": 2600, \"max_new_tokens\": 1024, \"ttft_slo_s\": 0.4867}\nprint(p.place(R, S)[1])  # every decode worker but 6 is full: no free sequence slots, no free KV memory","expected_output":"6"}],"approved_user_libraries":["numpy","math","collections","itertools","functools","random","copy"],"lower_is_better":false,"data_info":"Synthetic traffic generated inside the grader with a fixed pure-Python generator (no downloads): chat sessions of 2-8 turns with growing context, code-editor sessions of 2-7 turns starting from 40k-120k-token contexts, and agent loops of 5-15 short calls sharing a 6,000-token system prompt, with each kind's session rate changing across phases. Run: two 8-minute traces. Submit: three different 15-minute traces with a held-out phase schedule. The report gives goodput overall, per trace, per traffic kind and per minute, SLO miss rates, the local-prefill share, the mean prefill-pool size and an isolated upper bound.","time_limits":{"test":240,"dev":120},"example":{"input":"place({'id': 812, 'arrival': 241.35, 'session': 's57', 'prompt_tokens': 86412, 'max_new_tokens': 512, 'ttft_slo_s': 3.2804}, state)","output":"('remote', 6)"},"gpu":false,"description":"Serve a mixed stream of LLM requests on a fixed 64-GPU cluster and decide, request by request, where each prompt is prefilled; at the same time decide how many nodes form the prefill pool. The leaderboard ranks by **goodput**: the percentage of requests that meet both their time-to-first-token (TTFT) and their decode-speed SLO, higher is better.\n\n**The cluster.** 8 workers, each an 8-GPU node holding a full replica of a large MoE model. A worker is either a *decode* worker or a *prefill* worker, and you can change the split while traffic runs. Every request is assigned to one decode worker, which generates its output, and is prefilled in one of two ways:\n\n- `\"local\"`: the decode worker prefills the prompt itself. Each decode iteration then also processes a chunk of up to 2048 prompt tokens, so the iteration (and every sequence decoding on that worker) slows down until the prompt is done. Local prompts on one worker are prefilled one at a time, first come first served.\n- `\"remote\"`: the prompt joins the prefill pool's queue (first come first served, served by every prefill worker), and when it is done its KV cache is transferred to the decode worker.\n\n**Physics (exact, deterministic).** Prefilling `n` uncached tokens on top of `c` cached ones costs `n / 40000 * (1 + (c + n/2) / 131072)` seconds of a worker. A decode iteration takes `0.020 + 0.0003 * B + 0.004 * K / 100000` seconds for `B` running sequences holding `K` prompt tokens, plus the chunk time when a local prefill is in progress; each running sequence gets one token per iteration. A decode worker runs at most 48 sequences and holds 900,000 KV tokens; a request reserves `prompt_tokens + max_new_tokens` of them from the moment its local prefill starts (or its transfer starts) until it finishes, and waits in that worker's queue until they are free. A transfer takes `0.005 + 1.4e-6 * prompt_tokens` seconds. Prefix caching: when a request finishes, its decode worker keeps the session's full context (prompt plus output) as a cached prefix in the memory not reserved by running requests, evicting least-recently-used entries; the next turn of that session only prefills what is new if it lands on that worker. Agent sessions also share one 6,000-token system prompt. The prefill pool keeps its own least-recently-used cache of the prompts it prefilled, 2,000,000 tokens per prefill worker. Switching a worker's role drains it first (it finishes what it has, receives nothing new) and then takes it offline for 30 seconds; its cache is lost.\n\n**Traffic.** Multi-turn chat, code-editor sessions with very long contexts, and agent loops of short calls; the mix and the load change over time. Each request's TTFT SLO is `0.4 + prompt_tokens / 30000` seconds and its decode SLO is at least 25 tokens per second (output tokens after the first, divided by the time from the first token to the last). Requests not finished 120 seconds after the trace ends count as misses.\n\n**Contract.** Define `class Policy`:\n\n- `__init__(self, cluster)` receives the facts above as a dict.\n- `rebalance(self, state) -> int` is called at time 0 and then every 15 simulated seconds; return the number of prefill workers you want (0 to 7).\n- `place(self, request, state) -> (mode, worker_id)` is called once per arriving request; `mode` is `\"local\"` or `\"remote\"` and `worker_id` must be an active decode worker. `request` has `id`, `arrival`, `session`, `prompt_tokens`, `max_new_tokens`, `ttft_slo_s` (the output length is unknown).\n- `state` describes the cluster now: `time`; `workers`, one dict per worker with `id`, `role`, `status` (`active`, `draining`, `switching`) and, for decode workers, `running`, `kv_reserved`, `kv_capacity`, `cached_prefix_tokens`, `local_queue`, `local_queue_new_tokens`, `awaiting_transfer`, `iteration_ms` and (inside `place`) `cached_tokens`, how many leading tokens of this request that worker has cached; `prefill_queue`, `prefill_queue_new_tokens`, `prefill_cached_tokens` (the pool's cache hit for this request); `recent`, counts and means of the requests that finished in the last 60 seconds.\n\nYou never see future arrivals. Use numpy and the standard modules math, collections, heapq, itertools, functools, bisect, statistics, random, operator, copy, dataclasses and typing.\n\n**Scoring.** Submit replays three held-out 15-minute traces and averages their goodput; Run replays two 8-minute traces. The report also gives goodput by traffic kind and by minute, the TTFT and decode-SLO miss rates, your share of local prefills, the mean pool size and a loose upper bound (each request alone on an idle cluster). Clearing 70% on Submit counts as solved; everything above that is leaderboard.\n\n**Gates.** The score is set to 0 if `place` returns an unknown mode or a worker that is not an active decode worker, if `rebalance` returns anything but an int in 0..7, if your policy raises, if your policy's total time exceeds 30 seconds (Submit) or 15 seconds (Run), or if your code imports other modules or reaches for interpreter internals (frames, `globals`, the garbage collector, `exec`, files).","tags":["inference","serving","disaggregation","prefill-decode","prefix-caching","scheduling","open-ended","leaderboard"],"id":"aa10c37b-c4f9-4fc1-8df0-e7b0fb10746d","dataset_id":"synthetic","img_type":"full","difficulty":"hard","evaluation_metric":"goodput_pct","min_eval_metric":70.0,"category":"Inference","title":"Best Conditional Disaggregation Policy","dataset":"Simulated chat, code-editor and agent traffic on an 8-node cluster","time_limits_seconds":{"dev":120,"test":240}},{"created_at":"2026-11-01T00:07:04.541000+00:00","type":"general","constraints":["fit <= 60 s per world; predict <= 45 s in total per world; one CPU core, no GPU","predict returns one finite value per pair; the harness clips to [1, 5]","the harness owns all data; source <= 30,000 characters, 800 numeric literals, 4,000 characters of strings"],"test_cases":[{"test":"import numpy as np\n_r = np.random.default_rng(0)\n_M, _N = 60, 40\n_gu = np.arange(_M) % 2\n_gi = np.arange(_N) % 2\n_uu, _ii = np.meshgrid(np.arange(_M), np.arange(_N), indexing='ij')\n_uu, _ii = _uu.ravel(), _ii.ravel()\n_keep = _r.random(_uu.size) < 0.6\n_keep &= ~((_uu == 0) & (_ii == 2))\n_keep &= ~((_uu == 0) & (_ii == 3))\n_yy = np.where(_gu[_uu] == _gi[_ii], 5.0, 1.0)\n_fu = _r.normal(size=(_M, 3))\n_fi = _r.normal(size=(_N, 4))\n_p = fit(_uu[_keep], _ii[_keep], _yy[_keep], _M, _N, _fu, _fi)\n_o = np.asarray(_p(np.array([0, 1, 2]), np.array([5, 6, 7])), dtype=float)\nprint(_o.shape == (3,) and bool(np.isfinite(_o).all()))","expected_output":"True"},{"test":"import numpy as np\n_r = np.random.default_rng(0)\n_M, _N = 60, 40\n_gu = np.arange(_M) % 2\n_gi = np.arange(_N) % 2\n_uu, _ii = np.meshgrid(np.arange(_M), np.arange(_N), indexing='ij')\n_uu, _ii = _uu.ravel(), _ii.ravel()\n_keep = _r.random(_uu.size) < 0.6\n_keep &= ~((_uu == 0) & (_ii == 2))\n_keep &= ~((_uu == 0) & (_ii == 3))\n_yy = np.where(_gu[_uu] == _gi[_ii], 5.0, 1.0)\n_fu = _r.normal(size=(_M, 3))\n_fi = _r.normal(size=(_N, 4))\n_p = fit(_uu[_keep], _ii[_keep], _yy[_keep], _M, _N, _fu, _fi)\n_a = np.asarray(_p(np.array([0]), np.array([2])), dtype=float)[0]\n_b = np.asarray(_p(np.array([0]), np.array([3])), dtype=float)[0]\nprint(bool(_a > _b + 1.0))","expected_output":"True"},{"test":"import numpy as np\n_r = np.random.default_rng(0)\n_M, _N = 60, 40\n_gu = np.arange(_M) % 2\n_gi = np.arange(_N) % 2\n_uu, _ii = np.meshgrid(np.arange(_M), np.arange(_N), indexing='ij')\n_uu, _ii = _uu.ravel(), _ii.ravel()\n_keep = _r.random(_uu.size) < 0.6\n_keep &= ~((_uu == 0) & (_ii == 2))\n_keep &= ~((_uu == 0) & (_ii == 3))\n_yy = np.where(_gu[_uu] == _gi[_ii], 5.0, 1.0)\n_fu = _r.normal(size=(_M, 3))\n_fi = _r.normal(size=(_N, 4))\n_p = fit(_uu[_keep], _ii[_keep], _yy[_keep], _M, _N, _fu, _fi)\n_o = np.asarray(_p(np.repeat(np.arange(10), 2), np.tile(np.array([4, 5]), 10)), dtype=float)\nprint(bool(np.std(_o) > 0.5))","expected_output":"True"}],"lower_is_better":true,"approved_user_libraries":["numpy","scipy","pandas","sklearn","torch","lightgbm","xgboost"],"data_info":"No dataset: every world is generated from a seed inside the harness when it runs. A user with ratings has from a few to more than a thousand of them, about 100 at the median. The most popular items are rated by most users; the median rated item has about 100 ratings.\n\nPassed to fit: users, items (int64 arrays), ratings (float64 whole stars 1-5), n_users, n_items, user_features (float64, n_users x D_u), item_features (float64, n_items x D_i). Columns are anonymous and shuffled per world; some carry signal and some do not. About 6% of users and 6% of items have no ratings but do have a feature row.\n\nRun (validation): 2 worlds, about 3,000 users x 2,000 items, about 350,000 ratings each.\n\nSubmit (test): 4 worlds from other generator families, about 4,000 users x 2,500 items, 560,000 to 640,000 ratings each.\n\nTruth: the expected star count of each user-item pair, known only to the harness. predict is called on every item for about a third of the users with ratings and for every user without ratings.","time_limits":{"test":600,"dev":300},"gpu":false,"description":"## Lowest RMSE on Held-Out Ratings\n\nA catalog has thousands of users and thousands of items, and users have given a small share of those items a star rating from 1 to 5. Predict how much each user would like the items they have not rated. Some of those pairs look like what users usually pick, some are items they would never have opened, and some involve a user or an item that has no ratings at all.\n\n### What you write\n\n```python\ndef fit(users, items, ratings, n_users, n_items, user_features, item_features):\n    ...\n    return predict\n\ndef predict(users, items):          # the function fit returns\n    ...\n    return predictions              # float array, one value per (user, item) pair\n```\n\n- `users`, `items`: integer arrays of the same length, ids from `0` to `n_users - 1` and `0` to `n_items - 1`.\n- `ratings`: float array of whole stars, 1 to 5.\n- `user_features`: float array `(n_users, D_u)`. `item_features`: float array `(n_items, D_i)`. Every user and item has a row, rated or not. The columns are anonymous, and their order and meaning change from one world to the next.\n- `predict` receives batches of up to 200,000 pairs and can be called many times. The harness clips what it returns to `[1, 5]`.\n\n### The worlds\n\nEach world is drawn from a seeded generator inside the harness, so the ratings are synthetic. Item popularity and user activity are heavily skewed, and users are more likely to rate things they expect to enjoy, so ratings are not missing at random. About 6% of users and 6% of items have no ratings.\n\n- **Run**: 2 worlds, about 350,000 ratings each, from two generator families.\n- **Submit**: 4 worlds with up to 640,000 ratings each, from four **other** generator families. The structure of people's tastes, the way taste turns into stars, the noise and the selection all differ from Run, and the numbers of users and items change too.\n\n### How it is graded\n\nThe generator knows each user's **true expected rating** for every item, the average number of stars that user would give it. You are scored against that number, not against one noisy rating, so a score has no outcome noise.\n\nThe harness asks for every item for a hidden set of users, so the pairs it queries say nothing about which ones count. Pairs already in your training data are not scored. The rest fall into four groups, and each world's score is\n\n$$\n\\text{RMSE} = \\sqrt{0.5\\,\\text{MSE}_{\\text{logged}} + 0.3\\,\\text{MSE}_{\\text{uniform}} + 0.1\\,\\text{MSE}_{\\text{cold item}} + 0.1\\,\\text{MSE}_{\\text{cold user}}}\n$$\n\n- **logged**: unrated pairs of users and items that have ratings, weighted by how likely the user was to rate that item. These are the pairs a random held-out split would contain.\n- **uniform**: the same pairs with equal weight, so rarely rated items and unlikely matches count fully.\n- **cold item**: users with ratings, items with none.\n- **cold user**: users with none, items with ratings.\n\nYour score is the mean RMSE over the worlds. **Lower is better**, and the lab is passed at **0.70 or below**. Each world's RMSE and its four group RMSEs are printed.\n\n### Budgets and rules\n\n- `fit` gets 60 s per world and `predict` 45 s in total per world, on one CPU core with no GPU.\n- Libraries: numpy, scipy, pandas, scikit-learn, PyTorch, LightGBM and XGBoost.\n- The harness owns the data. Code that imports `dml_data`, `os`, `sys` or file and serialisation modules, or opens files, is refused. Source is capped at 30,000 characters, 800 numeric literals and 4,000 characters of string literals.\n- An exception, a broken budget, a wrong output shape or a non-finite prediction sets the score to 9.99 and fails the run.\n","tags":["recommender-systems","matrix-factorization","cold-start","missing-not-at-random","competitive","pml-book"],"id":"aabfc481-6464-42f5-b4cc-a4616438fd07","dataset_id":"synthetic","img_type":"full","difficulty":"hard","evaluation_metric":"rmse","min_eval_metric":0.7,"category":"Machine Learning","dataset":"Synthetic ratings worlds (generated in the grader)","title":"Lowest RMSE on Held-Out Ratings","time_limits_seconds":{"dev":300,"test":600}},{"created_at":"2026-10-26T20:43:46.031000+00:00","type":"general","test_cases":[{"test":"def _mini():\n    T = 12\n    regions = [{\"name\": \"us-east\", \"utc_offset\": -5, \"price_multiplier\": 1.0},\n               {\"name\": \"eu-west\", \"utc_offset\": 1, \"price_multiplier\": 1.12}]\n    gpus = {\"H100\": {\"fp8_tflops\": 1979.0, \"memory_gb\": 80.0, \"bandwidth_tbs\": 3.35, \"nvlink\": True, \"on_demand_per_hour\": 3.0},\n            \"B200\": {\"fp8_tflops\": 4500.0, \"memory_gb\": 192.0, \"bandwidth_tbs\": 8.0, \"nvlink\": True, \"on_demand_per_hour\": 6.5}}\n    configs = [{\"id\": 0, \"gpu\": \"H100\", \"tp\": 1, \"mig_slices\": None, \"gpus\": 1.0},\n               {\"id\": 1, \"gpu\": \"H100\", \"tp\": 2, \"mig_slices\": None, \"gpus\": 2.0},\n               {\"id\": 2, \"gpu\": \"B200\", \"tp\": 1, \"mig_slices\": None, \"gpus\": 1.0}]\n    models = [{\"name\": \"chat-8b\", \"kind\": \"decoder\", \"params_b\": 8.0, \"active_b\": 8.0, \"kv_gb_per_seq\": 0.27,\n               \"min_tokens_per_s_per_user\": 50.0, \"latency_budget_ms\": 20.0, \"residency\": None, \"penalty_per_m_tokens\": 1.2}]\n    return {\"tick_minutes\": 10, \"ticks\": T, \"regions\": regions, \"one_way_latency_ms\": [[0.0, 30.0], [30.0, 0.0]],\n            \"gpus\": gpus, \"tier_price_factor\": {\"reserved\": 0.5, \"ondemand\": 1.0, \"spot\": 0.35}, \"reserved_note\": \"\",\n            \"caps\": {\"reserved_gpus\": {\"H100\": 64, \"B200\": 48}, \"live_ondemand_plus_spot_gpus\": {\"H100\": 64, \"B200\": 32},\n                     \"live_spot_gpus\": {\"H100\": 16, \"B200\": 8}},\n            \"spot\": {\"preemption_per_hour\": 0.06, \"notice_ticks\": 1}, \"node_failures_per_gpu_hour\": 2e-05,\n            \"failed_reserved_gpu_returns_after_ticks\": 12, \"cold_start_ticks\": {\"chat-8b\": 1}, \"procurement_ticks\": 1,\n            \"models\": models, \"configs\": configs, \"capacity_tokens_per_s\": {\"chat-8b\": [7273.0, 14460.0, 19016.0]},\n            \"capacity_note\": {\"chat-8b\": [\"ok\", \"ok\", \"ok\"]},\n            \"forecast_tokens_per_s\": {\"chat-8b\": {\"us-east\": [20000.0] * T, \"eu-west\": [15000.0] * T}}}\n\n\ndef _obs(t, demand, replicas):\n    return {\"tick\": t, \"demand_last_tick\": demand, \"served_last_tick\": demand, \"replicas\": replicas,\n            \"reserved_gpus_free\": {}, \"events\": []}\nP = plan(_mini())\nprint(isinstance(P, dict) and isinstance(P.get('reserved', {}), dict) and isinstance(P.get('initial', []), list))","expected_output":"True"},{"test":"def _mini():\n    T = 12\n    regions = [{\"name\": \"us-east\", \"utc_offset\": -5, \"price_multiplier\": 1.0},\n               {\"name\": \"eu-west\", \"utc_offset\": 1, \"price_multiplier\": 1.12}]\n    gpus = {\"H100\": {\"fp8_tflops\": 1979.0, \"memory_gb\": 80.0, \"bandwidth_tbs\": 3.35, \"nvlink\": True, \"on_demand_per_hour\": 3.0},\n            \"B200\": {\"fp8_tflops\": 4500.0, \"memory_gb\": 192.0, \"bandwidth_tbs\": 8.0, \"nvlink\": True, \"on_demand_per_hour\": 6.5}}\n    configs = [{\"id\": 0, \"gpu\": \"H100\", \"tp\": 1, \"mig_slices\": None, \"gpus\": 1.0},\n               {\"id\": 1, \"gpu\": \"H100\", \"tp\": 2, \"mig_slices\": None, \"gpus\": 2.0},\n               {\"id\": 2, \"gpu\": \"B200\", \"tp\": 1, \"mig_slices\": None, \"gpus\": 1.0}]\n    models = [{\"name\": \"chat-8b\", \"kind\": \"decoder\", \"params_b\": 8.0, \"active_b\": 8.0, \"kv_gb_per_seq\": 0.27,\n               \"min_tokens_per_s_per_user\": 50.0, \"latency_budget_ms\": 20.0, \"residency\": None, \"penalty_per_m_tokens\": 1.2}]\n    return {\"tick_minutes\": 10, \"ticks\": T, \"regions\": regions, \"one_way_latency_ms\": [[0.0, 30.0], [30.0, 0.0]],\n            \"gpus\": gpus, \"tier_price_factor\": {\"reserved\": 0.5, \"ondemand\": 1.0, \"spot\": 0.35}, \"reserved_note\": \"\",\n            \"caps\": {\"reserved_gpus\": {\"H100\": 64, \"B200\": 48}, \"live_ondemand_plus_spot_gpus\": {\"H100\": 64, \"B200\": 32},\n                     \"live_spot_gpus\": {\"H100\": 16, \"B200\": 8}},\n            \"spot\": {\"preemption_per_hour\": 0.06, \"notice_ticks\": 1}, \"node_failures_per_gpu_hour\": 2e-05,\n            \"failed_reserved_gpu_returns_after_ticks\": 12, \"cold_start_ticks\": {\"chat-8b\": 1}, \"procurement_ticks\": 1,\n            \"models\": models, \"configs\": configs, \"capacity_tokens_per_s\": {\"chat-8b\": [7273.0, 14460.0, 19016.0]},\n            \"capacity_note\": {\"chat-8b\": [\"ok\", \"ok\", \"ok\"]},\n            \"forecast_tokens_per_s\": {\"chat-8b\": {\"us-east\": [20000.0] * T, \"eu-west\": [15000.0] * T}}}\n\n\ndef _obs(t, demand, replicas):\n    return {\"tick\": t, \"demand_last_tick\": demand, \"served_last_tick\": demand, \"replicas\": replicas,\n            \"reserved_gpus_free\": {}, \"events\": []}\nP = plan(_mini())\na = react(_obs(0, None, []))\nprint(a is None or isinstance(a, list))","expected_output":"True"},{"test":"def _mini():\n    T = 12\n    regions = [{\"name\": \"us-east\", \"utc_offset\": -5, \"price_multiplier\": 1.0},\n               {\"name\": \"eu-west\", \"utc_offset\": 1, \"price_multiplier\": 1.12}]\n    gpus = {\"H100\": {\"fp8_tflops\": 1979.0, \"memory_gb\": 80.0, \"bandwidth_tbs\": 3.35, \"nvlink\": True, \"on_demand_per_hour\": 3.0},\n            \"B200\": {\"fp8_tflops\": 4500.0, \"memory_gb\": 192.0, \"bandwidth_tbs\": 8.0, \"nvlink\": True, \"on_demand_per_hour\": 6.5}}\n    configs = [{\"id\": 0, \"gpu\": \"H100\", \"tp\": 1, \"mig_slices\": None, \"gpus\": 1.0},\n               {\"id\": 1, \"gpu\": \"H100\", \"tp\": 2, \"mig_slices\": None, \"gpus\": 2.0},\n               {\"id\": 2, \"gpu\": \"B200\", \"tp\": 1, \"mig_slices\": None, \"gpus\": 1.0}]\n    models = [{\"name\": \"chat-8b\", \"kind\": \"decoder\", \"params_b\": 8.0, \"active_b\": 8.0, \"kv_gb_per_seq\": 0.27,\n               \"min_tokens_per_s_per_user\": 50.0, \"latency_budget_ms\": 20.0, \"residency\": None, \"penalty_per_m_tokens\": 1.2}]\n    return {\"tick_minutes\": 10, \"ticks\": T, \"regions\": regions, \"one_way_latency_ms\": [[0.0, 30.0], [30.0, 0.0]],\n            \"gpus\": gpus, \"tier_price_factor\": {\"reserved\": 0.5, \"ondemand\": 1.0, \"spot\": 0.35}, \"reserved_note\": \"\",\n            \"caps\": {\"reserved_gpus\": {\"H100\": 64, \"B200\": 48}, \"live_ondemand_plus_spot_gpus\": {\"H100\": 64, \"B200\": 32},\n                     \"live_spot_gpus\": {\"H100\": 16, \"B200\": 8}},\n            \"spot\": {\"preemption_per_hour\": 0.06, \"notice_ticks\": 1}, \"node_failures_per_gpu_hour\": 2e-05,\n            \"failed_reserved_gpu_returns_after_ticks\": 12, \"cold_start_ticks\": {\"chat-8b\": 1}, \"procurement_ticks\": 1,\n            \"models\": models, \"configs\": configs, \"capacity_tokens_per_s\": {\"chat-8b\": [7273.0, 14460.0, 19016.0]},\n            \"capacity_note\": {\"chat-8b\": [\"ok\", \"ok\", \"ok\"]},\n            \"forecast_tokens_per_s\": {\"chat-8b\": {\"us-east\": [20000.0] * T, \"eu-west\": [15000.0] * T}}}\n\n\ndef _obs(t, demand, replicas):\n    return {\"tick\": t, \"demand_last_tick\": demand, \"served_last_tick\": demand, \"replicas\": replicas,\n            \"reserved_gpus_free\": {}, \"events\": []}\nP = plan(_mini())\na = react(_obs(1, {'chat-8b': {'us-east': 90000.0, 'eu-west': 60000.0}}, [])) or []\nprint(any(isinstance(x, dict) and x.get('op') == 'launch' for x in a))","expected_output":"True"}],"approved_user_libraries":["numpy","math","random","collections"],"lower_is_better":true,"data_info":"No data files. The harness generates one week of traffic per model and region (daily and weekly cycles, slow growth, correlated noise, surges absent from the forecast) and hands plan() the forecast plus every price, cap, latency and capacity table. Run: seed 11. Submit: a different hidden week with more noise, three surges and a 12-hour spot shortage in one region. The report lists the bill by tier, SLA penalties, served and unmet percentages, utilisation and cross-region share per model, refused launches, preemptions, failures and a loose lower bound (every token at the cheapest spot price, perfectly packed).","time_limits":{"test":180,"dev":120},"example":{"input":"plan(scenario) once, then react(obs) at every tick, e.g. obs['demand_last_tick']['chat-8b']['us-east'] = 31250.0","output":"plan -> {'reserved': {'us-east/B200': 6}, 'initial': [{'model': 'chat-8b', 'region': 'us-east', 'config': 12, 'tier': 'reserved'}, ...]}; react -> [{'op': 'launch', 'model': 'chat-8b', 'region': 'us-east', 'config': 8, 'tier': 'spot'}, {'op': 'stop', 'id': 41}]"},"gpu":false,"description":"Run the GPU fleet behind four models in four regions for one simulated week, and pay as little as possible while serving the traffic. The leaderboard ranks the **weekly bill in dollars** (GPU spend plus SLA penalties), lower is better. Clearing **$30,000** counts as solved; everything below that is leaderboard.\n\n**The world.** Time moves in 10-minute ticks (1,008 per week). Regions: `us-east` (UTC-5, prices x1.00), `us-west` (UTC-8, x1.04), `eu-west` (UTC+1, x1.12), `ap-northeast` (UTC+9, x1.20). Moving a request between regions adds 5 ms one way per time zone of separation.\n\nGPUs (FP8 dense compute, memory, bandwidth, on-demand price per GPU-hour before the region multiplier):\n- L4: 242 TFLOPS, 24 GB, 0.30 TB/s, $0.85\n- H100: 1,979 TFLOPS, 80 GB, 3.35 TB/s, $3.00\n- H200: 1,979 TFLOPS, 141 GB, 4.80 TB/s, $3.70\n- B200: 4,500 TFLOPS, 192 GB, 8.00 TB/s, $6.50\n\nThree ways to buy GPUs: **reserved** (0.50 x on-demand, committed in `plan()` for the whole week and billed whether used or not), **on-demand** (1.00 x) and **spot** (0.35 x, preempted at random about 6% per replica-hour with one tick of notice, and in short supply). Each region caps live on-demand plus spot GPUs and spot GPUs per type; launches beyond a cap, or onto reserved GPUs you do not have free, are refused and reported back to you.\n\nModels (weights at FP8, per-user decode speed SLO, extra one-way latency the model tolerates, penalty per million unmet tokens):\n- `embed-2b`: 2B encoder, no speed SLO, 100 ms, $0.04\n- `chat-8b`: 8B dense, 50 tokens/s, 20 ms, $1.20\n- `dense-70b`: 70B dense, 30 tokens/s, 35 ms, $4.00; traffic from eu-west must be served in eu-west\n- `moe-235b-a22b`: 235B total with 22B active, 40 tokens/s, 45 ms, $3.50\n\nA replica is one model on one **config**: a GPU type with tensor parallelism 1, 2, 4 or 8 (L4 has no NVLink, so only 1), or an H100 MIG slice of 1, 2 or 3 sevenths. `scenario[\"capacity_tokens_per_s\"][model][config]` gives each replica's tokens per second at the model's SLO; 0 means the config cannot serve the model (the weights plus 50% KV headroom do not fit, or the speed SLO cannot be held) and `scenario[\"capacity_note\"]` says why. A new replica starts serving after its cold start (`scenario[\"cold_start_ticks\"]`, 1 to 3 ticks by model size) plus one procurement tick unless it runs on reserved GPUs. Nodes fail at about 1 per 50,000 GPU-hours; a failed reserved GPU comes back after 12 ticks.\n\n**Routing (fixed).** Each tick the harness first serves every region's demand from that region's ready replicas. What is left goes to other regions in order of increasing latency, only within the model's latency budget and never out of a residency region, using their spare capacity. Anything still left is unmet.\n\n**Contract.**\n- `plan(scenario) -> {\"reserved\": {\"us-east/H100\": 8, ...}, \"initial\": [launch, ...]}` sees the week's forecast (`scenario[\"forecast_tokens_per_s\"][model][region]`, 1,008 values) and every table above. `initial` replicas are ready at tick 0.\n- `react(obs) -> [action, ...]` is called every tick before serving. `obs` holds `tick`, `demand_last_tick` and `served_last_tick` (tokens/s per model and region, `None` at tick 0), your `replicas` (id, model, region, config, tier, ready, tokens_per_s), `reserved_gpus_free`, and `events` (preemption notices, preemptions, node failures, refused launches).\n- A launch is `{\"op\": \"launch\", \"model\": ..., \"region\": ..., \"config\": id, \"tier\": \"reserved\" | \"ondemand\" | \"spot\"}` (without `op` inside `initial`); a stop is `{\"op\": \"stop\", \"id\": replica_id}`. At most 64 actions per tick.\n\n**Score.** `weekly_cost` = reserved GPUs x their hourly price x 168 + on-demand and spot replica time (billed from launch, cold start included, until stopped, preempted or failed) + unmet tokens x the model's penalty. Real traffic is not the forecast: it is noisy and contains surges the forecast does not show. Run plays one week; Submit plays a different hidden week with more noise, more surges and a spot shortage in one region. Budgets: 10 s for `plan`, 40 s for all `react` calls together.\n\n**Gates.** The score becomes $1,000,000,000 and the run fails if `plan` or `react` returns something malformed, launches a config that cannot serve the model, reserves more than a region allows, sends more than 64 actions in a tick, raises or exits, runs over budget, or reaches outside its arguments (frames, `gc`, `inspect`, `sys`, `os`, `getattr`, files, threads, or replacing numpy, json or builtins). Use numpy, math, random, collections and your own state.","tags":["inference","capacity-planning","autoscaling","multi-region","gpu","spot","open-ended","leaderboard"],"id":"aaef1382-ca50-4a03-a2e3-1871b20e32d8","dataset_id":"synthetic","img_type":"full","difficulty":"hard","evaluation_metric":"weekly_cost","min_eval_metric":30000.0,"category":"Inference","title":"Cheapest Fleet That Meets the SLA","dataset":"Simulated week of multi-region inference traffic","time_limits_seconds":{"dev":120,"test":180}},{"created_at":"2026-11-01T00:03:40.060000+00:00","type":"general","constraints":["Your code may spend 240 s on Run and 420 s on Submit in total","Slates hold distinct live item ids; recommend returns shape (len(user_ids), slate_size)","numpy, scipy, scikit-learn and a short list of standard modules only; no files","At most 20,000 characters of source, 300 numeric literals and 2,000 characters of strings"],"test_cases":[{"test":"import numpy as np\n_r = Recommender(40, 60, np.zeros((60, 4)), 3, 100)\n_s = np.asarray(_r.recommend(np.arange(8), np.arange(20)))\nprint(_s.shape == (8, 3) and _s.dtype.kind in 'iu' and bool(np.isin(_s, np.arange(20)).all()) and all(len(set(row)) == 3 for row in _s.tolist()))","expected_output":"True"},{"test":"\nimport numpy as np\nnp.random.seed(0)\n_rng = np.random.default_rng(0)\n_F = _rng.normal(size=(60, 4))\n_T = 400\n_rec = Recommender(40, 60, _F.copy(), 3, _T)\ndef _play(rounds, live):\n    for _ in range(rounds):\n        _u = _rng.choice(40, 8, replace=False)\n        _s = np.asarray(_rec.recommend(_u.copy(), live.copy()))\n        _p = np.where((_u[:, None] < 20) == (_s < 10), 0.7, 0.02)\n        _p[_s >= 20] = 0.02\n        _c = (_rng.random(_s.shape) < _p).astype(np.int64)\n        _rec.update(_u.copy(), _s.copy(), _c)\n_play(40, np.arange(30))\nprint('ok')","expected_output":"ok"},{"test":"\nimport numpy as np\nnp.random.seed(0)\n_rng = np.random.default_rng(0)\n_F = _rng.normal(size=(60, 4))\n_T = 400\n_rec = Recommender(40, 60, _F.copy(), 3, _T)\ndef _play(rounds, live):\n    for _ in range(rounds):\n        _u = _rng.choice(40, 8, replace=False)\n        _s = np.asarray(_rec.recommend(_u.copy(), live.copy()))\n        _p = np.where((_u[:, None] < 20) == (_s < 10), 0.7, 0.02)\n        _p[_s >= 20] = 0.02\n        _c = (_rng.random(_s.shape) < _p).astype(np.int64)\n        _rec.update(_u.copy(), _s.copy(), _c)\n_play(_T - 40, np.arange(20))\n_a = np.asarray(_rec.recommend(np.arange(0, 20), np.arange(20)))\n_b = np.asarray(_rec.recommend(np.arange(20, 40), np.arange(20)))\n_m = (float((_a < 10).mean()) + float((_b >= 10).mean())) / 2\nprint(_m > 0.75)","expected_output":"True"}],"lower_is_better":false,"approved_user_libraries":["numpy","scipy","sklearn"],"data_info":"No dataset: the harness generates every world from seeded random draws and hides the latent vectors.\n\nEach world gives Recommender n_users, n_items, item_features (float array, n_items by n_features), slate_size and n_rounds. Each round the harness calls recommend(user_ids, live_items) then update(user_ids, slates, clicks).\n\nRun plays 3 worlds, each with 1,000 rounds, 128 users per round and slates of 5:\n1. 2,000 users, about 1,500 items, about 200 live at a time, weakly informative features\n2. 2,000 users, about 5,400 items, about 400 live, short-lived items, features that carry no signal\n3. 2,000 users, about 1,850 items, about 200 live, items that fade as they age, weakly informative features\n\nSubmit plays 6 hidden worlds with different seeds and shapes: 1,200 to 5,000 users, about 1,200 to 6,000 items, slates of 4 to 8, and different read-down curves, churn rates and feature quality.","time_limits":{"test":600,"dev":360},"gpu":false,"description":"## Most Clicks from a Simulated User Population\n\nYou run the recommender of a simulated video site. Every round a batch of users opens the site, and for each one you choose a short ordered **slate** of items from the catalog. Users click or do not click. You only ever learn about what you showed: if an item was never on a user's slate, you never find out whether they would have liked it, and everything you train on next round was caused by what you recommended this round.\n\nGet as many clicks as you can. Any method is allowed.\n\n### What you write\n\n```python\nclass Recommender:\n    def __init__(self, n_users, n_items, item_features, slate_size, n_rounds):\n        ...\n\n    def recommend(self, user_ids, live_items):\n        # user_ids:   int array, shape (B,)  the users visiting this round\n        # live_items: int array, shape (L,)  sorted ids of the items in the catalog this round\n        # return:     int array, shape (B, slate_size), one row per user, slot 0 first\n        ...\n\n    def update(self, user_ids, slates, clicks):\n        # called right after recommend with the same user_ids and your slates\n        # clicks: int array, shape (B, slate_size), 1 where that user clicked that slot\n        ...\n```\n\n`item_features` is a float array of shape `(n_items, n_features)`, one row for every item that will ever exist in this world, including items that have not arrived yet. A new `Recommender` is built for every world, and the harness seeds `np.random` and `random` before building it.\n\n### The world\n\nUsers and items have hidden preference vectors, and a user's chance of liking an item depends on them. What you can rely on:\n\n- Users come back at very different rates: some visit constantly, many rarely, and in some worlds new users only turn up late.\n- The catalog turns over. New items keep arriving and old ones retire, so `live_items` changes every round, and an id that left never returns.\n- What people like and how popular an item is both move over time.\n- People read down a slate and may stop. A click in a low slot is rarer than the same item would get at the top, and no click there can mean nobody looked.\n- `item_features` are noisy side information. How much they say differs from world to world, and in some worlds they say nothing.\n\n### How it is graded\n\nThe harness knows every user's true click probability for every live item at every moment, and scores **expected clicks**, so a lucky click does not move your score. Over the **second half** of each world's rounds it adds up the expected clicks of your slates and of an **oracle** that knows the true probabilities and puts the best items in the best slots. A world's score is\n\n$$\\text{score} = 100 \\times \\frac{\\text{expected clicks of your slates}}{\\text{expected clicks of the oracle}}$$\n\nand your final score is the mean over worlds. **Higher is better**, and the lab is passed at **50 or above**. The first half is not scored, but your recommender plays it and learns from it, and the clicks are real data either way. The report also shows, for each world, what random slates would have scored and what the single best list shown to everyone would have scored with perfect knowledge of the probabilities.\n\n- **Run** plays 3 worlds.\n- **Submit** plays 6 hidden worlds with different seeds and different shapes (up to 5,000 users, up to about 6,000 items, slates of 4 to 8).\n\n### Budgets and rules\n\n- Your code may spend **240 s** in total on Run and **420 s** on Submit across all worlds and all calls.\n- Every row of a slate must hold distinct ids from `live_items`.\n- Libraries: numpy, scipy, scikit-learn and the standard library modules math, random, collections, heapq, bisect, itertools, functools, typing, dataclasses and time. No files, no other imports.\n- Your source may be at most 20,000 characters, with at most 300 numeric literals (none above 1e12) and 2,000 characters of string literals, so a table of remembered results will not fit.\n- A wrong shape or type, an item that is not live, a repeated item in a slate, an exception or a broken budget sets your score to 0 and fails the run.\n","tags":["recommender systems","exploration","feedback loop","cold start","competitive","pml-book"],"id":"ab24eb80-9b60-42ce-a654-6cc03875e1d2","img_type":"full","dataset_id":"synthetic","difficulty":"hard","evaluation_metric":"clicks_pct_of_oracle","min_eval_metric":50.0,"category":"Machine Learning","title":"Most Clicks from a Simulated User Population","dataset":"Simulated users and items (generated inside the grader)","time_limits_seconds":{"dev":360,"test":600}},{"created_at":"2026-10-27T20:07:47.612000+00:00","type":"general","test_cases":[{"test":"src = codegen(type('P', (), dict(name='t', heads=2, kv_heads=1, q_len=8, kv_len=8, head_dim=8, causal=False, scale=0.35, threads=4, uir=''))())\nprint(isinstance(src, str) and 'attention' in src)","expected_output":"True"},{"test":"\nimport os as _ca_o, subprocess as _ca_sp, ctypes as _ca_ct, tempfile as _ca_tf, time as _ca_ti\nimport numpy as _ca_np\n_ca_o.environ.setdefault(\"OMP_NUM_THREADS\", \"4\"); _ca_o.environ[\"OMP_NUM_THREADS\"] = \"4\"; _ca_o.environ[\"OMP_THREAD_LIMIT\"] = \"4\"\nclass _ca_Prog:\n    def __init__(self, H, Hkv, Nq, Nk, D, causal, scale):\n        self.name, self.heads, self.kv_heads, self.q_len, self.kv_len = \"test\", H, Hkv, Nq, Nk\n        self.head_dim, self.causal, self.scale, self.threads, self.uir = D, causal, scale, 4, \"\"\ndef _ca_al(n):\n    b = _ca_np.empty(n + 16, _ca_np.float32); off = (-b.ctypes.data % 64) // 4\n    return b[off:off + n]\ndef _ca_build(src):\n    d = _ca_tf.mkdtemp(); c = _ca_o.path.join(d, \"k.c\"); so = _ca_o.path.join(d, \"k.so\")\n    open(c, \"w\").write(src)\n    _ca_sp.run([\"gcc\", \"-O3\", \"-march=x86-64-v3\", \"-fno-math-errno\", \"-fopenmp\", \"-std=gnu11\", \"-shared\", \"-fPIC\",\n             \"-o\", so, c, \"-lm\"], check=True, capture_output=True)\n    f = _ca_ct.CDLL(so).attention; f.restype = None; f.argtypes = [_ca_ct.c_void_p] * 4\n    return f\ndef _ca_io(H, Hkv, Nq, Nk, D, seed):\n    r = _ca_np.random.default_rng(seed)\n    q, k, v, o = _ca_al(H * Nq * D), _ca_al(Hkv * Nk * D), _ca_al(Hkv * Nk * D), _ca_al(H * Nq * D)\n    q[:] = r.standard_normal(q.size) * 1.5; k[:] = r.standard_normal(k.size); v[:] = r.standard_normal(v.size)\n    o.fill(_ca_np.nan)\n    return q, k, v, o\ndef _ca_ref(q, k, v, H, Hkv, Nq, Nk, D, causal, scale):\n    Q = q.reshape(H, Nq, D).astype(_ca_np.float64)\n    K = _ca_np.repeat(k.reshape(Hkv, Nk, D).astype(_ca_np.float64), H // Hkv, axis=0)\n    V = _ca_np.repeat(v.reshape(Hkv, Nk, D).astype(_ca_np.float64), H // Hkv, axis=0)\n    S = Q @ K.transpose(0, 2, 1) * scale\n    if causal:\n        S = _ca_np.where(_ca_np.arange(Nk)[None, :] <= _ca_np.arange(Nq)[:, None], S, -_ca_np.inf)\n    S -= S.max(-1, keepdims=True); P = _ca_np.exp(S); P /= P.sum(-1, keepdims=True)\n    return (P @ V).reshape(-1)\ndef _ca_check(H, Hkv, Nq, Nk, D, causal, scale):\n    f = _ca_build(codegen(_ca_Prog(H, Hkv, Nq, Nk, D, causal, scale)))\n    q, k, v, o = _ca_io(H, Hkv, Nq, Nk, D, 7)\n    f(q.ctypes.data, k.ctypes.data, v.ctypes.data, o.ctypes.data)\n    return bool(_ca_np.all(_ca_np.isfinite(o))) and float(_ca_np.max(_ca_np.abs(o - _ca_ref(q, k, v, H, Hkv, Nq, Nk, D, causal, scale)))) <= 1e-3\n\nprint(_ca_check(2, 1, 19, 19, 16, True, 0.3) and _ca_check(4, 2, 5, 33, 24, False, 0.2))","expected_output":"True"},{"test":"\nimport os as _ca_o, subprocess as _ca_sp, ctypes as _ca_ct, tempfile as _ca_tf, time as _ca_ti\nimport numpy as _ca_np\n_ca_o.environ.setdefault(\"OMP_NUM_THREADS\", \"4\"); _ca_o.environ[\"OMP_NUM_THREADS\"] = \"4\"; _ca_o.environ[\"OMP_THREAD_LIMIT\"] = \"4\"\nclass _ca_Prog:\n    def __init__(self, H, Hkv, Nq, Nk, D, causal, scale):\n        self.name, self.heads, self.kv_heads, self.q_len, self.kv_len = \"test\", H, Hkv, Nq, Nk\n        self.head_dim, self.causal, self.scale, self.threads, self.uir = D, causal, scale, 4, \"\"\ndef _ca_al(n):\n    b = _ca_np.empty(n + 16, _ca_np.float32); off = (-b.ctypes.data % 64) // 4\n    return b[off:off + n]\ndef _ca_build(src):\n    d = _ca_tf.mkdtemp(); c = _ca_o.path.join(d, \"k.c\"); so = _ca_o.path.join(d, \"k.so\")\n    open(c, \"w\").write(src)\n    _ca_sp.run([\"gcc\", \"-O3\", \"-march=x86-64-v3\", \"-fno-math-errno\", \"-fopenmp\", \"-std=gnu11\", \"-shared\", \"-fPIC\",\n             \"-o\", so, c, \"-lm\"], check=True, capture_output=True)\n    f = _ca_ct.CDLL(so).attention; f.restype = None; f.argtypes = [_ca_ct.c_void_p] * 4\n    return f\ndef _ca_io(H, Hkv, Nq, Nk, D, seed):\n    r = _ca_np.random.default_rng(seed)\n    q, k, v, o = _ca_al(H * Nq * D), _ca_al(Hkv * Nk * D), _ca_al(Hkv * Nk * D), _ca_al(H * Nq * D)\n    q[:] = r.standard_normal(q.size) * 1.5; k[:] = r.standard_normal(k.size); v[:] = r.standard_normal(v.size)\n    o.fill(_ca_np.nan)\n    return q, k, v, o\ndef _ca_ref(q, k, v, H, Hkv, Nq, Nk, D, causal, scale):\n    Q = q.reshape(H, Nq, D).astype(_ca_np.float64)\n    K = _ca_np.repeat(k.reshape(Hkv, Nk, D).astype(_ca_np.float64), H // Hkv, axis=0)\n    V = _ca_np.repeat(v.reshape(Hkv, Nk, D).astype(_ca_np.float64), H // Hkv, axis=0)\n    S = Q @ K.transpose(0, 2, 1) * scale\n    if causal:\n        S = _ca_np.where(_ca_np.arange(Nk)[None, :] <= _ca_np.arange(Nq)[:, None], S, -_ca_np.inf)\n    S -= S.max(-1, keepdims=True); P = _ca_np.exp(S); P /= P.sum(-1, keepdims=True)\n    return (P @ V).reshape(-1)\ndef _ca_check(H, Hkv, Nq, Nk, D, causal, scale):\n    f = _ca_build(codegen(_ca_Prog(H, Hkv, Nq, Nk, D, causal, scale)))\n    q, k, v, o = _ca_io(H, Hkv, Nq, Nk, D, 7)\n    f(q.ctypes.data, k.ctypes.data, v.ctypes.data, o.ctypes.data)\n    return bool(_ca_np.all(_ca_np.isfinite(o))) and float(_ca_np.max(_ca_np.abs(o - _ca_ref(q, k, v, H, Hkv, Nq, Nk, D, causal, scale)))) <= 1e-3\n\n_ca_NAIVE_C = \"\"\"\n#include <math.h>\n#include <stdlib.h>\nvoid attention(const float* q, const float* k, const float* v, float* out) {\n    float* s = (float*)malloc(sizeof(float) * 256);\n    for (int h = 0; h < 4; h++) for (int i = 0; i < 256; i++) {\n        const float* qi = q + (h * 256 + i) * 64; float m = -INFINITY, l = 0.0f;\n        for (int j = 0; j < 256; j++) { float d = 0.0f; for (int c = 0; c < 64; c++) d += qi[c] * k[(h * 256 + j) * 64 + c];\n            s[j] = d * 0.125f; if (s[j] > m) m = s[j]; }\n        for (int j = 0; j < 256; j++) { s[j] = expf(s[j] - m); l += s[j]; }\n        for (int c = 0; c < 64; c++) { float a = 0.0f; for (int j = 0; j < 256; j++) a += s[j] * v[(h * 256 + j) * 64 + c];\n            out[(h * 256 + i) * 64 + c] = a / l; }\n    }\n    free(s);\n}\n\"\"\"\ndef _ca_time(f, H, Hkv, Nq, Nk, D):\n    ts = []\n    for rep in range(7):\n        q, k, v, o = _ca_io(H, Hkv, Nq, Nk, D, rep)\n        t = _ca_ti.perf_counter(); f(q.ctypes.data, k.ctypes.data, v.ctypes.data, o.ctypes.data); ts.append(_ca_ti.perf_counter() - t)\n    return sorted(ts)[3]\n\nyours = _ca_time(_ca_build(codegen(_ca_Prog(4, 4, 256, 256, 64, False, 0.125))), 4, 4, 256, 256, 64)\nnaive = _ca_time(_ca_build(_ca_NAIVE_C), 4, 4, 256, 256, 64)\nprint(naive / yours >= 2.0)","expected_output":"True"}],"lower_is_better":false,"approved_user_libraries":["numpy","math","collections","itertools","functools"],"data_info":"No dataset: inputs are standard-normal float32 tensors drawn fresh for every call (q scaled by 1.5). Run has 5 attention programs and Submit 8 held-out ones; the reference is PyTorch's CPU scaled_dot_product_attention timed in the same container.","time_limits":{"test":300,"dev":150},"example":{"input":"codegen(Program('mha_256_d64', heads=4, kv_heads=4, q_len=256, kv_len=256, head_dim=64, causal=False, scale=0.125))","output":"a str of C source defining void attention(const float* q, const float* k, const float* v, float* out); the report then shows e.g. 'mha_256_d64  torch 0.30 ms  yours 0.22 ms  speedup 1.36'"},"gpu":false,"description":"You are writing the back end of an ML compiler. For each attention program your `codegen` returns C source. The grader compiles it, checks every result, and races it against PyTorch's fused CPU attention (`torch.nn.functional.scaled_dot_product_attention`) on the same machine, with the same thread budget and the same instruction set. The leaderboard ranks by **geometric-mean speedup over PyTorch, higher is better**. 1.0 means you match PyTorch.\n\n**Contract.** Define `codegen(program) -> str`. The string is C (gnu11) that defines\n\n```c\nvoid attention(const float* q, const float* k, const float* v, float* out);\n```\n\n`program` has these attributes:\n\n- `name`, `heads` (H), `kv_heads` (Hkv, divides H), `q_len` (Nq), `kv_len` (Nk), `head_dim` (D).\n- `causal` (bool) and `scale` (float). Causal programs are square (`q_len == kv_len`), and query `i` sees keys `0..i`.\n- `threads`, which is 4.\n- `uir`: the same program as `.uir` text in the course's UOp format. In that text, `reduce x %j : op=add` reduces over the range `%j`, `-inf` is negative infinity, and `exp2` is the week-5 composite.\n\n**Layouts.** `q` is `[H][Nq][D]`; `k` and `v` are `[Hkv][Nk][D]`; `out` is `[H][Nq][D]`. All are row-major float32, 64-byte aligned. Query head `h` uses kv head `h // (H / Hkv)`.\n\nThe output is `out[h][i] = sum_j softmax_j(scale * dot(q[h][i], k[g][j])) * v[g][j]`, over the visible keys `j`.\n\n**How it is compiled and run.**\n\n- Compile command: `gcc -O3 -march=x86-64-v3 -fno-math-errno -fopenmp -std=gnu11 -shared -fPIC ... -lm`.\n- Instruction set: AVX2 + FMA and nothing beyond. Grading hosts vary (AMD and Intel x86-64 servers); AVX-512 is never enabled.\n- Threads come only from OpenMP, at most 4 for the whole process. The grader sets `OMP_NUM_THREADS=4` and `OMP_THREAD_LIMIT=4`, and requests for more are capped.\n- Headers: only `math.h stdlib.h string.h stdint.h stddef.h float.h stdbool.h limits.h immintrin.h x86intrin.h omp.h stdatomic.h assert.h`.\n- The kernel may not do I/O, create processes, use signals, read the environment, change scheduling, use inline assembly, or create threads any other way. That rules out `pthread_*`, `#pragma omp teams/target`, `_Pragma`, token pasting `##`, and constructors or sections.\n- Each program is compiled once and its library stays loaded, so state may persist between calls.\n\n**Correctness, on every call.**\n\n- Inputs are fresh standard-normal values on every call (`q` scaled by 1.5), so nothing can be cached across calls.\n- Every output must be written and finite, within an absolute error of **0.001** of a float32 reference.\n- All work must be finished when `attention` returns. A spot check of outputs taken right after return must equal the final values.\n\n**Score.** For every program, the grader alternates windows of calls between PyTorch and your kernel in the same container.\n\n- Both run on 4 threads with AVX2, with fresh inputs, the same settle time before each window, and the same per-call output sampling.\n- A program's speedup is the median over windows of PyTorch's time per call divided by yours.\n- The score is the geometric mean over programs. A score of at least **0.25** counts as solved; everything above that is leaderboard.\n\n**Programs.**\n\n- **Run:** these 5 programs, 3 windows each:\n- `mha_256_d64`: heads 4, kv_heads 4 (MHA), q_len 256, kv_len 256, head_dim 64, not causal, scale 0.125\n- `gqa_causal_384_d64`: heads 8, kv_heads 2 (GQA), q_len 384, kv_len 384, head_dim 64, causal, scale 0.125\n- `cross_128x1000_d96`: heads 2, kv_heads 2 (MHA), q_len 128, kv_len 1000, head_dim 96, not causal, scale 0.102062\n- `causal_200_d48`: heads 6, kv_heads 6 (MHA), q_len 200, kv_len 200, head_dim 48, causal, scale 0.144338\n- `mqa_causal_512_d128`: heads 4, kv_heads 1 (MQA), q_len 512, kv_len 512, head_dim 128, causal, scale 0.0883883\n- **Submit:** 8 held-out programs, 5 windows each. They use the same features with different shapes: up to 16 heads; MHA, GQA and MQA; causal and not; one cross-attention; q_len and kv_len from 96 to 1,500 (not always multiples of 8 or 16).\n- `head_dim` is always a multiple of 8 between 32 and 128.\n\n**Budgets.**\n\n- `codegen` runs for at most 20 s in total on Run and 30 s on Submit.\n- Compiling takes at most 60 s or 90 s.\n- Any single call is capped at 8 s, and C source at 2,000,000 characters.\n- Your Python may import only `numpy`, `math`, `collections`, `itertools`, `functools`, `re`, `string`, `textwrap`, `typing`, `dataclasses`, `heapq`, `bisect` and `fractions`, and may use an imported module only as `module.name`.\n\n**Gates.** The score is set to 0 and the run fails if any of these happen:\n- `codegen` raises or returns something other than a str.\n- The source breaks a rule above, or does not compile.\n- A kernel crashes or exceeds the call cap.\n- A result is wrong, incomplete or still being written after return.\n- Your Python reads files, uses introspection (`globals`, `getattr`, frames, `eval`/`exec`) or tampers with imported modules.\n\nThe report lists, for each program, PyTorch's time, yours, the speedup and your GFLOP/s.","tags":["compilers","code-generation","attention","flash-attention","simd","openmp","c","open-ended","leaderboard"],"id":"acd728e1-278c-4dd0-861e-dccad0b4e637","dataset_id":"synthetic","img_type":"full","difficulty":"hard","evaluation_metric":"speedup_vs_torch","min_eval_metric":0.25,"category":"Compilers","dataset":"Synthetic attention programs (MHA, GQA, MQA, causal, cross-attention); fresh random inputs per call","title":"Fastest CPU Attention","time_limits_seconds":{"dev":150,"test":300}},{"offline":true,"description":"Train word vectors on 8,000 short children's stories and use them to answer analogy questions by vector arithmetic, the test the word2vec papers use to measure word vectors. How you build the vectors is up to you. The score is **analogy_accuracy**, higher is better. Reaching 0.4 counts as solved; above that is leaderboard.\n\n**Contract.** Implement `train(stories) -> vectors`. `stories` is a list of 8,000 strings, the first 8,000 stories of the TinyStories validation split (about 1.4 million words). Return a dict from word to vector: each key a lowercase word, each value a list, NumPy array or tensor of the same length (1 to 300 numbers). `train` must return within 120 seconds on one CPU.\n\n**What is scored.** A question is four words `(a, b, c, d)` where `a : b` and `c : d` have the same relationship, such as `boy : girl` and `king : queen`. The harness computes $x = u_b - u_a + u_c$, where $u_w$ is your vector for $w$ scaled to length 1, and finds the word whose unit vector has the highest cosine with $x$ among the 3,000 most frequent words of the stories, leaving out `a`, `b` and `c`. The question is right only if that word is exactly `d`. A question with a word you returned no vector for is wrong.\n\nThe questions come from four relationship types of the first word2vec paper's test set: man-woman (`boy : girl`, `he : she`), plural nouns (`tree : trees`, `child : children`), past tense (`walk : walked`, `go : went`) and comparative adjectives (`big : bigger`). Each type has a list of word pairs, and every ordered pair of two different pairs in a list is a question. Run uses half of each list and Submit the other half, so the Submit pairs are never shown. **analogy_accuracy** is the mean of the four types' accuracies.\n\nTo find the 3,000 search words the harness splits each story with `re.findall(r\"[a-z]+\", story.lower())` and counts the words. Use the same split, or make sure your keys match it.\n\n**Gates.** The score is 0 (a fail) if `train` runs over 120 seconds, returns something other than a dict, or returns vectors of different lengths or with values that are not finite. The 120 seconds include turning your vectors into plain numbers after `train` returns (about a second for 3,000 vectors).\n\n**What your code may use.** numpy, torch and small standard-library helpers (math, random, time, collections, re, ...). Graded runs have no network, and your code may not open files, load datasets or embed data: string constants are limited to 3,000 characters and numeric literals to 600. In this lab it may also not use private attributes (ones that start with `_`, such as `x._foo`) or the names `sys`, `os`, `builtins`, `importlib`, `inspect`, `ctypes`, `gc`, `pickle`, `json`, `subprocess`, `types`, `operator`, `traceback`, `weakref`, `modules` and a few more like them (the error message names the one it found), nor `torch.set_num_threads` or functions that write files (`save`, `savez`, `savetxt`, `tofile`, `dump`).","type":"general","tags":["word2vec","word-embeddings","skip-gram","negative-sampling","word-analogies","nlp","leaderboard"],"id":"af997b64-c9b7-4e87-81b3-1299ecef35e0","created_at":"2026-11-23T14:21:53.152000+00:00","img_type":"pytorch","test_cases":[{"test":"import numpy as np\nstories = ['The boy saw a big dog. The girl saw a small cat.'] * 30 + ['He ran to the tree. She walked to the trees.'] * 30\nv = train(stories)\nks = list(v)\nprint(isinstance(v, dict) and len(ks) > 0 and all(isinstance(k, str) for k in ks) and len({len(np.asarray(v[k]).ravel()) for k in ks}) == 1)","expected_output":"True"}],"dataset_id":"tinystories","evaluation_metric":"analogy_accuracy","difficulty":"medium","data_info":"The first 8,000 non-empty stories of the TinyStories validation split (CDLA-Sharing-1.0), as a list of strings, about 1.4 million words. Scored: analogy questions from four relationship types (man-woman, plural nouns, past tense, comparative), searched over the 3,000 most frequent words of those stories; Run and Submit use disjoint word pairs. The report shows the accuracy of each type, the number of questions, how many search words got a vector, and the training time.","time_limits":{"test":240,"dev":240},"lower_is_better":false,"approved_user_libraries":["numpy","torch","math","collections","random","time"],"min_eval_metric":0.4,"example":{"input":"train(stories) with 8,000 TinyStories stories","output":"{'the': [0.12, -0.40, ...], 'boy': [...], ...}; the harness answers boy : girl :: king : ? with the word nearest to unit(girl) - unit(boy) + unit(king)"},"category":"NLP","title":"Word Vectors That Solve Analogies","dataset":"TinyStories","gpu":false,"time_limits_seconds":{"dev":240,"test":240}},{"created_at":"2026-10-28T18:57:58.168000+00:00","type":"general","test_cases":[{"test":"import numpy as np\n_r = np.random.default_rng(3)\ndef _X(n):\n    return np.column_stack([_r.uniform(1, 10, n), _r.uniform(1, 52, n), _r.uniform(3, 8, n), _r.uniform(0.9, 1.3, n),\n                            _r.uniform(300, 3000, n), _r.uniform(2, 4, n), _r.uniform(33, 41, n), _r.uniform(-124, -115, n)])\nXa = _X(200)\nya = 0.6 * np.log(Xa[:, 0]) - 0.3 + _r.normal(0, 0.2, 200)\nXb = _X(50)\nm, v = fit_predict(Xa, ya, Xb)\nm, v = np.asarray(m, dtype=float), np.asarray(v, dtype=float)\nprint(m.shape == (50,) and v.shape == (50,), bool(np.all(np.isfinite(m)) and np.all(v > 0)))","expected_output":"True True"},{"test":"import numpy as np\n_r = np.random.default_rng(3)\ndef _X(n):\n    return np.column_stack([_r.uniform(1, 10, n), _r.uniform(1, 52, n), _r.uniform(3, 8, n), _r.uniform(0.9, 1.3, n),\n                            _r.uniform(300, 3000, n), _r.uniform(2, 4, n), _r.uniform(33, 41, n), _r.uniform(-124, -115, n)])\nXa = _X(200)\nya = 0.6 * np.log(Xa[:, 0]) - 0.3 + _r.normal(0, 0.2, 200)\nXb = np.repeat(np.median(Xa, axis=0)[None, :], 2, axis=0)\nXb[0, 0], Xb[1, 0] = 2.0, 9.0\nm, v = fit_predict(Xa, ya, Xb)\nprint(\"richer block predicted higher:\", bool(np.asarray(m)[1] > np.asarray(m)[0] + 0.3))","expected_output":"richer block predicted higher: True"},{"test":"import numpy as np\n_r = np.random.default_rng(3)\ndef _X(n):\n    return np.column_stack([_r.uniform(1, 10, n), _r.uniform(1, 52, n), _r.uniform(3, 8, n), _r.uniform(0.9, 1.3, n),\n                            _r.uniform(300, 3000, n), _r.uniform(2, 4, n), _r.uniform(33, 41, n), _r.uniform(-124, -115, n)])\nXa = _X(200)\nya = 0.6 * np.log(Xa[:, 0]) - 0.3 + _r.normal(0, 0.2, 200)\nXb = np.repeat(np.median(Xa, axis=0)[None, :], 2, axis=0)\nXb[1, 5] = 400.0                     # a household size far beyond any training row\nm, v = fit_predict(Xa, ya, Xb)\nv = np.asarray(v, dtype=float)\nprint(\"error bar wider far from the data:\", bool(v[1] > 1.5 * v[0]))","expected_output":"error bar wider far from the data: True"}],"lower_is_better":true,"approved_user_libraries":["numpy","scipy","sklearn"],"data_info":"California housing (registry id california-housing), block groups top-coded at $500,001 removed (19,648 rows). Each task: 200 random training rows and 2,000 different random test rows; X raw (8 features: MedInc, HouseAge, AveRooms, AveBedrms, Population, AveOccup, Latitude, Longitude), y = log(median house value in $100k). Run: 10 tasks (seeds 42-51). Submit: 30 different tasks.","time_limits":{"test":300,"dev":120},"example":{"input":"fit_predict(X_train (200, 8), y_train (200,), X_test (2000, 8))","output":"(mean, var), e.g. (array([0.41, -0.22, 1.05, ...]), array([0.081, 0.093, 0.140, ...])); Submit mean NLL: constant Gaussian 0.791, OLS plug-in 3.75, OLS posterior predictive 0.319"},"gpu":false,"description":"A price estimate is only useful with honest error bars. With **200 sales** to learn from, you cannot know much, and you know least about houses that look like nothing you have seen. The book makes this concrete: the **plug-in** predictive $\\mathcal{N}(y \\mid \\hat{w}^\\top x, \\sigma^2)$ gives every house the same error bar, while the **posterior predictive** $\\mathcal{N}(y \\mid \\mu_N^\\top x, \\sigma^2 + x^\\top \\Sigma_N x)$ widens it where the training data say little. Your job: from 200 California block groups, give a Gaussian predictive distribution for the value of thousands of others, and be scored on how much probability you put on the truth.\n\n## The data\n\nEach row is a census block group from the California housing data (registry id `california-housing`). Block groups whose value was top-coded at \\$500,001 are removed. The eight columns of `X` are raw, in this order:\n\n- `MedInc`: median income, in tens of thousands of dollars\n- `HouseAge`: median house age, years (capped at 52)\n- `AveRooms`: average rooms per household\n- `AveBedrms`: average bedrooms per household\n- `Population`: block group population\n- `AveOccup`: average household size\n- `Latitude`, `Longitude`\n\nSome columns have a long right tail (`AveOccup` exceeds 1,000 in a handful of rows). The target is $y = \\log v$, where $v$ is the median house value in units of \\$100,000.\n\n## Your function\n\n```python\ndef fit_predict(X_train, y_train, X_test):\n    ...\n    return mean, var     # two arrays of shape (len(X_test),), every var > 0\n```\n\n- `X_train`: `(200, 8)`, `y_train`: `(200,)`, `X_test`: `(2000, 8)`, all float64.\n- Return the mean and the **variance** of a Gaussian predictive distribution for each test row.\n- Learn from these arrays only. Each task runs in a fresh copy of the process, so nothing carries over from one call to the next.\n\nApproved libraries: numpy, scipy, scikit-learn (plus small standard-library helpers such as `math` and `functools`). CPU only.\n\n## Score (lower is better)\n\nA **task** draws 200 training rows and 2,000 different test rows at random from the data. For each test row with true value $y_i$ and your prediction $(m_i, v_i)$, the loss is the Gaussian negative log-likelihood\n\n$$\\text{NLL}_i = \\tfrac{1}{2}\\log(2\\pi v_i) + \\frac{(y_i - m_i)^2}{2 v_i},$$\n\nwith $v_i$ floored at $10^{-4}$. The score is the mean NLL in nats over all test rows of all tasks. **Run** scores 10 tasks; **Submit** scores 30 other tasks. You pass at a Submit score of **0.33** or lower; below that, lower ranks higher.\n\nThe report also shows your NLL on test rows that lie inside and outside the range of the 200 training rows (about 6% of test rows have at least one feature beyond the training minimum or maximum), RMSE, 90% interval coverage, mean squared z-score (1.0 for calibrated variances), and two references computed in the same tasks: a constant Gaussian and ordinary least squares with the plug-in variance.\n\n## Budget and gates\n\n`fit_predict` gets **120 s of CPU time in total** for the 30 Submit tasks (40 s for the 10 Run tasks). The run fails (score 99) if `fit_predict` raises or exits, goes over the budget, returns the wrong shapes, NaN or inf, or any variance that is not strictly positive. Your code may not read data from anywhere else: no file or dataset access, no imports beyond the approved libraries, no reading your own source or docstrings, and at most 120 numeric literals and 400 characters of string literals (outside docstrings), so the model has to come from the 200 training rows and not be written into the code.","tags":["bayesian-linear-regression","posterior-predictive","uncertainty","gaussian-nll","small-data","empirical-bayes","open-ended","leaderboard"],"id":"b1231da6-8bc2-43d4-97c1-2b0bc1cd15bf","dataset_id":"california-housing","img_type":"full","evaluation_metric":"nll","difficulty":"medium","min_eval_metric":0.33,"category":"Regression","dataset":"California Housing (200 training rows per task)","title":"Honest Error Bars From 200 Houses","time_limits_seconds":{"dev":120,"test":300}},{"created_at":"2026-10-27T19:33:57.494000+00:00","type":"general","test_cases":[{"test":"def _flat(p):\n    out = []\n    for it in p:\n        out += list(it) if isinstance(it, (list, tuple, set, frozenset)) else [it]\n    return out\n_g = {\"name\": \"tiny\", \"outputs\": [6],\n      \"machine\": {\"bandwidth_bytes_per_us\": 100000.0, \"peak_flops_per_us\": 1000000.0, \"launch_us\": 2.0},\n      \"nodes\": [\n        {\"id\": 0, \"op\": \"BUFFER\", \"src\": [], \"shape\": [256, 64], \"arg\": \"x\"},\n        {\"id\": 1, \"op\": \"MUL\", \"src\": [0], \"shape\": [256, 64], \"arg\": 2.0},\n        {\"id\": 2, \"op\": \"EXP2\", \"src\": [1], \"shape\": [256, 64], \"arg\": None},\n        {\"id\": 3, \"op\": \"REDUCE\", \"src\": [2], \"shape\": [256, 1], \"arg\": {\"op\": \"add\", \"axes\": [1]}},\n        {\"id\": 4, \"op\": \"EXPAND\", \"src\": [3], \"shape\": [256, 64], \"arg\": None},\n        {\"id\": 5, \"op\": \"RECIP\", \"src\": [4], \"shape\": [256, 64], \"arg\": None},\n        {\"id\": 6, \"op\": \"MUL\", \"src\": [2, 5], \"shape\": [256, 64], \"arg\": None}]}\n_p = _flat(plan(_g))\nprint(all(isinstance(i, int) and 0 <= i < 7 and _g['nodes'][i]['op'] != 'BUFFER' for i in _p))","expected_output":"True"},{"test":"def _flat(p):\n    out = []\n    for it in p:\n        out += list(it) if isinstance(it, (list, tuple, set, frozenset)) else [it]\n    return out\n_e = {\"name\": \"edge\", \"outputs\": [1, 2],\n      \"machine\": {\"bandwidth_bytes_per_us\": 900000.0, \"peak_flops_per_us\": 30000000.0, \"launch_us\": 5.0},\n      \"nodes\": [\n        {\"id\": 0, \"op\": \"BUFFER\", \"src\": [], \"shape\": [8, 8], \"arg\": \"x\"},\n        {\"id\": 1, \"op\": \"MUL\", \"src\": [0, 0], \"shape\": [8, 8], \"arg\": None},\n        {\"id\": 2, \"op\": \"ADD\", \"src\": [0], \"shape\": [8, 8], \"arg\": 1.0}]}\n_p = _flat(plan(_e))\nprint(all(isinstance(i, int) and i in (1, 2) for i in _p))","expected_output":"True"},{"test":"def _flat(p):\n    out = []\n    for it in p:\n        out += list(it) if isinstance(it, (list, tuple, set, frozenset)) else [it]\n    return out\n_g = {\"name\": \"tiny\", \"outputs\": [6],\n      \"machine\": {\"bandwidth_bytes_per_us\": 100000.0, \"peak_flops_per_us\": 1000000.0, \"launch_us\": 2.0},\n      \"nodes\": [\n        {\"id\": 0, \"op\": \"BUFFER\", \"src\": [], \"shape\": [256, 64], \"arg\": \"x\"},\n        {\"id\": 1, \"op\": \"MUL\", \"src\": [0], \"shape\": [256, 64], \"arg\": 2.0},\n        {\"id\": 2, \"op\": \"EXP2\", \"src\": [1], \"shape\": [256, 64], \"arg\": None},\n        {\"id\": 3, \"op\": \"REDUCE\", \"src\": [2], \"shape\": [256, 1], \"arg\": {\"op\": \"add\", \"axes\": [1]}},\n        {\"id\": 4, \"op\": \"EXPAND\", \"src\": [3], \"shape\": [256, 64], \"arg\": None},\n        {\"id\": 5, \"op\": \"RECIP\", \"src\": [4], \"shape\": [256, 64], \"arg\": None},\n        {\"id\": 6, \"op\": \"MUL\", \"src\": [2, 5], \"shape\": [256, 64], \"arg\": None}]}\nprint(len(set(_flat(plan(_g))) - {6}) < 5)","expected_output":"True"}],"lower_is_better":false,"approved_user_libraries":["numpy","math","collections","itertools","functools","random"],"data_info":"Synthetic model graphs generated inside the grader from fixed seeds: MLPs, attention, transformer blocks and stacks, layernorm/softmax heads, Adam optimizer steps, batchnorm training, convolution stacks and cross-entropy losses, each priced on one of four machines. Run: 8 graphs. Submit: 16 held-out graphs.","time_limits":{"test":240,"dev":120},"example":{"input":"plan(graph) with graph = {'nodes': [{'id': 0, 'op': 'BUFFER', 'shape': [256, 64], ...}, {'id': 1, 'op': 'MUL', 'src': [0], 'arg': 2.0, ...}, ...], 'outputs': [6], 'machine': {'bandwidth_bytes_per_us': 80000.0, 'peak_flops_per_us': 1200000.0, 'launch_us': 2.0}}","output":"kernels to compute, e.g. [3, [17, 18, 19]] (node 3 alone, nodes 17-19 in one multi-output kernel); the grader prices the plan (time 9.8 us vs ideal 7.4 us) and reports 100 * geomean(ideal / time)"},"gpu":false,"description":"After rangeify, every op in a model graph is a loop nest, and the compiler still has to decide which intermediate results get written to memory. You decide. For each graph, choose which nodes to **STAGE** (materialize into a temporary buffer) and which staged nodes share a kernel. Every node you do not stage is fused into the kernels that use it and recomputed there. The plans are priced with a fixed roofline cost model, and the leaderboard ranks by **percent of the ideal time, higher is better**.\n\n**Contract.** Define `plan(graph)`. It is called once per graph and returns an iterable of kernels. Each item is either a node id (one staged node computed by its own kernel) or a list of node ids (several staged nodes computed by one multi-output kernel).\n\n- `graph[\"nodes\"]` is a topologically ordered list. Each node is a dict with `id`, `op`, `src` (ids of its inputs), `shape` (a list) and `arg`.\n- `graph[\"outputs\"]` lists the nodes that must end up in memory. Any output you do not list gets its own kernel.\n- `graph[\"machine\"]` gives `bandwidth_bytes_per_us`, `peak_flops_per_us` and `launch_us`. It differs between graphs.\n- Every value is f32 (4 bytes).\n- Each node may appear at most once in a plan.\n- All nodes in one multi-output kernel must have the same shape, and none of them may depend, directly or through other nodes, on another node of the same kernel.\n\n**Ops.**\n- `BUFFER`: an input already in memory. It can't be staged.\n- ALU ops take operands of identical shape, with an optional immediate in `arg` (for example `MUL` with `arg` 0.5): `ADD MUL MAX CMPLT WHERE` (1 flop per element), `RECIP SQRT` (4) and `EXP2 LOG2` (8).\n- `REDUCE` has `arg` = `{\"op\": \"add\"|\"max\", \"axes\": [...]}`. Reduced axes stay as size 1, as in tinygrad.\n- Movement ops cost no flops: `EXPAND` (broadcasts size-1 axes), `RESHAPE`, `PERMUTE` (`arg` = order), `PAD` and `SHRINK` (`arg` = per-axis pairs).\n\n**Kernels.** Each kernel computes its staged nodes (its *roots*). It loads every `BUFFER` and staged node it reaches, and recomputes every unstaged node it reaches. Its work is counted like this:\n\n- The kernel loops over every element of its roots' shape.\n- An ALU node's inputs are evaluated in the same loop iteration as the node.\n- A `REDUCE` node opens an inner loop over its `r = numel(input) / numel(node)` reduced elements. Each evaluation of the REDUCE costs `r` flops and evaluates its input `r` times.\n- A movement node changes which element is read. Nothing is hoisted: an unstaged node is evaluated once per iteration of the loop that uses it, so a node behind an `EXPAND` is recomputed for every broadcast copy.\n- Within one kernel, two uses of a node share one evaluation exactly when they reach it through the same sequence of `REDUCE` and movement nodes. Otherwise each distinct access path evaluates it separately. This holds across all roots of a multi-output kernel too. Precisely, every root has context `(root, ())` with `numel(root)` iterations. A node in context `(key, it)` passes `(key, it)` to its unstaged inputs if it is an ALU node, `(key + (node,), it * r)` if it is a `REDUCE`, and `(key + (node,), it)` if it is a movement node. Every distinct `(node, key)` pair in the kernel is evaluated once and costs `it * flops_per_element`.\n- A kernel moves `4 * (sum of numel over its roots + sum of numel over the distinct BUFFER and staged nodes it loads)` bytes.\n- A kernel takes `max(bytes / bandwidth, flops / peak) + launch` microseconds.\n- A plan's time is the sum over its kernels.\n- A kernel with more than 50,000 distinct `(node, key)` pairs is too large to compile, which makes the plan illegal.\n\n**Score.** Each graph's *ideal time* is an unreachable lower bound: every input read once, every output written once, every node computed exactly once, and one launch per output: `max(those bytes / bandwidth, those flops / peak) + launch * len(outputs)`. The score is `100 * geometric mean over graphs of (ideal / your time)`. A score of at least **45** counts as solved; everything above that is leaderboard. The report shows each graph's time, ideal time, kernel count, and the time of staging every node.\n\n**Graphs.**\n- **Run:** 8 graphs (an MLP, a layernorm + softmax head, two Adam optimizer steps, attention, a transformer block, a transformer stack, batchnorm training) on four machines.\n- **Submit:** 16 held-out graphs, including families that never appear in Run, with up to about 2,000 nodes.\n\n**Budget and rules.** Total time inside `plan` is capped at 30 s on Run and 60 s on Submit, summed over all graphs. Your code may import only `numpy`, `math`, `collections`, `itertools`, `functools`, `heapq`, `bisect`, `random`, `time`, `typing` and `dataclasses`, and may use an imported module only as `module.name`.\n\n**Gates.** The score is set to 0 and the run fails if any of these happen:\n- `plan` raises or exits.\n- `plan` returns something that is not an iterable of valid non-`BUFFER` node ids.\n- A plan is illegal.\n- The time budget runs out.\n- Your code reads files, uses introspection (`globals`, `vars`, `getattr`/`setattr`, frames, `eval`/`exec`), or aliases, patches or reaches into the internals of an imported module.","tags":["compilers","kernel-fusion","rangeify","materialization","roofline","scheduling","open-ended","leaderboard"],"id":"b9ec2128-20b8-49e5-b42c-eb256a8a6c25","dataset_id":"synthetic","img_type":"full","difficulty":"hard","evaluation_metric":"pct_of_ideal","min_eval_metric":45.0,"category":"Compilers","dataset":"Synthetic model graphs (MLPs, attention, transformer stacks, optimizer steps, norms, convs)","title":"Best Fusion Plan","time_limits_seconds":{"dev":120,"test":240}},{"created_at":"2026-10-28T18:58:39.456000+00:00","description":"## Best Predictions from Sparse Counts\n\nYou run a platform with tens of thousands of **groups**: ads, products, coins, sellers. For each group you have seen $N$ trials and $N_1$ successes, and you must predict the probability that the group's **next** trial succeeds. Most groups have almost no history (zero to five trials), a few have hundreds. Every group also comes with six numeric features. The success rates were drawn from a hidden prior that differs from dataset to dataset.\n\nThe maximum likelihood answer $N_1 / N$ predicts that a group with 0 successes in 2 trials never succeeds, and says nothing at all for a group with no trials (the zero-count problem). Laplace's rule of succession $(N_1 + 1)/(N + 2)$ fixes that but ignores everything the other groups tell you. Build the best predictor you can; any method is allowed.\n\n### Contract\n\n```python\ndef fit_predict(successes, trials, features):\n    # successes: int64 array, shape (G,)   observed successes N1 per group\n    # trials:    int64 array, shape (G,)   observed trials N per group (can be 0)\n    # features:  float64 array, shape (G, 6)\n    # return:    float array, shape (G,)   P(next trial of group g succeeds)\n```\n\nEach call is one independent dataset with its own hidden prior: fit whatever you need inside the call, from its arguments only. Nothing carries over between calls.\n\n### Score\n\nEach group $g$ has a true success rate $\\theta_g$ that you never see. The grader scores your probability $p_g$ by the Bernoulli log loss of the group's next trial, averaged exactly over that trial's outcome:\n\n$$\\ell_g = -\\left[\\theta_g \\log p_g + (1 - \\theta_g)\\log(1 - p_g)\\right]$$\n\nThe score is the mean of $\\ell_g$ over every group of every dataset, in nats per trial. **Lower is better.** The report also shows each dataset's score next to the Laplace-rule score on the same data.\n\n- **Run** grades 3 practice datasets of 15,000 groups.\n- **Submit** grades 4 different datasets of 30,000 groups each, generated from priors that are not in Run.\n- To pass, the Submit score must be at most **0.48** nats, about 6% below what Laplace's rule (the starter) scores there. Beyond that, lower scores rank higher.\n\n### Rules (breaking one fails the run with a score of 99)\n\n- Return one probability per group, finite, inside $[10^{-6},\\ 1 - 10^{-6}]$ (a hard 0 or 1 fails, so clip).\n- Each call must finish within 45 seconds of wall-clock time.\n- Libraries: `numpy`, `scipy`, `math`. The grader seeds `np.random` and `random` before each call; do not create or reseed random generators.\n- An exception raised by `fit_predict` fails the run.\n","tags":["bayesian statistics","empirical bayes","beta-binomial","log loss","competitive"],"type":"general","id":"bedc8873-60a5-4103-8d3f-7ef8ac3fa9cc","dataset_id":"synthetic","test_cases":[{"test":"import numpy as np\nk = np.array([0, 1, 3, 0, 10, 2]); n = np.array([0, 1, 3, 5, 40, 2])\nX = np.zeros((6, 6)); X[:, 0] = np.linspace(-1.0, 1.0, 6); X[:, 4] = [0, 1, 0, 1, 0, 1]\np = np.asarray(fit_predict(k, n, X), dtype=float)\nprint(p.shape == (6,) and bool(np.all(np.isfinite(p))) and bool(np.all((p >= 1e-6) & (p <= 1 - 1e-6))))","expected_output":"True"},{"test":"import numpy as np\n# 400 groups with 100 trials each and about 2% successes, then one group with no trials yet\nk = np.array([1, 2, 3, 2] * 100 + [0]); n = np.array([100] * 400 + [0])\nX = np.zeros((401, 6))\np = np.asarray(fit_predict(k, n, X), dtype=float)\nprint(bool(p[-1] < 0.1))","expected_output":"True"},{"test":"import numpy as np\n# 300 groups with 50 trials each and about 90% successes, then one group with 0 successes in 2 trials\nk = np.array([44, 45, 46] * 100 + [0]); n = np.array([50] * 300 + [2])\nX = np.zeros((301, 6))\np = np.asarray(fit_predict(k, n, X), dtype=float)\nprint(bool(p[-1] > 0.5))","expected_output":"True"}],"img_type":"full","evaluation_metric":"log_loss","difficulty":"hard","data_info":"Generated inside the grader, no files. Each fit_predict call receives one dataset: successes and trials (int64, shape (G,)) and features (float64, shape (G, 6)). Group success rates come from a hidden prior (it can depend on the features) and trial counts are long-tailed (many groups with 0-5 trials, a few with hundreds or thousands). Run: 3 datasets x 15,000 groups. Submit: 4 different datasets x 30,000 groups from priors not used in Run.","approved_user_libraries":["numpy","scipy","math"],"lower_is_better":true,"time_limits":{"test":240,"dev":180},"min_eval_metric":0.48,"category":"Statistics","dataset":"Synthetic grouped success counts (generated inside the grader)","title":"Best Predictions from Sparse Counts","gpu":false,"time_limits_seconds":{"dev":180,"test":240}},{"created_at":"2026-11-01T00:04:56.026000+00:00","type":"general","test_cases":[{"test":"import numpy as np\n_r = np.random.default_rng(3)\n_D = 196\n_F = _r.normal(size=(_D, 3)) * 0.06\ndef _draw(n):\n    return 0.3 + _r.normal(size=(n, 3)) @ _F.T + 0.03 * _r.normal(size=(n, _D))\ndef _params(m):\n    return (np.asarray(m[\"pi\"], dtype=float), np.asarray(m[\"mu\"], dtype=float),\n            [np.asarray(w, dtype=float) for w in m[\"W\"]], np.asarray(m[\"psi\"], dtype=float))\ndef _ll(X, m):\n    pi, mu, W, psi = _params(m)\n    lp = []\n    for k in range(len(pi)):\n        C = W[k] @ W[k].T + np.diag(psi[k])\n        s, ld = np.linalg.slogdet(C)\n        R = X - mu[k]\n        lp.append(np.log(pi[k] + 1e-300) - 0.5 * (_D * np.log(2 * np.pi) + ld + np.sum(R * np.linalg.solve(C, R.T).T, 1)))\n    lp = np.stack(lp, 1)\n    t = lp.max(1, keepdims=True)\n    return float((t[:, 0] + np.log(np.exp(lp - t).sum(1))).mean() / _D)\n_m = fit(_draw(1500))\n_pi, _mu, _W, _psi = _params(_m)\n_K = len(_pi)\nprint(_pi.ndim == 1, _mu.shape == (_K, _D), _psi.shape == (_K, _D), len(_W) == _K, all(w.ndim == 2 and w.shape[0] == _D for w in _W))","expected_output":"True True True True True"},{"test":"import numpy as np\n_r = np.random.default_rng(4)\n_D = 196\n_F = _r.normal(size=(_D, 3)) * 0.06\ndef _draw(n):\n    return 0.3 + _r.normal(size=(n, 3)) @ _F.T + 0.03 * _r.normal(size=(n, _D))\ndef _params(m):\n    return (np.asarray(m[\"pi\"], dtype=float), np.asarray(m[\"mu\"], dtype=float),\n            [np.asarray(w, dtype=float) for w in m[\"W\"]], np.asarray(m[\"psi\"], dtype=float))\ndef _ll(X, m):\n    pi, mu, W, psi = _params(m)\n    lp = []\n    for k in range(len(pi)):\n        C = W[k] @ W[k].T + np.diag(psi[k])\n        s, ld = np.linalg.slogdet(C)\n        R = X - mu[k]\n        lp.append(np.log(pi[k] + 1e-300) - 0.5 * (_D * np.log(2 * np.pi) + ld + np.sum(R * np.linalg.solve(C, R.T).T, 1)))\n    lp = np.stack(lp, 1)\n    t = lp.max(1, keepdims=True)\n    return float((t[:, 0] + np.log(np.exp(lp - t).sum(1))).mean() / _D)\n_m = fit(_draw(1500))\n_pi, _mu, _W, _psi = _params(_m)\n_K = len(_pi)\n_n = _K + 2 * _K * _D + _D * sum(w.shape[1] for w in _W)\nprint(bool(abs(_pi.sum() - 1) < 1e-6 and _pi.min() >= 0), bool(_psi.min() >= 1e-4), _n <= 48000)","expected_output":"True True True"},{"test":"import numpy as np\n_r = np.random.default_rng(5)\n_D = 196\n_F = _r.normal(size=(_D, 3)) * 0.06\ndef _draw(n):\n    return 0.3 + _r.normal(size=(n, 3)) @ _F.T + 0.03 * _r.normal(size=(n, _D))\ndef _params(m):\n    return (np.asarray(m[\"pi\"], dtype=float), np.asarray(m[\"mu\"], dtype=float),\n            [np.asarray(w, dtype=float) for w in m[\"W\"]], np.asarray(m[\"psi\"], dtype=float))\ndef _ll(X, m):\n    pi, mu, W, psi = _params(m)\n    lp = []\n    for k in range(len(pi)):\n        C = W[k] @ W[k].T + np.diag(psi[k])\n        s, ld = np.linalg.slogdet(C)\n        R = X - mu[k]\n        lp.append(np.log(pi[k] + 1e-300) - 0.5 * (_D * np.log(2 * np.pi) + ld + np.sum(R * np.linalg.solve(C, R.T).T, 1)))\n    lp = np.stack(lp, 1)\n    t = lp.max(1, keepdims=True)\n    return float((t[:, 0] + np.log(np.exp(lp - t).sum(1))).mean() / _D)\n_Xa, _Xb = _draw(1500), _draw(500)\n_d = {\"pi\": [1.0], \"mu\": _Xa.mean(0)[None], \"W\": [np.zeros((_D, 0))], \"psi\": np.maximum(_Xa.var(0), 1e-4)[None]}\nprint(\"finds the correlated pixels:\", _ll(_Xb, fit(_Xa)) > _ll(_Xb, _d) + 0.1)","expected_output":"finds the correlated pixels: True"},{"test":"import numpy as np\n_r = np.random.default_rng(6)\n_D = 196\n_F = _r.normal(size=(_D, 3)) * 0.06\ndef _draw(n):\n    return 0.3 + _r.normal(size=(n, 3)) @ _F.T + 0.03 * _r.normal(size=(n, _D))\ndef _params(m):\n    return (np.asarray(m[\"pi\"], dtype=float), np.asarray(m[\"mu\"], dtype=float),\n            [np.asarray(w, dtype=float) for w in m[\"W\"]], np.asarray(m[\"psi\"], dtype=float))\ndef _ll(X, m):\n    pi, mu, W, psi = _params(m)\n    lp = []\n    for k in range(len(pi)):\n        C = W[k] @ W[k].T + np.diag(psi[k])\n        s, ld = np.linalg.slogdet(C)\n        R = X - mu[k]\n        lp.append(np.log(pi[k] + 1e-300) - 0.5 * (_D * np.log(2 * np.pi) + ld + np.sum(R * np.linalg.solve(C, R.T).T, 1)))\n    lp = np.stack(lp, 1)\n    t = lp.max(1, keepdims=True)\n    return float((t[:, 0] + np.log(np.exp(lp - t).sum(1))).mean() / _D)\n_side = _r.random(3000) < 0.5\n_blank = np.arange(_D) < 98\n_a = np.where(_side[:, None] == _blank[None, :], 0.5 + 0.1 * _r.normal(size=(3000, _D)), 0.02 * _r.random((3000, _D)))\n_d = {\"pi\": [1.0], \"mu\": _a[:2400].mean(0)[None], \"W\": [np.zeros((_D, 0))], \"psi\": np.maximum(_a[:2400].var(0), 1e-4)[None]}\n_R = _a[:2400] - _a[:2400].mean(0)\n_vals, _vecs = np.linalg.eigh(_R.T @ _R / 2400)\n_s2 = max(_vals[:-10].mean(), 1e-4)\n_one = {\"pi\": [1.0], \"mu\": _a[:2400].mean(0)[None], \"W\": [_vecs[:, -10:] * np.sqrt(np.maximum(_vals[-10:] - _s2, 0))], \"psi\": np.full((1, _D), _s2)}\nprint(\"beats one Gaussian on two kinds of image:\", _ll(_a[2400:], fit(_a[:2400])) > max(_ll(_a[2400:], _one), _ll(_a[2400:], _d)) + 0.3)","expected_output":"beats one Gaussian on two kinds of image: True"}],"lower_is_better":false,"approved_user_libraries":["numpy","scipy","sklearn","torch","math","time","random","collections","itertools","functools","copy"],"data_info":"Fashion-MNIST (dml_data id fashion-mnist), 28 x 28 averaged in 2 x 2 blocks to 14 x 14, scaled to [0, 1], flattened to 196 pixels, plus independent uniform noise on [0, 1/16] per pixel. Run: 10,000 training-split images to fit on and 2,000 other training-split images to score. Submit: 20,000 training-split images (a different draw) to fit on and 5,000 test-split images to score, with fresh noise. fit sees only the noisy training pixels, without labels.","time_limits":{"test":300,"dev":150},"example":{"input":"fit(X_train float64 (20000, 196)) on Submit","output":"{'pi': (K,), 'mu': (K, 196), 'W': [ (196, L_k) for each k ], 'psi': (K, 196)}; the grader returns mean held-out log-likelihood in nats per pixel, about 0.10 for one diagonal Gaussian"},"gpu":false,"description":"Build the best probability model of small clothing images that you can, under two hard limits: every component of the model is a Gaussian whose covariance is low-rank plus diagonal, and the whole model may store at most **48,000 numbers**. The book builds this family: factor analysis, probabilistic PCA and mixtures of factor analyzers. You hand back the parameters and the grader computes the exact held-out log-likelihood from them, so every submission is a normalized density scored on the same footing.\n\n## The data\n\nFashion-MNIST images. Each 28 x 28 image is averaged in 2 x 2 blocks down to 14 x 14, scaled to [0, 1] and flattened to `D = 196` pixels. Every pixel then gets independent uniform noise on [0, 1/16], in train and test alike. You get the training images without labels; the test images never leave the grader.\n\n## Your function\n\n```python\ndef fit(X_train):\n    ...\n    return {\"pi\": pi, \"mu\": mu, \"W\": W, \"psi\": psi}\n```\n\n- `X_train`: float64 array of shape `(N, 196)`.\n- `pi`: shape `(K,)`, non-negative, summing to 1 within 1e-6.\n- `mu`: shape `(K, 196)`.\n- `W`: a list of `K` arrays where `W[k]` has shape `(196, L_k)`. Components may have different `L_k`, and `L_k = 0` is allowed (`np.zeros((196, 0))`). A single array of shape `(K, 196, L)` also works.\n- `psi`: shape `(K, 196)`, the diagonal of each $\\Psi_k$, every entry at least 0.0001.\n\nYour model is then\n\n$$p(x) = \\sum_{k=1}^{K} \\pi_k \\, \\mathcal{N}\\left(x \\mid \\mu_k, \\; W_k W_k^\\top + \\operatorname{diag}(\\psi_k)\\right)$$\n\nApproved libraries: numpy, scipy, scikit-learn, torch (CPU), and small standard-library helpers (math, time, random, collections, itertools, functools, copy). Your code may not open files, load datasets or reach the network, and is limited to 30,000 characters, 600 numeric literals and 3,000 characters of string constants.\n\n## The parameter budget\n\nEvery stored number counts:\n\n$$\\text{numbers} = K + 2KD + D \\sum_{k=1}^{K} L_k \\le 48{,}000$$\n\nFor example, `K = 20` components with `L_k = 10` each store 47,060 numbers, and one component with `L = 195` stores 38,613. How you spend the budget is up to you.\n\n## Score (higher is better)\n\n$$\\text{score} = \\frac{1}{196\\,n} \\sum_{i=1}^{n} \\log p(x_i)$$\n\nThis is the mean held-out log-likelihood in nats per pixel. **Run** fits on 10,000 images from the training split and scores 2,000 other training-split images. **Submit** fits on 20,000 training-split images (a different draw) and scores 5,000 images from the test split that Run never shows, with fresh noise. You pass at **1.15** or higher; above that, higher ranks higher. A single diagonal Gaussian scores about 0.10.\n\n## Budgets and gates\n\n`fit` gets **60 s** of process CPU time on Run and **180 s** on Submit, and every thread counts. The run fails with a score of 0 if your code imports anything outside the approved set or touches files or datasets, if `fit` raises or goes over its CPU budget, if the model stores more than 48,000 numbers, if an array has the wrong shape or holds a NaN or inf, if `pi` is not a probability vector, if a `psi` entry is below 0.0001, or if a test image's log-likelihood is not finite.\n\nThe report shows your score, the median and worst-1% nats per pixel across test images, `K`, your ranks (largest first, up to 50), the numbers stored, how many components carry at least one test image's worth of responsibility, and your CPU and wall seconds.","tags":["density-estimation","factor-analysis","ppca","mixture-of-factor-analyzers","low-rank","em","fashion-mnist","open-ended","leaderboard"],"id":"c2520e61-d0b5-4622-925f-d1397b616df8","dataset_id":"fashion-mnist","img_type":"full","evaluation_metric":"nats_per_dim","difficulty":"medium","min_eval_metric":1.15,"category":"Machine Learning","dataset":"Fashion-MNIST (14 x 14, noised)","title":"Best Density Model with a Low-Rank Latent","time_limits_seconds":{"dev":150,"test":300}},{"created_at":"2026-10-26T02:03:09.231000+00:00","type":"general","test_cases":[{"test":"import torch\nz = torch.randn(8, 31, requires_grad=True)\nt = torch.randint(0, 31, (8,))\nL = loss_fn(z, t)\nL.backward()\nprint(L.dim() == 0 and bool(torch.isfinite(L)) and z.grad is not None)","expected_output":"True"},{"test":"import torch\nm = torch.nn.Linear(3, 31)\nopt = make_optimizer(list(m.parameters()), 3e-3, 1.0)\nprint(isinstance(opt, torch.optim.Optimizer) and sum(len(g['params']) for g in opt.param_groups) == 2)","expected_output":"True"},{"test":"import torch\nz = torch.zeros(4, 31)\nz[:, 0] = 40.0\nz.requires_grad_(True)\nL = loss_fn(z, torch.zeros(4, dtype=torch.long))\nL.backward()\nprint(float(z.grad[:, 0].abs().max()) > 0.0)","expected_output":"True"},{"test":"import torch\nz = torch.randn(6, 31, requires_grad=True)\nt = torch.randint(0, 31, (6,))\nloss_fn(z, t).backward()\nprint(float(z.grad.sum(1).abs().max()) < 1e-5)","expected_output":"True"}],"approved_user_libraries":["torch","numpy","math"],"lower_is_better":true,"data_info":"No dataset: the harness builds modular addition a + b mod 31 (961 pairs, 50% train split per seed) and trains the paper's one-layer transformer itself. Submit: 3,000 full-batch steps on seeds 0, 1, 2 (about 40-60 s on CPU). Run: 3,000 steps on seed 2 (about 20 s). The report gives the score (mean exact held-out cross-entropy), mean test accuracy and per-seed margins and cliff crossings.","time_limits":{"test":480,"dev":240},"example":{"input":"loss_fn(logits, targets) and make_optimizer(params, 3e-3, 1.0) are called by the harness's training loop; the model, data and seeds are fixed","output":"score = mean exact held-out cross-entropy over seeds after the budget: about 0.12 for standard cross-entropy with AdamW eps 1e-8 (crashes through the float32 cliff), about 0.013 for the paper's fixed loss"},"gpu":false,"description":"Barron, Gnanapragasam and Tschannen (2026) show that the standard cross-entropy breaks training once a model becomes confident: past a precision cliff (a logit margin of about 16.6 in float32) the target's gradient rounds to exactly zero, Adam's second moment collapses, weight decay drags the margin back under the cliff, and the restored gradient lands as a loss spike, the Slingshot. Their answer is a loss rewritten in log space. This lab hands you the training run and asks you to make it behave, by whatever means you think right: the paper's loss, a different loss, a gradient projection, a change to the optimiser, a schedule, a logit transform, or something of your own. The leaderboard ranks by **score**, lower is better.\n\n**The run.** The paper's setup, owned by the harness: a one-layer, width-64, four-head ReLU transformer with no normalisation on modular addition a + b mod 31 (961 pairs, half for training), full-batch training with learning rate 3e-3 and weight decay 1, float32 on CPU, fixed seeds. Under the standard loss and AdamW with epsilon 1e-8 this run crosses the cliff within a few hundred steps: in each seed 74-143 training examples lose their gradient, the loss spikes, and margins crash from 16 to under 8.\n\n**Contract.** Implement two functions:\n\n- `loss_fn(logits, targets) -> scalar tensor`: the training loss on float32 logits of shape `(batch, 31)` and integer targets `(batch,)`. Autograd differentiates whatever you return; a `torch.autograd.Function` or a surrogate loss that delivers a hand-written gradient is fine.\n- `make_optimizer(params, lr, weight_decay) -> torch.optim.Optimizer`: any optimiser over exactly these parameters. `lr` and `weight_decay` are the run's values; you choose everything else, including whether to honour them.\n\n**Score.** After the step budget, the held-out cross-entropy of the model, computed exactly in float64 in the margin form (so a collapsed softmax cannot hide it), averaged over the seeds. Submit: 3,000 steps, seeds 0, 1, 2. Run: 3,000 steps on seeds 2 and 5, averaged. The standard loss with the paper's AdamW scores about 0.1; the paper's fixed loss about 0.013. Clearing 0.03 counts as solved; everything below that is leaderboard.\n\n**Gates.** The score is set to 99.0 (a fail) if `loss_fn` creates any float64 tensor (casting the loss to float64 is the prior mitigation the paper replaces, so it is out of bounds), if the loss is not a finite scalar, if no gradient reaches the model, if the optimiser does not hold exactly the model's parameters, or if training runs over its time budget. The report lists, per seed, the held-out log-loss and accuracy, the training log-loss, the largest mean margin reached and how many training examples crossed the float32 cliff.","tags":["grokking","softmax","cross-entropy","adam","slingshot","open-ended","leaderboard"],"id":"c315b9dd-696b-4882-a942-429b32a1c79c","img_type":"pytorch","dataset_id":"synthetic","difficulty":"hard","evaluation_metric":"score","min_eval_metric":0.03,"category":"Optimization","title":"Grok Without the Slingshot","dataset":"Modular addition a + b mod 31 (generated in the harness)","time_limits_seconds":{"dev":240,"test":480}},{"created_at":"2026-11-09T19:56:31.360000+00:00","type":"general","test_cases":[{"test":"m = train(['emily', 'emma', 'anna'])\np = predict(m, 'em_ly')\nprint(len(p) == 26 and all(x >= 0 for x in p) and sum(p) > 0)","expected_output":"True"},{"test":"m = train(['tom', 'tom', 'bob'] * 30)\np = predict(m, '_om')\nprint('abcdefghijklmnopqrstuvwxyz'[max(range(26), key=lambda i: p[i])])","expected_output":"t"},{"test":"m = train(['ann', 'amy'] * 30)\np = predict(m, 'a_n')\nprint('abcdefghijklmnopqrstuvwxyz'[max(range(26), key=lambda i: p[i])])","expected_output":"n"},{"test":"import math\nm = train(['bob', 'rob', 'tom'] * 30)\np = predict(m, '_ob')\nprint(all(math.isfinite(x) for x in p))","expected_output":"True"}],"lower_is_better":true,"approved_user_libraries":["numpy","torch","math","collections","random","time"],"data_info":"Karpathy's makemore names.txt (32,033 lowercase names, MIT) for training. Scored: real US baby names (SSA data, CC0 via the R package babynames) that are not in names.txt, each with one letter hidden; 4,000 on Submit, a different 1,000 on Run. The harness reports bits per hidden letter, accuracy, the training and prediction time, and a left-bigram baseline.","time_limits":{"test":240,"dev":150},"example":{"input":"train(names) on names.txt, then predict(model, 'em_ly')","output":"[0.01, 0.0, ..., 0.62 (i), ...] (26 numbers for a-z); cost = -log2(p['i'] / sum)"},"gpu":false,"description":"Each name below has one letter hidden: `em_ly`, `_ason`, `kayl_`. Train any model you like on the 32,033 names in Karpathy's makemore list, then say how likely each letter is to fill the gap. The leaderboard ranks by **bits per hidden letter** on names your model has never seen, lower is better.\n\n**Contract.** Implement two functions:\n\n- `train(names: list[str]) -> model` receives the training names (lowercase a-z) and returns any object.\n- `predict(model, masked: str) -> list[float]` receives a lowercase name with exactly one `_` and returns 26 non-negative numbers, one for each letter `a` to `z`. The harness divides them by their sum, so they need not add up to 1.\n\n**What is scored.** The scored names are real names that are **not** in the training list, so you cannot look an answer up; your model has to have learned how names are spelled. Submit scores 4,000 of them; Run scores a different 1,000. The hidden letter can be anywhere, including the first or the last letter.\n\n**Budget.** Submit: `train` must return within 90 seconds of wall-clock time on one CPU, and the 4,000 predictions must finish within 60 seconds. Run: the same 90 seconds to train, 30 to predict its 1,000 names.\n\n**Score.** bits per hidden letter = the average of -log2(probability you gave the true letter). A true letter you gave less than 1e-6 costs 19.9 bits, so never rule a letter out completely. The harness also reports your accuracy (how often your most likely letter was right) and a baseline that only looks at the letter before the gap. Clearing 3.3 counts as solved; everything below that is leaderboard.\n\n**Gates.** The score is set to 99.0 (a fail) if `train` or the predictions run over budget, or if `predict` returns anything other than 26 finite, non-negative numbers that are not all zero.","tags":["language-modeling","makemore","n-gram","mlp","open-ended","leaderboard"],"id":"c69c29bb-d5cd-40b4-bfa1-c76c63334cbd","img_type":"pytorch","dataset_id":"names","evaluation_metric":"bits_per_letter","difficulty":"medium","min_eval_metric":3.3,"category":"Language Modeling","title":"Fill In the Missing Letter","dataset":"Names (Karpathy makemore)","time_limits_seconds":{"dev":150,"test":240}},{"created_at":"2026-09-23T11:37:22.205327+00:00","constraints":["numpy only; no network access","quantize(W, bits) -> dict of numpy arrays containing 'codes' (integer array of W's shape spanning fewer than 2**bits levels); dequantize(q) -> float array of W's shape, using only q","Total bits (codes at `bits` each, every other array at its dtype width) must not exceed (bits + 0.5) per weight"],"type":"general","last_updated":"2026-09-23T11:37:22.205327+00:00","test_cases":[{"test":"import numpy as np\nq = quantize(np.random.default_rng(0).normal(size=(8, 64)).astype(np.float32), 4)\nprint(isinstance(q, dict) and 'codes' in q and q['codes'].shape == (8, 64))","expected_output":"True"},{"test":"import numpy as np\nW = np.random.default_rng(0).normal(size=(8, 64)).astype(np.float32)\nq = quantize(W, 4)\nprint(int(q['codes'].max()) - int(q['codes'].min()) < 16, dequantize(q).shape == W.shape)","expected_output":"True True"},{"test":"import numpy as np\nW = np.random.default_rng(1).normal(size=(16, 128)).astype(np.float32)\nW[:, 5] *= 40\nq = quantize(W, 4)\nW_hat = dequantize(q)\nprint(float(np.linalg.norm(W_hat - W) / np.linalg.norm(W)) < 0.15)","expected_output":"True"}],"lower_is_better":true,"approved_user_libraries":["numpy"],"data_info":"Synthetic weights generated inside the grader with numpy (no downloads): Gaussian weights with a few input channels scaled 15 to 40 times and sparse spikes 20 to 60 times, for a 512 -> 512 -> 128 network on Submit and 256 -> 256 -> 64 on Run, evaluated on 512 Gaussian calibration inputs.","time_limits":{"test":120,"dev":60},"example":{"input":"quantize(W of shape (512, 512), bits=4)","output":"a dict such as {'codes': uint8 (512, 512), 'scale': float16 (512, 8), 'zero': float16 (512, 8)}; the grader reports bits_per_weight, weight_rel_error, output_rel_error and test_acc = output_rel_error"},"model_specs":"Your choice of scheme: scale granularity, symmetric or asymmetric grids, codebooks, outlier side channels, rounding strategy. The grader owns a hidden two-layer ReLU network with outlier channels and the calibration inputs; it counts your bits and measures the relative change in the network's outputs.","gpu":false,"description":"# Design Your Own Quantizer\n\nYou are given the weight matrices of a small network whose weights contain a few large outlier channels, the way real transformer layers do, and a budget of four bits per weight on average. Compress each matrix into an integer representation plus whatever side information you like, then reconstruct it. The grader measures how much the network's outputs move on held-out inputs, and it counts every bit you used.\n\n```python\ndef quantize(W, bits):\n    ...\n    return q          # a dict of numpy arrays\n\ndef dequantize(q):\n    ...\n    return W_hat      # float array with W's shape\n```\n\n- `W` is a float32 array of shape `(out_features, in_features)`; `bits` is `4`.\n- `q` must be a dict whose values are numpy arrays. It must contain `'codes'`, an integer array of `W`'s shape whose values span at most `2 ** bits` distinct integers (`max - min < 2 ** bits`). Every other array is side information: scales, zero points, a codebook, outlier positions and values, anything.\n- `dequantize` receives only `q`. It must not read anything else.\n\n## How it is graded\n\nThe bit count is `codes.size x bits` plus, for every other array in `q`, its element count times its dtype width in bits (a float16 scale costs 16 bits, a float32 codebook entry 32, an int32 index 32). The count must not exceed `(bits + 0.5) x W.size`, so per-channel scales, group scales, a small codebook and a sparse set of outliers all fit, and hiding the original matrix does not.\n\nThe grader quantizes both layers of a hidden two-layer network, runs the original and the reconstructed network on hidden calibration inputs, and reports the relative output error `||z_hat - z|| / ||z||`. Lower is better. The bar is set so that a single scale per matrix fails and the standard techniques pass. Only numpy is available.\n","tags":["quantization","int4","outliers","group-quantization","nf4","inference","open-ended"],"id":"c8e5b2d4-9f1a-4e6c-b7d3-2a4f6e8c0b9d","difficulty":"hard","evaluation_metric":"output_rel_error","schema":"quantize(W: np.ndarray float32 (out_features, in_features), bits: int) -> dict[str, np.ndarray]; dequantize(q: dict) -> np.ndarray (out_features, in_features)","min_eval_metric":0.3,"category":"Inference","title":"Design Your Own Quantizer","time_limits_seconds":{"dev":60,"test":120}},{"created_at":"2026-10-26T00:10:44.620000+00:00","type":"general","test_cases":[{"test":"import torch\nz = torch.tensor([[1.0, 2.0, 3.0], [0.5, -1.0, 2.0]])\nlp = log_softmax(z)\nprint(tuple(lp.shape) == (2, 3) and bool(torch.allclose(lp.exp().sum(1), torch.ones(2), atol=1e-5)))","expected_output":"True"},{"test":"import torch\nz = torch.tensor([[1.0, 2.0, 3.0]], requires_grad=True)\nL = cross_entropy(z, torch.tensor([2]))\nL.backward()\nprint(L.dim() == 0 and z.grad is not None and abs(float(z.grad.sum())) < 1e-5)","expected_output":"True"},{"test":"import torch\nz = torch.tensor([[40.0, 0.0, 0.0]], dtype=torch.bfloat16, requires_grad=True)\nL = cross_entropy(z, torch.tensor([0]))\nL.backward()\nprint(float(z.grad[0, 0]) < 0.0)","expected_output":"True"},{"test":"import torch\nzt = torch.tensor([[2.0, 1.0, 0.0]], dtype=torch.bfloat16)\nzs = zt.clone().requires_grad_(True)\nL = soft_target_cross_entropy(zs, zt)\nL.backward()\nprint(float(zs.grad.abs().max()) == 0.0)","expected_output":"True"}],"lower_is_better":true,"approved_user_libraries":["torch","numpy","math"],"data_info":"No dataset: the battery is generated from seeded random logits inside the harness (hard targets at margins -8 to 60 with 3/16/128 classes, log-softmax at the same margins, soft targets at student-teacher gaps 0 to 3), evaluated in bfloat16 and float32 on CPU against float64 references in the margin form. Run: seed 1, 8 margins, 2 class counts, 5 gaps. Submit: seed 7, 15 margins, 3 class counts, 10 gaps. The report shows the score, the three mean log10 errors and the five worst cases.","time_limits":{"test":240,"dev":120},"example":{"input":"z = torch.tensor([[9.0, -9.0, -9.0]], dtype=torch.float32, requires_grad=True); cross_entropy(z, torch.tensor([0])).backward()","output":"loss about 3.046e-8 and z.grad about [-3.046e-8, 1.523e-8, 1.523e-8] (sums to zero); the standard functions return loss 0 and a target gradient of exactly 0"},"gpu":false,"description":"Every deep-learning framework ships a softmax, a log-softmax and a cross-entropy that subtract the row maximum and call it numerically stable. Barron, Gnanapragasam and Tschannen (2026) show they are not: once the correct logit leads the others by more than a precision cliff (about 5.5 in bfloat16, 16.6 in float32) the target's gradient rounds to exactly zero while the other entries do not, so the gradient stops summing to zero (**Softmax Collapse**), and a student scored against its own teacher's distribution receives a nonzero gradient (**Softmax Cancellation**). Their fix recomputes everything in log space with softplus, expm1 and log1p, in the input precision, with no internal upcasting. This lab asks for your version. The leaderboard ranks by **score**, lower is better: the mean log10 error of your losses and gradients against exact float64 values.\n\n**Contract.** Implement three functions on `(batch, classes)` tensors:\n\n- `log_softmax(z) -> tensor` of the same shape: row-wise log-probabilities.\n- `cross_entropy(z, targets) -> scalar`: mean hard-target cross-entropy, `targets` an integer tensor `(batch,)`.\n- `soft_target_cross_entropy(z_s, z_t) -> scalar`: mean cross-entropy of student logits against the teacher distribution `softmax(z_t)`; the gradient flows to `z_s` only.\n\nEach is called on leaf tensors in **bfloat16 and float32** and differentiated with autograd, so your gradient is whatever autograd produces from your forward, or whatever a `torch.autograd.Function` you write returns. Losses must be scalars in the input dtype.\n\n**Battery.** Hard targets: random logits with the target lifted to a chosen margin, from -8 up to 60, with 3, 16 and 128 classes. Log-softmax: the same margins, scored on every entry and on the target entry in particular. Soft targets: a student equal to its teacher, and students perturbed by gaps from 1e-7 to 3. The references are computed in float64 in the margin form, which is exact at every margin in the battery.\n\n**Score.** For every case: relative error of the loss, relative error of the gradient and the zero-sum violation of the gradient rows, each capped at 1 and taken as log10 (so an exactly wrong answer costs 0 and a float32-exact one about -7). score = 0.6 x mean gradient error + 0.2 x mean loss error + 0.2 x mean zero-sum error. The standard PyTorch functions score about -2.4. Clearing -3.5 counts as solved; everything below that is leaderboard.\n\n**Gates.** The score is set to 99.0 (a fail) if any operation inside your functions produces a floating tensor wider than the input dtype (a float64 anywhere, or a float32 while the inputs are bfloat16: the harness watches every dispatched op), if a loss is not a scalar of the input dtype, if any loss or gradient is non-finite, if the loss does not depend on the logits, or if the evaluation runs over its time budget. Run uses a smaller battery and seed than Submit.","tags":["softmax","cross-entropy","numerical-stability","bfloat16","open-ended","leaderboard"],"id":"c91a1547-eeba-4b30-bbd3-ecdf65b55bb7","img_type":"pytorch","dataset_id":"synthetic","evaluation_metric":"score","difficulty":"hard","min_eval_metric":-3.5,"category":"Numerical Methods","title":"Accurate Softmax Gradients in Low Precision","dataset":"Seeded random logits (generated in the harness)","time_limits_seconds":{"dev":120,"test":240}},{"created_at":"2026-10-26T18:05:33.406000+00:00","type":"general","test_cases":[{"test":"import torch\nW = torch.randn(8, 64)\nb, s = quantize('t.mlp1', W, torch.randn(100, 64))\nprint(b.dtype == torch.uint8 and s.dtype == torch.uint8 and tuple(b.shape) == (8, 2, 16) and tuple(s.shape) == (8, 2))","expected_output":"True"},{"test":"import torch\ngrid = torch.tensor([0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, -0.0, -0.5, -1.0, -1.5, -2.0, -3.0, -4.0, -6.0])\ng = torch.Generator().manual_seed(0)\ncodes = torch.randint(0, 16, (4, 64), generator=g)\ncodes[:, ::32] = 7\nW = grid[codes] * 2.0 ** -3\nb, s = quantize('t.mlp2', W, torch.randn(50, 64))\nv = torch.empty(4, 2, 32)\nv[..., 0::2] = grid[(b & 15).long()]\nv[..., 1::2] = grid[(b >> 4).long()]\nWq = (v * torch.pow(2.0, s.float() - 127)[..., None]).reshape(4, 64)\nprint(bool(torch.equal(Wq, W)))","expected_output":"True"},{"test":"import torch\nb, s = quantize('t.mlp1', torch.zeros(2, 32), torch.randn(10, 32))\nv = torch.tensor([0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, -0.0, -0.5, -1.0, -1.5, -2.0, -3.0, -4.0, -6.0])[(b & 15).long()]\nprint(bool((v == 0).all()) and int(s.max()) < 255)","expected_output":"True"}],"lower_is_better":true,"approved_user_libraries":["torch","numpy","math"],"data_info":"dataset mini-gptoss-mxfp4: the full-precision weights of a 20M-parameter character-level gpt-oss (6 layers, d 256, 8 query and 2 KV heads, window 64 on even layers, 16 experts top-4, expert width 256, untied embeddings, trained on 98M characters of the TinyStories train split). The harness builds the model, captures calibration activations from TinyStories-valid text and evaluates on a disjoint TinyStories-valid slice. quantize receives tensors on the GPU (T4).","time_limits":{"test":300,"dev":180},"example":{"input":"quantize('layers.0.experts.3.mlp1', W (512, 256) float32, X (n, 256) float32) is called for each of the 192 expert matrices","output":"(blocks uint8 (512, 8, 16), scales uint8 (512, 8)); the score is the KL divergence of the decoded model from full precision on held-out text, in millibits per character: about 3.4 for round-to-nearest, 2.2 for GPTQ"},"gpu":true,"description":"gpt-oss ships its mixture-of-experts weights in **MXFP4**: every block of 32 consecutive weights shares one power-of-two scale, and each weight keeps only a 4-bit floating-point value. The experts hold about 90% of gpt-oss's parameters, so this format is what lets the 120B model fit on a single 80 GB GPU. How you choose the scales and the 4-bit values decides how much of the model survives. This lab hands you a small gpt-oss and asks you to quantize its experts as well as you can, by any method. The leaderboard ranks by how far the quantized model's predictions drift from the original, **KL divergence in millibits per character**, lower is better.\n\n**The model.** A 20M-parameter character-level language model with the gpt-oss architecture: RMSNorm, grouped-query attention with learned attention sinks, RoPE, sliding-window layers alternating with full-attention layers, and a 16-expert, top-4 MoE whose experts use gpt-oss's clamped SwiGLU. It was trained on TinyStories. Its 6 layers × 16 experts give 192 expert weight matrices, 94% of all parameters. Everything else (attention, router, norms, embeddings, biases) stays in full precision, as in gpt-oss.\n\n**Contract.** Implement `quantize(name, W, X) -> (blocks, scales)`, called once per expert matrix:\n\n- `name`: for example `\"layers.3.experts.11.mlp1\"`. `mlp1` has shape `(512, 256)`; `mlp2` has shape `(256, 256)`.\n- `W`: the full-precision weight, a float32 tensor of shape `(out, in)`. Blocks of 32 run along the input dimension.\n- `X`: calibration inputs for that matrix, a float32 tensor of shape `(n, in)`. These are the activations this expert actually receives on calibration text, taken from the full-precision model, with a few thousand rows per expert. Use them or ignore them.\n- Return `blocks`, uint8 of shape `(out, in // 32, 16)`, with two 4-bit codes per byte, and `scales`, uint8 of shape `(out, in // 32)`. This is gpt-oss's own checkpoint layout:\n  - The low nibble holds the even element of each pair and the high nibble the odd one.\n  - A code is a sign bit (8) plus a 3-bit magnitude index into {0, 0.5, 1, 1.5, 2, 3, 4, 6}.\n  - A scale byte `b` means $2^{b-127}$. Byte 255 is NaN.\n\nThe harness decodes your bytes itself, so the result is MXFP4 by construction.\n\n**Score.** The mean KL divergence $\\mathrm{KL}(p_{\\text{full}} \\,\\|\\, p_{\\text{MXFP4}})$ between the two models' next-character distributions over held-out TinyStories text, in millibits per character: 1.0 means the quantized model's predictions carry one thousandth of a bit of extra surprise per character. KL is what quantization actually changes and, unlike a difference in loss, it does not swing with which characters happen to be in the text. Submit evaluates 65,536 characters with 64 calibration windows; Run evaluates 16,384 characters with 32. The report also gives both models' bits per character (the full-precision model scores about 0.78). The score is at most 5.0 to count as solved; everything below that is leaderboard.\n\n**Gates.** The score is set to 9999 (a fail) if a returned tensor has the wrong dtype or shape, if a scale byte is 255, if a decoded weight is not finite, if `quantize` opens the dataset files, if anything modifies the model's weights, or if the calls to `quantize` take more than 150 s in total (90 s on Run). The report lists both bits-per-character values and the time your quantizer used.","tags":["quantization","mxfp4","gpt-oss","mixture-of-experts","gptq","open-ended","leaderboard"],"id":"cbb94f0c-9f2c-4f98-a793-84a0e75044a6","img_type":"pytorch","dataset_id":"mini-gptoss-mxfp4","evaluation_metric":"kl_mbits_per_char","difficulty":"hard","min_eval_metric":5.0,"category":"Inference","title":"Best MXFP4 Quantization","dataset":"Mini gpt-oss (character-level, TinyStories) weights + TinyStories-valid text","time_limits_seconds":{"dev":180,"test":300}},{"created_at":"2026-11-02T16:34:42.431000+00:00","type":"general","constraints":["train gets 30 s on a T4 (wall), with CPU time across all threads capped at 15% more plus 2 s","logprobs gets 24 s in total; it runs in fresh processes from a torch.save copy of the model, so it cannot keep state","position t may use only bytes 0..t of its own row; rows must be finite log-probabilities","no files, no network, no other processes; nothing pretrained can be loaded","attributes may be assigned only on self, inside a method defined in a class body","source capped at 40,000 characters, 250 numeric literals, 400 characters of string constants"],"test_cases":[{"test":"import contextlib\nimport io\nimport math\nimport torch\n_dev = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n_text = b\"The cat sat on the mat. The dog sat on the log. \" * 120 + bytes([30]) + b\"def add(a, b):\\n    return a + b\\n\" * 120\n_x = torch.tensor([list(b\"The cat sat on the mat. The dog sat on the log. The cat sat on the\")[:64],\n                   list(bytes(range(200, 208)) * 8)], device=_dev)\nwith contextlib.redirect_stdout(io.StringIO()):     # your own prints are fine: they stay out of the comparison\n    _m = train(_text, 3.0)\n    _lp = torch.as_tensor(logprobs(_m, _x)).float()\nprint(tuple(_lp.shape))","expected_output":"(2, 64, 256)"},{"test":"import contextlib\nimport io\nimport math\nimport torch\n_dev = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n_text = b\"The cat sat on the mat. The dog sat on the log. \" * 120 + bytes([30]) + b\"def add(a, b):\\n    return a + b\\n\" * 120\n_x = torch.tensor([list(b\"The cat sat on the mat. The dog sat on the log. The cat sat on the\")[:64],\n                   list(bytes(range(200, 208)) * 8)], device=_dev)\nwith contextlib.redirect_stdout(io.StringIO()):     # your own prints are fine: they stay out of the comparison\n    _m = train(_text, 3.0)\n    _lp = torch.as_tensor(logprobs(_m, _x)).float()\nprint(bool(torch.isfinite(_lp).all()) and float(torch.logsumexp(_lp, -1).abs().max()) < 1e-3)","expected_output":"True"},{"test":"import contextlib\nimport io\nimport math\nimport torch\n_dev = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n_text = b\"The cat sat on the mat. The dog sat on the log. \" * 120 + bytes([30]) + b\"def add(a, b):\\n    return a + b\\n\" * 120\n_x = torch.tensor([list(b\"The cat sat on the mat. The dog sat on the log. The cat sat on the\")[:64],\n                   list(bytes(range(200, 208)) * 8)], device=_dev)\nwith contextlib.redirect_stdout(io.StringIO()):     # your own prints are fine: they stay out of the comparison\n    _m = train(_text, 3.0)\n    _lp = torch.as_tensor(logprobs(_m, _x)).float()\n_x2 = _x.clone()\n_x2[:, 41:] = 101\nwith contextlib.redirect_stdout(io.StringIO()):\n    _lp2 = torch.as_tensor(logprobs(_m, _x2)).float()\nprint(float((_lp2[:, :41] - _lp[:, :41]).abs().max()) < 0.01)","expected_output":"True"},{"test":"import contextlib\nimport io\nimport math\nimport torch\n_dev = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n_text = b\"The cat sat on the mat. The dog sat on the log. \" * 120 + bytes([30]) + b\"def add(a, b):\\n    return a + b\\n\" * 120\n_x = torch.tensor([list(b\"The cat sat on the mat. The dog sat on the log. The cat sat on the\")[:64],\n                   list(bytes(range(200, 208)) * 8)], device=_dev)\nwith contextlib.redirect_stdout(io.StringIO()):     # your own prints are fine: they stay out of the comparison\n    _m = train(_text, 3.0)\n    _lp = torch.as_tensor(logprobs(_m, _x)).float()\nprint(float((_lp[0, 10] - _lp[0, 20]).abs().max()) > 0.01)","expected_output":"True"},{"test":"import contextlib\nimport io\nimport math\nimport torch\n_dev = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n_text = b\"The cat sat on the mat. The dog sat on the log. \" * 120 + bytes([30]) + b\"def add(a, b):\\n    return a + b\\n\" * 120\n_x = torch.tensor([list(b\"The cat sat on the mat. The dog sat on the log. The cat sat on the\")[:64],\n                   list(bytes(range(200, 208)) * 8)], device=_dev)\nwith contextlib.redirect_stdout(io.StringIO()):     # your own prints are fine: they stay out of the comparison\n    _m = train(_text, 3.0)\n    _lp = torch.as_tensor(logprobs(_m, _x)).float()\n_bits = float(-_lp[1, 31:63].gather(-1, _x[1, 32:64, None]).mean()) / math.log(2)\nprint(_bits < 4.0)","expected_output":"True"}],"lower_is_better":true,"approved_user_libraries":["numpy","torch","math","random","time","collections","itertools","copy"],"data_info":"t2b-mix v1, a mixed byte corpus built for the From Tokens to Bytes collection from Project Gutenberg books (public domain in the USA) and permissively licensed GitHub code. Training bytes (14.2 MB): English prose, French, German, Spanish, Italian, Portuguese and Chinese books, Python, C, JavaScript, Go and Rust files, and LaTeX math books, every document shuffled and joined by 0x1E. Scored: excerpts of 512 bytes from Finnish, Hungarian, Greek, Japanese, OCaml, Prolog, Lean 4, Fortran, Haskell documents that never appear in training. Reported, unscored: excerpts from unseen documents of the four training domains. Run and Submit use different halves of the hidden documents. Your code never reads the data files.","time_limits":{"test":120,"dev":120},"example":{"input":"x = the bytes of 'Kalevala on suomalainen' as a (1, 23) tensor; lp = logprobs(model, x)","output":"lp has shape (1, 23, 256); lp[0, 3] is the model's log-probability for each possible byte after 'Kale', and the score charges -log2 of exp(lp[0, 3, ord('v')])"},"gpu":true,"description":"Cartesia's two posts \"From Tokens to Bytes\" argue that the way a model chunks its input changes how well its training transfers to data it never saw. Their H-Net needs less compute than a BPE Transformer to reach the same loss, and the gap grows away from the training mix: 1.28x on in-distribution validation, a median of 2.04x on the programming languages it trained on, and a median of 3.10x on ten programming languages outside the mix, from 2.19x on Haskell to 5.37x on Prolog (all the posts' numbers, from compute-optimal scaling ladders of billion-parameter models).\n\nThis lab asks the same question at toy scale. You get **30 s on a T4** to train any model you like, tokenized or not, on a mixed corpus of English, six other languages, five programming languages and LaTeX math. You are scored on text from languages and programming languages that are **not in it**: Finnish, Hungarian, Greek, Japanese, OCaml, Prolog, Lean 4, Fortran, Haskell. The score is **bits per byte**. Lower is better.\n\n### What you write\n\n```python\ndef train(train_bytes, seconds):\n    ...\n    return model            # anything torch.save can pickle\n\ndef logprobs(model, x):\n    ...\n    return lp               # shape (B, T, 256): log-probabilities of the next byte\n```\n\n- `train_bytes` is a `bytes` object of 14.2 MB: every training document of the corpus, shuffled, joined by the byte `0x1E`. `seconds` is 30.\n- `x` is a `torch.LongTensor` of shape (32, 512) on the GPU, holding byte values 0 to 255. Each row is an excerpt of 512 bytes that starts at a random offset inside a hidden document, often in the middle of a word or of a UTF-8 character.\n- `lp[b, t, v]` must be $\\log P(x_{b,t+1} = v \\mid x_{b,0}, \\dots, x_{b,t})$. Position $t$ may use bytes $0$ to $t$ of its own row and nothing else. The last position predicts a byte the grader does not show you, so it is not scored.\n- Each row of 256 values must be finite log-probabilities: their logsumexp must be within 0.001 of 0. `torch.log_softmax` does this.\n- Tokenize inside if you want, but the answer is per byte. A token model has to turn its token probabilities into a next-byte distribution after a prefix that can end in the middle of a token. That is the prompt boundary problem from the second post.\n\n### How it is graded\n\nFor each of the 9 held-out domains the grader takes 64 excerpts of 512 bytes and computes\n\n$$\\text{bpb}_d = \\frac{1}{N_d} \\sum_{\\text{scored bytes}} -\\log_2 P(\\text{byte} \\mid \\text{bytes before it in its excerpt})$$\n\nThe score is the plain mean of the 9 values, so every domain counts the same. **Lower is better.** A score of **4.50** or lower passes, and below that you are competing on the number. The report also shows each domain's value and, unscored, the same measure on unseen documents of the four training domains (`val_bpb`), so you can see how much of your model's skill transfers.\n\n- **Run** uses one half of the hidden documents and shows what your code prints and the full text of errors. **Submit** uses the other half and shows neither.\n- Offsets are drawn fresh on every run. Over 6 Submit runs the reference moved by up to 0.02, so judge a small change over more than one run.\n- Run and Submit each take about 55 s.\n\n### How your code runs\n\n`train` runs in its own process. When it returns, the grader saves the model with `torch.save`, and two fresh processes load that copy and answer `logprobs` for half of the excerpts each, one process after the other, in batches of 32. So nothing `logprobs` sees can change how it scores a later excerpt.\n\nEvery excerpt is also sent to the other process with the bytes after a secret position replaced by other text, and a quarter are sent again unchanged. Predictions that should agree must agree to within 0.01 nats. That checks four things at once: no peeking at later bytes, no state kept between calls, no row reading another row, and the same answer every time (switch dropout off).\n\n### Rules\n\nA run that breaks one prints a score of 99 and fails.\n\n- `train` gets 30 s of wall time, and 15% more than that plus 2 s of CPU time across all threads. `logprobs` gets 24 s in total over all batches. Loading your file and your model gets 15 s each.\n- The saved model may be at most 1024 MB, and must survive `torch.save` and `torch.load`: no lambdas or functions defined inside other functions in it.\n- Your code gets no files, no network and no other processes. The grader owns all data access.\n- Allowed imports: numpy, torch, math, random, time, collections, itertools, copy, heapq, bisect, re, statistics, warnings, typing, enum, abc.\n- Write ordinary classes freely, including `class Net(nn.Module)`. Outside a method of a class, attributes may not be assigned: write `x.data[:] = ...` rather than `x.data = ...`, and call `torch.backends` settings as functions where one exists.\n- Source limits, so no model or text can be pasted in: 40,000 characters, 14,000 without comments and docstrings, 250 numeric literals of at most 10 characters each and 600 characters in total, 400 characters of string and bytes constants, 32 items in any literal list, tuple, set or dict, 220 ASCII names of at most 24 characters, and 60 functions and classes.\n\nNew to this? The learn section explains the measure and the marginalization problem, and lists what we measured.","tags":["bits-per-byte","byte-level","tokenization","out-of-distribution","transfer","marginalization","prompt-boundary","language-modeling","pytorch","open-ended","leaderboard","tokens-to-bytes"],"id":"cd60e3df-139d-40b0-85d8-ca36c44af9fd","img_type":"pytorch","dataset_id":"t2b-mix","evaluation_metric":"bits_per_byte","difficulty":"hard","min_eval_metric":4.5,"category":"NLP","title":"Best Byte Model on Data It Never Saw","dataset":"Tokens to Bytes mixed corpus (t2b-mix v1)","time_limits_seconds":{"dev":120,"test":120}},{"created_at":"2026-10-27T19:41:20.114000+00:00","type":"general","test_cases":[{"test":"\ndef _tiny_cfg(V=96, D=64, L=2, H=4, HKV=2, F=96, S=160):\n    lay, off = {}, 0\n    def add(name, shape):\n        nonlocal off\n        n = 1\n        for s in shape:\n            n *= s\n        lay[name] = {\"offset\": off, \"shape\": list(shape)}\n        off += n\n    hd = D // H\n    add(\"tok_emb\", (V, D))\n    for l in range(L):\n        p = \"layers.%d.\" % l\n        add(p + \"attn_norm\", (D,)); add(p + \"wq\", (D, H * hd)); add(p + \"wk\", (D, HKV * hd)); add(p + \"wv\", (D, HKV * hd))\n        add(p + \"wo\", (H * hd, D)); add(p + \"ffn_norm\", (D,)); add(p + \"w_gate\", (D, F)); add(p + \"w_up\", (D, F)); add(p + \"w_down\", (F, D))\n    add(\"final_norm\", (D,)); add(\"lm_head\", (D, V))\n    return {\"vocab\": V, \"dim\": D, \"n_layers\": L, \"n_heads\": H, \"n_kv_heads\": HKV, \"head_dim\": hd, \"ffn_dim\": F,\n            \"max_seq\": S, \"prompt_len\": 8, \"decode_steps\": 8, \"rope_theta\": 10000.0, \"norm_eps\": 1e-5,\n            \"n_weights\": off, \"weights\": lay}\n\nsrc = codegen(_tiny_cfg())\nprint(isinstance(src, str) and all(name in src for name in (\"llm_create\", \"llm_prefill\", \"llm_decode\", \"llm_free\")))\n","expected_output":"True"},{"test":"\ndef _tiny_cfg(V=96, D=64, L=2, H=4, HKV=2, F=96, S=160):\n    lay, off = {}, 0\n    def add(name, shape):\n        nonlocal off\n        n = 1\n        for s in shape:\n            n *= s\n        lay[name] = {\"offset\": off, \"shape\": list(shape)}\n        off += n\n    hd = D // H\n    add(\"tok_emb\", (V, D))\n    for l in range(L):\n        p = \"layers.%d.\" % l\n        add(p + \"attn_norm\", (D,)); add(p + \"wq\", (D, H * hd)); add(p + \"wk\", (D, HKV * hd)); add(p + \"wv\", (D, HKV * hd))\n        add(p + \"wo\", (H * hd, D)); add(p + \"ffn_norm\", (D,)); add(p + \"w_gate\", (D, F)); add(p + \"w_up\", (D, F)); add(p + \"w_down\", (F, D))\n    add(\"final_norm\", (D,)); add(\"lm_head\", (D, V))\n    return {\"vocab\": V, \"dim\": D, \"n_layers\": L, \"n_heads\": H, \"n_kv_heads\": HKV, \"head_dim\": hd, \"ffn_dim\": F,\n            \"max_seq\": S, \"prompt_len\": 8, \"decode_steps\": 8, \"rope_theta\": 10000.0, \"norm_eps\": 1e-5,\n            \"n_weights\": off, \"weights\": lay}\n\nimport ctypes, os, subprocess, tempfile, time\nimport numpy as np\ndef _tiny_build(cfg):\n    d = tempfile.mkdtemp()\n    with open(os.path.join(d, \"m.c\"), \"w\") as fh:\n        fh.write(codegen(cfg))\n    r = subprocess.run([\"cc\", \"-O3\", \"-march=x86-64-v3\", \"-fPIC\", \"-shared\", \"-std=gnu17\", \"-o\", os.path.join(d, \"m.so\"),\n                        os.path.join(d, \"m.c\"), \"-lm\"], capture_output=True, text=True)\n    if r.returncode != 0:\n        print(r.stderr[-800:])\n        return None\n    lib = ctypes.CDLL(os.path.join(d, \"m.so\"))\n    lib.llm_create.restype = ctypes.c_void_p\n    lib.llm_create.argtypes = [ctypes.c_void_p]\n    lib.llm_prefill.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p]\n    lib.llm_decode.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p]\n    lib.llm_free.argtypes = [ctypes.c_void_p]\n    return lib\n\nlib = _tiny_build(_tiny_cfg())\nprint(lib is not None and all(hasattr(lib, n) for n in (\"llm_create\", \"llm_prefill\", \"llm_decode\", \"llm_free\")))\n","expected_output":"True"},{"test":"\ndef _tiny_cfg(V=96, D=64, L=2, H=4, HKV=2, F=96, S=160):\n    lay, off = {}, 0\n    def add(name, shape):\n        nonlocal off\n        n = 1\n        for s in shape:\n            n *= s\n        lay[name] = {\"offset\": off, \"shape\": list(shape)}\n        off += n\n    hd = D // H\n    add(\"tok_emb\", (V, D))\n    for l in range(L):\n        p = \"layers.%d.\" % l\n        add(p + \"attn_norm\", (D,)); add(p + \"wq\", (D, H * hd)); add(p + \"wk\", (D, HKV * hd)); add(p + \"wv\", (D, HKV * hd))\n        add(p + \"wo\", (H * hd, D)); add(p + \"ffn_norm\", (D,)); add(p + \"w_gate\", (D, F)); add(p + \"w_up\", (D, F)); add(p + \"w_down\", (F, D))\n    add(\"final_norm\", (D,)); add(\"lm_head\", (D, V))\n    return {\"vocab\": V, \"dim\": D, \"n_layers\": L, \"n_heads\": H, \"n_kv_heads\": HKV, \"head_dim\": hd, \"ffn_dim\": F,\n            \"max_seq\": S, \"prompt_len\": 8, \"decode_steps\": 8, \"rope_theta\": 10000.0, \"norm_eps\": 1e-5,\n            \"n_weights\": off, \"weights\": lay}\n\nimport ctypes, os, subprocess, tempfile, time\nimport numpy as np\ndef _tiny_build(cfg):\n    d = tempfile.mkdtemp()\n    with open(os.path.join(d, \"m.c\"), \"w\") as fh:\n        fh.write(codegen(cfg))\n    r = subprocess.run([\"cc\", \"-O3\", \"-march=x86-64-v3\", \"-fPIC\", \"-shared\", \"-std=gnu17\", \"-o\", os.path.join(d, \"m.so\"),\n                        os.path.join(d, \"m.c\"), \"-lm\"], capture_output=True, text=True)\n    if r.returncode != 0:\n        print(r.stderr[-800:])\n        return None\n    lib = ctypes.CDLL(os.path.join(d, \"m.so\"))\n    lib.llm_create.restype = ctypes.c_void_p\n    lib.llm_create.argtypes = [ctypes.c_void_p]\n    lib.llm_prefill.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p]\n    lib.llm_decode.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p]\n    lib.llm_free.argtypes = [ctypes.c_void_p]\n    return lib\n\n# with a KV cache, one decode step costs about the same after 140 tokens as after 2\ncfg = _tiny_cfg()\nlib = _tiny_build(cfg)\nw = (np.random.default_rng(0).standard_normal(cfg[\"n_weights\"]) * 0.05).astype(np.float32)\nP = ctypes.c_void_p\ndef _per_step(n_prompt):\n    st = lib.llm_create(P(w.ctypes.data))\n    toks = (np.arange(n_prompt) % cfg[\"vocab\"]).astype(np.int32)\n    out = np.zeros(cfg[\"vocab\"], np.float32)\n    lib.llm_prefill(st, P(toks.ctypes.data), n_prompt, P(out.ctypes.data))\n    t = time.perf_counter()\n    for i in range(10):\n        lib.llm_decode(st, i, P(out.ctypes.data))\n    dt = time.perf_counter() - t\n    lib.llm_free(st)\n    return dt\nshort = min(_per_step(2) for _ in range(3))\nlong_ = min(_per_step(140) for _ in range(3))\nprint(bool(long_ < 4 * short))\n","expected_output":"True"}],"approved_user_libraries":["math","itertools","functools","collections"],"lower_is_better":false,"data_info":"Synthetic Llama-style models generated inside the grader: random float32 weights (unit-variance embeddings, matrices scaled by 1/sqrt(fan-in), norms near 1) and random prompt tokens. Run: two models with fixed seeds (dim 256 / 4 layers / GQA 8:2, and dim 192 / 3 layers / GQA 6:3). Submit: four held-out models (dim 224-384, 3-6 layers, vocab up to 1024) with fresh random weights and prompts every run.","time_limits":{"test":300,"dev":150},"example":{"input":"codegen(cfg) with cfg['dim'] = 256, cfg['n_layers'] = 4, cfg['n_heads'] = 8, cfg['n_kv_heads'] = 2, cfg['vocab'] = 512, cfg['weights']['layers.0.wq'] = {'offset': 131328, 'shape': [256, 256]}, ...","output":"a C translation unit exporting llm_create/llm_prefill/llm_decode/llm_free; the grader reports e.g. run-a: baseline 45.7 ms, yours 21.6 ms, speedup 2.11, max relative logit error 1.6e-06"},"gpu":false,"description":"Weeks 9-10 of the course put a real language model through your compiler. Here you are the back end: write a Python function that, given a model's exact shapes, **generates C source** for running it. The grader compiles your C, runs a prompt through it and then decodes token by token, and times it against a baseline compiled in the same container. The leaderboard ranks by **speedup over the baseline, higher is better**.\n\n**Contract.** Define `codegen(cfg) -> str`. It is called once per model and returns one C translation unit that exports:\n\n```c\nvoid *llm_create(const float *weights);\nvoid  llm_prefill(void *state, const int *tokens, int n, float *logits);\nvoid  llm_decode(void *state, int token, float *logits);\nvoid  llm_free(void *state);\n```\n\n- `llm_create` gets the model's weights: one read-only float32 array of `cfg[\"n_weights\"]` values, not necessarily 32-byte aligned, valid until `llm_free`. It returns your state. Its time is not part of the score but is capped at 3 s per call.\n- `llm_prefill` runs a prompt of `n` tokens (positions `0..n-1`) and writes the `vocab` logits of the last position.\n- `llm_decode` appends one token at the next position and writes its `vocab` logits.\n- `llm_free` releases everything. Every repetition starts with a fresh `llm_create`.\n\n**The model** is a Llama-style decoder. For the residual row `x` of a token at position `p` (0-based), with `rms(x, g) = x / sqrt(mean(x*x) + norm_eps) * g`:\n\n1. `x = tok_emb[token]`.\n2. In each of the `n_layers` blocks:\n   - `h = rms(x, attn_norm)`, `q = h @ wq`, `k = h @ wk`, `v = h @ wv`.\n   - RoPE on every head of `q` and `k`: for `i < head_dim/2`, the angle is `a = p * rope_theta^(-2i/head_dim)` (computed in double precision). The pair `(u, w) = (e[i], e[i + head_dim/2])` becomes `(u cos a - w sin a, u sin a + w cos a)`.\n   - `k` and `v` of position `p` join the cache. Query head `j` attends to KV head `j // (n_heads / n_kv_heads)` over positions `0..p`: scores `q.k / sqrt(head_dim)`, softmax, then the weighted sum of the `v` rows.\n   - `x = x + concat(heads) @ wo`.\n   - `h = rms(x, ffn_norm)` and `x = x + (silu(h @ w_gate) * (h @ w_up)) @ w_down`, with `silu(z) = z / (1 + exp(-z))`.\n3. `logits = rms(x, final_norm) @ lm_head`.\n\nEvery matrix is row-major `[in, out]`.\n\n**cfg** holds `vocab`, `dim`, `n_layers`, `n_heads`, `n_kv_heads`, `head_dim`, `ffn_dim`, `max_seq`, `prompt_len`, `decode_steps`, `rope_theta` (10000.0), `norm_eps` (1e-5), `n_weights` and `weights`. `weights` maps each tensor name to `{\"offset\": ..., \"shape\": [...]}`, with the offset counted in floats into the weight array. The names are `tok_emb [vocab, dim]`, `layers.<l>.attn_norm [dim]`, `layers.<l>.wq [dim, n_heads*head_dim]`, `layers.<l>.wk` and `layers.<l>.wv [dim, n_kv_heads*head_dim]`, `layers.<l>.wo [n_heads*head_dim, dim]`, `layers.<l>.ffn_norm [dim]`, `layers.<l>.w_gate` and `layers.<l>.w_up [dim, ffn_dim]`, `layers.<l>.w_down [ffn_dim, dim]`, `final_norm [dim]` and `lm_head [dim, vocab]`.\n\n**Workload and correctness.**\n\n- For each model, the grader runs several repetitions. Each one uses a fresh random prompt of `prompt_len` tokens, then `decode_steps` decode calls.\n- Each decode call is fed the greedy (argmax) token of a float32 numpy reference.\n- Every logits vector is checked against the reference: `max|yours - ref| <= 1e-4 * max(1, max|ref|)` at every step. Your argmax must also be a token whose reference logit is within that tolerance of the top one.\n- The arithmetic must therefore be float32 or wider.\n- **Run:** two models with fixed weights.\n- **Submit:** four held-out models with fresh random weights and prompts per run (the seed is printed). Their dims range over `dim` 192-384, 3-6 layers, grouped-query and full multi-head attention, `vocab` and `ffn_dim` not always multiples of 8 or 16, prompts of 48-160 tokens, 40-96 decode steps, and `max_seq` up to 224.\n\n**Score.** For each model, `speedup = baseline time / your time`. Time is the wall time of `llm_prefill` plus all `llm_decode` calls (create and free are not counted), as the median over repetitions. Baseline and yours alternate in the same container. The baseline is a straightforward C implementation of the same model with a KV cache: it processes one token at a time with plain loops and is compiled with the same flags. The score is the **geometric mean of the speedups**, and the report shows per-model times, tokens per second and your largest logit error. A score of at least **0.9** counts as solved; everything above that is leaderboard.\n\n**Machine.** Both libraries are built with `cc -O3 -march=x86-64-v3 -fPIC -shared -std=gnu17 -Werror=implicit-function-declaration -Werror=implicit-int -Werror=int-conversion -Werror=incompatible-pointer-types ... -lm` (gcc 12). The CPU is x86-64 with AVX2 and FMA; intrinsics from `immintrin.h` are fine, and AVX-512 is not enabled. You get one CPU core and no threads.\n\n**Rules.** The score is set to 0 and the run fails if any rule is broken.\n\n- **Python.** It may import only `math`, `itertools`, `functools`, `collections`, `textwrap`, `string`, `typing` and `dataclasses`. It may not use file access, introspection (`globals`, `getattr`, frames, `eval`/`exec`) or module tampering. `codegen` may take at most 10 s per model.\n- **Generated C size.** At most 1.5 MB per model.\n- **Headers.** Only `<math.h> <string.h> <stdlib.h> <stdint.h> <stddef.h> <float.h> <limits.h> <stdbool.h> <immintrin.h>`.\n- **Forbidden in the C.** Inline `asm`, `extern`, token pasting (`##`), universal character names, threads, and any I/O, process, signal or environment functions.\n- **Reserved identifiers.** These names are rejected anywhere outside comments and strings, even as variable names: `read write open close remove rename signal raise kill exit abort target section alias constructor destructor visibility system environ stdout stderr stdin omp`.\n- **Linked functions.** After compiling, the library may call only memory functions (`malloc calloc realloc free aligned_alloc posix_memalign memcpy memmove memset memcmp qsort`) and math-library functions.\n- **Budgets.** Compiling may take at most 90 s per model. Your library may run for at most 40 s in total on Run and 80 s on Submit.\n- **Correctness.** A logits mismatch, a wrong greedy token or a non-finite logit fails the run. So does a crash or hang inside your C.","tags":["compilers","code-generation","llm-inference","kv-cache","simd","gemm","performance","open-ended","leaderboard"],"id":"d3350608-bc53-4387-96b4-c67dcd6274b2","dataset_id":"synthetic","img_type":"full","difficulty":"hard","evaluation_metric":"speedup","min_eval_metric":0.9,"category":"Compilers","title":"Fastest Tiny LLM","dataset":"Synthetic Llama-style models (random weights) and random prompts","time_limits_seconds":{"dev":150,"test":300}},{"created_at":"2026-10-27T14:20:33.329000+00:00","type":"general","test_cases":[{"test":"agent = Agent(54, 4, 3000)\nout = [agent.act(s) for s in (0, 7, 7, 53, 20)]\nprint(all(type(a) is int and 0 <= a < 4 for a in out))","expected_output":"True"},{"test":"import random\nimport numpy as np\n\ndef _run_corridor(length, steps, seed):\n    random.seed(seed); np.random.seed(seed)\n    ids = list(range(100, 100 + length))\n    agent = Agent(200, 4, steps)\n    pos, goals, acts = 0, 0, []\n    for t in range(steps):\n        s = ids[pos]\n        a = agent.act(s)\n        acts.append(a)\n        nxt = pos + 1 if a == 2 else pos - 1 if a == 3 else pos\n        nxt = min(max(nxt, 0), length - 1)\n        if nxt == length - 1:\n            goals += 1\n            agent.learn(s, a, 1.0, ids[nxt], True)\n            pos = 0\n        else:\n            agent.learn(s, a, 0.0, ids[nxt], False)\n            pos = nxt\n    return goals, acts\nprint(_run_corridor(6, 400, 3) == _run_corridor(6, 400, 3))","expected_output":"True"},{"test":"import random\nimport numpy as np\n\ndef _run_corridor(length, steps, seed):\n    random.seed(seed); np.random.seed(seed)\n    ids = list(range(100, 100 + length))\n    agent = Agent(200, 4, steps)\n    pos, goals, acts = 0, 0, []\n    for t in range(steps):\n        s = ids[pos]\n        a = agent.act(s)\n        acts.append(a)\n        nxt = pos + 1 if a == 2 else pos - 1 if a == 3 else pos\n        nxt = min(max(nxt, 0), length - 1)\n        if nxt == length - 1:\n            goals += 1\n            agent.learn(s, a, 1.0, ids[nxt], True)\n            pos = 0\n        else:\n            agent.learn(s, a, 0.0, ids[nxt], False)\n            pos = nxt\n    return goals, acts\ngoals, _ = _run_corridor(14, 800, 5)\nprint(goals >= 25)","expected_output":"True"}],"approved_user_libraries":["numpy","math","collections","itertools","functools","random"],"lower_is_better":false,"data_info":"Synthetic gridworld mazes generated inside the grader from fixed seeds. Run: the book's blocking maze (6 x 9, 3,000 steps) and shortcut maze (6 x 9, 6,000 steps) plus four practice mazes (4,000 steps). Submit: eight held-out mazes of 7-11 x 9-15 cells, 6,000 steps each, with one to three hidden changes.","time_limits":{"test":270,"dev":150},"example":{"input":"Agent(n_states=54, n_actions=4, total_steps=3000); then for every real step: a = agent.act(17); agent.learn(17, a, 0.0, 26, False)  (or reward 1.0, done=True when the move entered the goal)","output":"an action in 0..3 per step; the grader reports e.g. goals 212 vs oracle 225 on the blocking maze and a mean score of 91.4 (percent of the oracle's goals)"},"gpu":false,"description":"An agent is dropped into a gridworld maze it has never seen. Every time it reaches the goal it earns +1 and is sent back to the start. Partway through the run, without warning, the maze changes: a wall can close the route the agent relies on, or an opening can appear that makes a shorter route possible. Collect as many goals as you can in a fixed number of real steps. The leaderboard ranks by **percent of the oracle's goals, higher is better**.\n\n**Contract.** Define a class `Agent`:\n\n- `Agent(n_states, n_actions, total_steps)` is created once per maze. `n_actions` is 4. `total_steps` is the number of real steps you get in this maze.\n- `act(state) -> int` returns an action: 0 up, 1 down, 2 right, 3 left. It is called once per real step.\n- `learn(state, action, reward, next_state, done)` is called right after each `act` with what happened. `reward` is 1.0 when the move entered the goal; then `done` is True, `next_state` is the goal's id, and the next `act` call receives the start state. Otherwise `reward` is 0.0 and `done` is False.\n\n**The mazes.**\n\n- A maze is a rectangular grid of `n_states` cells, walls included. Its height and width are not given.\n- States are integer ids `0..n_states-1`, assigned to cells by a random permutation that differs per maze, so an id says nothing about where a cell is.\n- Moves are deterministic, as in the book's Dyna maze. An action moves the agent to the neighbouring cell in that direction. If that cell is a wall or outside the grid, the agent stays where it is and `next_state == state`.\n- At one to three hidden steps per maze, the walls change. Either an opening on the current shortest route closes (sometimes while a new opening appears elsewhere, leading to a longer route), or a wall opens and makes a shorter route possible. Every open cell always stays connected to the goal. If the agent is standing on a cell that is about to become a wall, that change waits until it has left.\n- **Run:** the book's blocking maze (Example 8.2: 3,000 steps, changes at step 1,000) and shortcut maze (Example 8.3: 6,000 steps, changes at step 3,000), plus four practice mazes of 4,000 steps.\n- **Submit:** eight held-out mazes of 7-11 by 9-15 cells, 6,000 steps each, with different layouts and change times.\n\n**Score.** For each maze, your goals are compared with the oracle's: an agent that knows the maze and every change the moment it happens, and always walks a shortest route. The maze's score is `100 * your_goals / oracle_goals`, and the score is the mean over the mazes. The report shows both goal counts for every maze; on Run it also shows when and how each maze changed. A score of at least **45** counts as solved; everything above that is leaderboard.\n\n**Budget and rules.** Total time spent inside your `Agent` (constructor, `act` and `learn`) is capped at 60 s on Run and 120 s on Submit. Within that total you may plan as much as you like on any step. `random` and `numpy.random` are seeded before every maze. Your code may import only `numpy`, `math`, `collections`, `itertools`, `functools`, `random`, `heapq` and `bisect`, and may use an imported module only as `module.name`.\n\n**Gates.** The score is set to 0 and the run fails if any of these happen:\n- `act` returns anything but an int in `0..3`.\n- Any method raises or exits.\n- The time budget runs out.\n- Your code reads files, uses introspection (`globals`, `vars`, `getattr`/`setattr`, frames, tracebacks, `eval`/`exec`), or assigns to, aliases or reaches into the internals of an imported module.","tags":["reinforcement-learning","dyna","planning","model-based-rl","exploration","sutton-barto","open-ended","leaderboard"],"id":"dc348c53-6b06-4fbb-a8ca-57bc562b68d6","dataset_id":"synthetic","img_type":"full","difficulty":"hard","evaluation_metric":"pct_of_oracle","min_eval_metric":45.0,"category":"Reinforcement Learning","dataset":"Synthetic gridworld mazes that change mid-run (book Examples 8.1-8.3)","title":"Most Goals in a Changing Maze","time_limits_seconds":{"dev":150,"test":270}},{"created_at":"2026-10-31T23:47:22.793000+00:00","type":"general","constraints":["cluster(X, kind) returns one integer label per row; K is not given","each call <= 10 s; the grader seeds np.random and random before each call","numpy, scipy, scikit-learn and small standard-library helpers; the harness owns all data access"],"test_cases":[{"test":"import numpy as np\n_r = np.random.default_rng(7)\ndef _ari(a, b):\n    _, a = np.unique(a, return_inverse=True)\n    _, b = np.unique(b, return_inverse=True)\n    C = np.zeros((a.max() + 1, b.max() + 1))\n    np.add.at(C, (a, b), 1.0)\n    c2 = lambda v: v * (v - 1.0) / 2.0\n    s, sa, sb, t = c2(C).sum(), c2(C.sum(1)).sum(), c2(C.sum(0)).sum(), c2(float(len(a)))\n    e = sa * sb / t\n    return (s - e) / (0.5 * (sa + sb) - e)\n_X = np.vstack([_r.normal(c, 0.5, (150, 3)) for c in (0.0, 8.0)])\n_L = np.asarray(cluster(_X.copy(), \"continuous\"))\nprint(_L.shape == (300,), _L.dtype.kind in \"iu\")","expected_output":"True True"},{"test":"import numpy as np\n_r = np.random.default_rng(7)\ndef _ari(a, b):\n    _, a = np.unique(a, return_inverse=True)\n    _, b = np.unique(b, return_inverse=True)\n    C = np.zeros((a.max() + 1, b.max() + 1))\n    np.add.at(C, (a, b), 1.0)\n    c2 = lambda v: v * (v - 1.0) / 2.0\n    s, sa, sb, t = c2(C).sum(), c2(C.sum(1)).sum(), c2(C.sum(0)).sum(), c2(float(len(a)))\n    e = sa * sb / t\n    return (s - e) / (0.5 * (sa + sb) - e)\n_y = _r.integers(0, 3, 400)\n_p = np.array([[0.9] * 20 + [0.1] * 40, [0.1] * 20 + [0.9] * 20 + [0.1] * 20, [0.1] * 40 + [0.9] * 20])\n_X = (_r.random((400, 60)) < _p[_y]).astype(np.float64)\n_L = np.asarray(cluster(_X.copy(), \"binary\"))\nprint(_L.shape == (400,), _L.dtype.kind in \"iu\")","expected_output":"True True"},{"test":"import numpy as np\n_r = np.random.default_rng(7)\ndef _ari(a, b):\n    _, a = np.unique(a, return_inverse=True)\n    _, b = np.unique(b, return_inverse=True)\n    C = np.zeros((a.max() + 1, b.max() + 1))\n    np.add.at(C, (a, b), 1.0)\n    c2 = lambda v: v * (v - 1.0) / 2.0\n    s, sa, sb, t = c2(C).sum(), c2(C.sum(1)).sum(), c2(C.sum(0)).sum(), c2(float(len(a)))\n    e = sa * sb / t\n    return (s - e) / (0.5 * (sa + sb) - e)\n_y = np.repeat(np.arange(2), 200)\n_X = np.vstack([_r.normal(c, 0.5, (200, 3)) for c in (0.0, 9.0)])\nprint(\"two blobs:\", len(np.unique(cluster(_X.copy(), \"continuous\"))))","expected_output":"two blobs: 2"},{"test":"import numpy as np\n_r = np.random.default_rng(7)\ndef _ari(a, b):\n    _, a = np.unique(a, return_inverse=True)\n    _, b = np.unique(b, return_inverse=True)\n    C = np.zeros((a.max() + 1, b.max() + 1))\n    np.add.at(C, (a, b), 1.0)\n    c2 = lambda v: v * (v - 1.0) / 2.0\n    s, sa, sb, t = c2(C).sum(), c2(C.sum(1)).sum(), c2(C.sum(0)).sum(), c2(float(len(a)))\n    e = sa * sb / t\n    return (s - e) / (0.5 * (sa + sb) - e)\n_c = 12.0 * np.array([[0, 0], [0, 1], [1, 0], [1, 1], [2, 0], [2, 1]], dtype=float)\n_y = np.repeat(np.arange(6), 80)\n_X = np.vstack([_r.normal(c, 0.7, (80, 2)) for c in _c])\nprint(\"six blobs ari over 0.9:\", _ari(np.asarray(cluster(_X.copy(), \"continuous\")), _y) > 0.9)","expected_output":"six blobs ari over 0.9: True"},{"test":"import numpy as np\n_r = np.random.default_rng(7)\ndef _ari(a, b):\n    _, a = np.unique(a, return_inverse=True)\n    _, b = np.unique(b, return_inverse=True)\n    C = np.zeros((a.max() + 1, b.max() + 1))\n    np.add.at(C, (a, b), 1.0)\n    c2 = lambda v: v * (v - 1.0) / 2.0\n    s, sa, sb, t = c2(C).sum(), c2(C.sum(1)).sum(), c2(C.sum(0)).sum(), c2(float(len(a)))\n    e = sa * sb / t\n    return (s - e) / (0.5 * (sa + sb) - e)\n_y = np.repeat(np.arange(2), 300)\n_th = _r.uniform(0, 2 * np.pi, 600)\n_X = np.c_[(1 + 2 * _y) * np.cos(_th), (1 + 2 * _y) * np.sin(_th)] + 0.06 * _r.normal(size=(600, 2))\nprint(\"two rings ari over 0.9:\", _ari(np.asarray(cluster(_X.copy(), \"continuous\")), _y) > 0.9)","expected_output":"two rings ari over 0.9: True"}],"lower_is_better":false,"approved_user_libraries":["numpy","scipy","sklearn"],"data_info":"The harness generates every task itself; only the digits family reads a dataset (sklearn-digits from dml_data, with Run and Submit on disjoint images). The true number of clusters is between 2 and 10, and the sample size does not depend on it.\n\nFamilies on Run and Submit:\n- aniso: elongated Gaussian clusters with different orientations (3 to 9 clusters, 2 to 6 dimensions).\n- unequal: round Gaussian clusters with very different spreads and sizes (3 to 9 clusters, 2 to 8 dimensions).\n- rings: 2 to 4 concentric noisy rings, with up to 2 extra noise dimensions.\n- moons: a chain of 2 to 5 interlocking crescents, with up to 1 extra noise dimension.\n- digits: 4 to 10 digit classes of the 8x8 sklearn digits, reduced by PCA to 10, 15 or 25 dimensions.\n- binary (kind \"binary\"): Bernoulli mixtures with 3 to 10 prototypes over 50, 80 or 120 bits.\n- density: round clusters of very different densities plus 10% uniform background points, which are not scored (3 to 8 clusters, 2 to 5 dimensions).\n- binary_hier (kind \"binary\"): 4 to 9 Bernoulli prototypes in related groups over 50 or 90 bits, where siblings differ in only a small share of the bits.\n\nRun: 24 fixed tasks in family order. Submit: 48 tasks in random order, including 4 held-out families that are not described here. All continuous tasks are centred, rotated, rescaled and shifted; all rows are shuffled.","time_limits":{"test":600,"dev":300},"example":{"input":"cluster(X of shape (612, 3), 'continuous')","output":"labels of shape (612,), for example [2, 0, 0, 5, ...]; K-means with a guessed K = 3 scores about 0.43 on Submit"},"gpu":false,"description":"You are handed a table of points and nothing else: no labels, and not even the number of groups. Find the groups.\n\nEvery task comes from a generator that knows the true cluster of each point, so your partition can be scored against the truth. Some tasks are blobs, some are shapes no blob model describes, some are binary vectors, one family is real handwritten digits, and on **Submit** four whole families appear that **Run** never shows you. One function has to handle all of them.\n\n## Your function\n\n```python\ndef cluster(X, kind):\n    ...\n    return labels    # integer numpy array, shape (len(X),)\n```\n\n- `X`: float64 array of shape `(n, d)`, with `n` from about 270 to 1,100 and `d` from 2 to 120. Rows are shuffled. Continuous tasks are centred, randomly rotated, rescaled and shifted, so neither the axes nor the units mean anything.\n- `kind`: the string `\"continuous\"`, or `\"binary\"` when every entry of `X` is `0.0` or `1.0`.\n- `labels`: any integers. Each distinct value is one cluster; the numbering carries no meaning.\n- The number of clusters is **not given**. It differs from task to task, between 2 and 10.\n\n## Score (higher is better)\n\nFor each task the grader computes the **adjusted Rand index** between your labels and the true clusters. It is 1 for a perfect partition and about 0 for a random one, whatever the cluster sizes; putting everything in one cluster, or every point in its own, scores 0. Your score is the **mean over all tasks**, and the lab is passed at **0.60 or above**.\n\n- **Run**: 24 fixed tasks, 3 from each of the 8 families listed under Data. The report prints every task with its family, your cluster count, the true count and your ARI, plus purity and NMI as secondary numbers.\n- **Submit**: 48 hidden tasks, 4 from each of those 8 families (new tasks, other digit images) and 4 from each of **4 held-out families**. The tasks come in a random order. Every submission sees them under a fresh rotation, scale and row order, with up to 5% of the rows dropped, so a score moves by about 0.02 between identical submissions. The report gives one mean ARI per family, with the held-out families anonymous.\n\n## Budget and rules\n\n- Each call to `cluster` gets **10 seconds**, measured by the grader. Before each call the grader seeds `np.random` and `random`, so unseeded code repeats exactly on Run.\n- Libraries: numpy, scipy and scikit-learn, plus small standard-library helpers (math, random, time, collections, itertools, functools, heapq, bisect, statistics, warnings, copy, dataclasses, typing, enum, abc).\n- The grader owns the data. Imports outside that list, `dml_data`, `sklearn.datasets`, `getattr`, and anything that reads a file are refused.\n- Your source may have at most 30,000 characters, 3,000 characters of string constants and 600 numeric literals, and no integer literal over 18 digits.\n- A refused source, an exception, a call over budget, a wrong shape or non-integer labels sets the score to 0 and fails the run.","tags":["clustering","adjusted-rand-index","model-selection","mixture-models","spectral-clustering","unsupervised","competitive","open-ended","leaderboard","pml-book"],"id":"e06b6259-9740-49aa-bde5-842cbc07d457","img_type":"full","dataset_id":"sklearn-digits","evaluation_metric":"mean_adjusted_rand_index","difficulty":"hard","min_eval_metric":0.6,"category":"Machine Learning","title":"Best Clustering Without Labels","dataset":"Generated clustering tasks plus sklearn digits","time_limits_seconds":{"dev":300,"test":600}},{"created_at":"2026-11-01T01:18:06.358000+00:00","type":"general","test_cases":[{"test":"import numpy as np\ndef _matrix(sig, m, n, seed):\n    r = np.random.default_rng(seed)\n    a = np.linalg.qr(r.standard_normal((m, len(sig))))[0]\n    b = np.linalg.qr(r.standard_normal((n, len(sig))))[0]\n    return (a * sig) @ b.T\ndef _run(A, k, budget):\n    used = [0]\n    def mv(x):\n        x = np.asarray(x)\n        used[0] += 1 if x.ndim == 1 else x.shape[1]\n        return A @ x\n    def rmv(x):\n        x = np.asarray(x)\n        used[0] += 1 if x.ndim == 1 else x.shape[1]\n        return A.T @ x\n    U, s, Vt = approximate(mv, rmv, A.shape, k, budget)\n    U, s, Vt = np.asarray(U), np.asarray(s), np.asarray(Vt)\n    sv = np.linalg.svd(A, compute_uv=False)\n    ratio = np.linalg.norm(A - (U * s) @ Vt) / np.sqrt(np.sum(sv[k:] ** 2))\n    return U, s, Vt, used[0], ratio\nA = _matrix(1.0 / np.arange(1, 121), 150, 120, 1)\nU, s, Vt, used, ratio = _run(A, 5, 30)\nprint(\"shapes:\", U.shape[0] == 150, Vt.shape[1] == 120, 1 <= len(s) <= 5, U.shape[1] == len(s) == Vt.shape[0])\nprint(\"within budget:\", used <= 30)","expected_output":"shapes: True True True True\nwithin budget: True"},{"test":"import numpy as np\ndef _matrix(sig, m, n, seed):\n    r = np.random.default_rng(seed)\n    a = np.linalg.qr(r.standard_normal((m, len(sig))))[0]\n    b = np.linalg.qr(r.standard_normal((n, len(sig))))[0]\n    return (a * sig) @ b.T\ndef _run(A, k, budget):\n    used = [0]\n    def mv(x):\n        x = np.asarray(x)\n        used[0] += 1 if x.ndim == 1 else x.shape[1]\n        return A @ x\n    def rmv(x):\n        x = np.asarray(x)\n        used[0] += 1 if x.ndim == 1 else x.shape[1]\n        return A.T @ x\n    U, s, Vt = approximate(mv, rmv, A.shape, k, budget)\n    U, s, Vt = np.asarray(U), np.asarray(s), np.asarray(Vt)\n    sv = np.linalg.svd(A, compute_uv=False)\n    ratio = np.linalg.norm(A - (U * s) @ Vt) / np.sqrt(np.sum(sv[k:] ** 2))\n    return U, s, Vt, used[0], ratio\nA = _matrix(1.0 / np.arange(1, 121), 150, 120, 2)\nU, s, Vt, used, ratio = _run(A, 5, 30)\nj = len(s)\nprint(\"orthonormal:\", bool(np.abs(U.T @ U - np.eye(j)).max() < 1e-6 and np.abs(Vt @ Vt.T - np.eye(j)).max() < 1e-6))\nprint(\"s sorted, non-negative:\", bool(np.all(s >= 0) and np.all(np.diff(s) <= 1e-9 * s[0])))","expected_output":"orthonormal: True\ns sorted, non-negative: True"},{"test":"import numpy as np\ndef _matrix(sig, m, n, seed):\n    r = np.random.default_rng(seed)\n    a = np.linalg.qr(r.standard_normal((m, len(sig))))[0]\n    b = np.linalg.qr(r.standard_normal((n, len(sig))))[0]\n    return (a * sig) @ b.T\ndef _run(A, k, budget):\n    used = [0]\n    def mv(x):\n        x = np.asarray(x)\n        used[0] += 1 if x.ndim == 1 else x.shape[1]\n        return A @ x\n    def rmv(x):\n        x = np.asarray(x)\n        used[0] += 1 if x.ndim == 1 else x.shape[1]\n        return A.T @ x\n    U, s, Vt = approximate(mv, rmv, A.shape, k, budget)\n    U, s, Vt = np.asarray(U), np.asarray(s), np.asarray(Vt)\n    sv = np.linalg.svd(A, compute_uv=False)\n    ratio = np.linalg.norm(A - (U * s) @ Vt) / np.sqrt(np.sum(sv[k:] ** 2))\n    return U, s, Vt, used[0], ratio\nsig = np.full(200, 1e-3)\nsig[:8] = np.linspace(1.0, 0.5, 8)\nA = _matrix(sig, 260, 200, 3)\nU, s, Vt, used, ratio = _run(A, 8, 48)\nprint(\"strong head over a flat tail, error within 2% of the optimum:\", bool(ratio < 1.02))","expected_output":"strong head over a flat tail, error within 2% of the optimum: True"},{"test":"import numpy as np\ndef _matrix(sig, m, n, seed):\n    r = np.random.default_rng(seed)\n    a = np.linalg.qr(r.standard_normal((m, len(sig))))[0]\n    b = np.linalg.qr(r.standard_normal((n, len(sig))))[0]\n    return (a * sig) @ b.T\ndef _run(A, k, budget):\n    used = [0]\n    def mv(x):\n        x = np.asarray(x)\n        used[0] += 1 if x.ndim == 1 else x.shape[1]\n        return A @ x\n    def rmv(x):\n        x = np.asarray(x)\n        used[0] += 1 if x.ndim == 1 else x.shape[1]\n        return A.T @ x\n    U, s, Vt = approximate(mv, rmv, A.shape, k, budget)\n    U, s, Vt = np.asarray(U), np.asarray(s), np.asarray(Vt)\n    sv = np.linalg.svd(A, compute_uv=False)\n    ratio = np.linalg.norm(A - (U * s) @ Vt) / np.sqrt(np.sum(sv[k:] ** 2))\n    return U, s, Vt, used[0], ratio\nsig = 0.01 / np.sqrt(np.arange(1, 201))\nsig[:12] = 1.0\nA = _matrix(sig, 260, 200, 4)\nU, s, Vt, used, ratio = _run(A, 8, 48)\nprint(\"twelve equal singular values, error within 2% of the optimum:\", bool(ratio < 1.02))","expected_output":"twelve equal singular values, error within 2% of the optimum: True"},{"test":"import numpy as np\ndef _matrix(sig, m, n, seed):\n    r = np.random.default_rng(seed)\n    a = np.linalg.qr(r.standard_normal((m, len(sig))))[0]\n    b = np.linalg.qr(r.standard_normal((n, len(sig))))[0]\n    return (a * sig) @ b.T\ndef _run(A, k, budget):\n    used = [0]\n    def mv(x):\n        x = np.asarray(x)\n        used[0] += 1 if x.ndim == 1 else x.shape[1]\n        return A @ x\n    def rmv(x):\n        x = np.asarray(x)\n        used[0] += 1 if x.ndim == 1 else x.shape[1]\n        return A.T @ x\n    U, s, Vt = approximate(mv, rmv, A.shape, k, budget)\n    U, s, Vt = np.asarray(U), np.asarray(s), np.asarray(Vt)\n    sv = np.linalg.svd(A, compute_uv=False)\n    ratio = np.linalg.norm(A - (U * s) @ Vt) / np.sqrt(np.sum(sv[k:] ** 2))\n    return U, s, Vt, used[0], ratio\nA = _matrix(1.0 / np.arange(1, 201), 260, 200, 5)\nU, s, Vt, used, ratio = _run(A, 10, 40)\nprint(\"slow decay, error within 10% of the optimum:\", bool(ratio < 1.10))","expected_output":"slow decay, error within 10% of the optimum: True"}],"approved_user_libraries":["numpy","scipy"],"lower_is_better":true,"data_info":"Hidden matrices held in a separate grader process, reachable only through counted matvec and rmatvec products. Run: 60 matrices, synthetic spectra plus MNIST-based image matrices. Submit: 150 different matrices with extra spectrum shapes and image matrices from Fashion-MNIST, Olivetti faces and CIFAR-10. Image matrices are centred, with hidden row subsets, shuffled columns and hidden reflections. No data is given to your code.","time_limits":{"test":300,"dev":120},"example":{"input":"approximate(matvec, rmatvec, (700, 600), 10, 40): a hidden 700 x 600 matrix, target rank 10, 40 products","output":"U of shape (700, 10), s of shape (10,), Vt of shape (10, 600). If the true SVD's error is 2.00 and yours is 2.04, this matrix adds 2.0 to the mean; the score is that mean over all matrices (pass at 10.8 or lower)."},"gpu":false,"description":"The book says the truncated SVD $\\hat{A}_k = U_k S_k V_k^\\top$ is the best rank-$k$ approximation of $A$ in Frobenius norm. Computing it normally starts from the whole matrix. Here you never see the matrix: you may only multiply by it, and every product is counted.\n\nBuild the most accurate rank-$k$ approximation you can from a fixed number of products. Any method is allowed.\n\n## Your function\n\n```python\ndef approximate(matvec, rmatvec, shape, k, budget):\n    ...\n    return U, s, Vt\n```\n\n- `shape` is `(m, n)`, the shape of the hidden matrix $A$. `k` is the target rank. `budget` is the number of products you may use on this matrix.\n- `matvec(X)` returns $AX$ and `rmatvec(Y)` returns $A^\\top Y$. `X` has shape `(n, b)` and `Y` has shape `(m, b)`; a 1-D vector also works and returns a 1-D vector.\n- **Each column counts as one product**, on either side. Using `matvec` then `rmatvec` on one vector costs 2.\n- Return `U` of shape `(m, j)`, `s` of shape `(j,)` and `Vt` of shape `(j, n)` with $1 \\le j \\le k$. The columns of `U` and the rows of `Vt` must be orthonormal to within 1e-06, and `s` must be non-negative and in decreasing order.\n\nYour approximation is $\\hat{A} =$ `(U * s) @ Vt`.\n\n## The matrices\n\nEach matrix is scored once, and `approximate` has no way to tell which kind it got. Every matrix has a hidden overall scale, between $10^{-4}$ and $10^{4}$.\n\n- $k$ runs from 4 to 30, and `budget` is 3 to 8 times $k$. Your function must use what it is given: the budget is always well below what it would take to read the whole matrix.\n- Most matrices are synthetic, built from a known spectrum with hidden singular vectors: singular values that decay slowly, decay fast, drop sharply onto a long flat tail, or sit in groups of nearly or exactly equal values, plus matrices whose largest directions live on a small hidden set of rows and columns.\n- Some are real image matrices: a hidden subset of rows, centred along both axes, with shuffled columns and hidden reflections applied.\n\n**Run** scores 60 matrices. **Submit** scores 150 different matrices, with spectrum shapes and image datasets that Run never shows.\n\n## Score (lower is better)\n\nThe optimum for each matrix comes from its true SVD, $\\lVert A - A_k \\rVert_F = \\sqrt{\\sum_{i>k} \\sigma_i^2}$. The score is the mean percentage by which you miss it:\n\n$$\\text{score} = \\frac{1}{N} \\sum_{t=1}^{N} \\min\\left( 100 \\left( \\frac{\\lVert A_t - \\hat{A}_t \\rVert_F}{\\lVert A_t - (A_t)_k \\rVert_F} - 1 \\right),\\ 100 \\right)$$\n\nA score of 0 would match the true SVD on every matrix. Each matrix counts for at most 100. You pass at **10.8** or lower; below that, lower ranks higher. The starter scores about 50 on Submit.\n\n## Rules and gates\n\nThe matrices live in a separate process that only answers these products and does the scoring. The run fails (score 999) if:\n\n- you ask for more products than `budget` on any matrix;\n- `approximate` raises or exits, or returns the wrong shapes, rank above $k$, NaN or infinity, factors that are not orthonormal, or an unsorted or negative `s`;\n- a block is complex, is not 2-D or 1-D with the right length, or holds NaN or infinity (these raise an error inside your call);\n- one matrix takes over 20 s, or all of them over 60 s on Run or 180 s on Submit.\n\nYour code may import numpy, scipy and small standard-library helpers such as `math` or `itertools`. These are refused before anything runs:\n\n- **assigning to or deleting an attribute (`x.y = ...`) anywhere except on `self`, directly in a method written in a class body.** Ordinary classes are fine;\n- files, datasets, environment variables, dynamic attribute access and private attributes.\n\nYour source is limited to 20,000 characters, 300 numeric literals and 1,500 characters of strings outside docstrings.\n\nRandomness is allowed. The report shows your score, the mean per family of matrices and per budget multiple, your three worst matrices and the share of the budget you used.","tags":["svd","low-rank","linear-algebra","numerical-linear-algebra","open-ended","leaderboard"],"id":"e66bd345-4351-4f2a-a1da-0648b7f154f5","dataset_id":"synthetic","img_type":"full","difficulty":"hard","evaluation_metric":"excess_error_pct","min_eval_metric":10.8,"category":"Linear Algebra","dataset":"Hidden matrices in a separate grader process: synthetic spectra and image matrices","title":"Best Low-Rank Approximation from a Matvec Budget","time_limits_seconds":{"dev":120,"test":300}},{"created_at":"2026-09-23T23:30:47.844491+00:00","type":"general","constraints":["numpy only; no network access","Implement class Scheduler(max_batch, total_blocks, block_size, prefill_tps, decode_ms_base, decode_ms_per_seq) with plan(t, waiting, running, free_blocks) -> (admit_ids, preempt_ids, prefill_budget)","plan is called before every simulated step (thousands of times); keep it fast"],"last_updated":"2026-09-23T23:30:47.844491+00:00","test_cases":[{"test":"s = Scheduler(48, 1024, 16, 12000.0, 18.0, 0.3)\nprint(hasattr(s, 'plan'))","expected_output":"True"},{"test":"s = Scheduler(48, 1024, 16, 12000.0, 18.0, 0.3)\nw = [{'id': 0, 'arrival': 0.0, 'prompt_len': 100, 'max_new': 50, 'generated': 0, 'blocks_needed': 7}]\nout = s.plan(0.0, w, [], 1024)\nprint(len(out) == 3 and list(out[0]) == [0])","expected_output":"True"},{"test":"s = Scheduler(48, 1024, 16, 12000.0, 18.0, 0.3)\nw = [{'id': 0, 'arrival': 0.0, 'prompt_len': 3000, 'max_new': 200, 'generated': 0, 'blocks_needed': 188}]\nr = [{'id': k, 'phase': 'decode', 'prompt_len': 400, 'prefilled': 400, 'generated': 10, 'max_new': 200, 'blocks_held': 26} for k in range(1, 40)]\nout = s.plan(1.0, w, r, 4)\nprint(list(out[0]) == [] or out[2] is not None)","expected_output":"True"}],"lower_is_better":false,"approved_user_libraries":["numpy"],"data_info":"Synthetic request traces generated inside the grader with numpy (no downloads): Poisson arrivals at 5 requests per second, prompts of 64 to 512 tokens with 15 percent of 1500 to 3000 tokens, 40 to 200 output tokens; 400 requests on both graders, from different random draws.","time_limits":{"test":180,"dev":120},"example":{"input":"plan(t=12.3, waiting=[{'id': 41, 'arrival': 12.1, 'prompt_len': 2200, 'max_new': 120, 'generated': 0, 'blocks_needed': 138}, ...], running=[{'id': 37, 'phase': 'decode', ...}, ...], free_blocks=150)","output":"([41], [], 512): admit request 41, preempt nothing, prefill at most 512 prompt tokens this step; the grader reports goodput, ttft_failures, itl_failures, forced_preemptions and test_acc = goodput"},"model_specs":"Your choice of admission order, preemption rule and prefill chunking. The grader owns the replica simulator (batch cap 48, 640 KV blocks of 16 tokens, 12000 prefill tokens per second, decode step 18 ms + 0.3 ms per sequence) and the traces; it only applies the decisions you return.","gpu":false,"description":"# Design Your Own Request Scheduler\n\nOne inference replica, a stream of requests, a fixed budget of KV cache blocks and a cap on how many sequences can decode at once. Before every step the replica asks your scheduler what to do: which waiting requests to admit, which running requests to preempt, and how many prompt tokens to prefill this step. The grader replays a hidden trace through a replica simulator driven by your decisions and reports goodput, the fraction of requests that finished within their latency objectives.\n\n```python\nclass Scheduler:\n    def __init__(self, max_batch, total_blocks, block_size, prefill_tps, decode_ms_base, decode_ms_per_seq):\n        ...\n\n    def plan(self, t, waiting, running, free_blocks):\n        ...\n        return admit_ids, preempt_ids, prefill_budget\n```\n\n- `waiting` is the list of arrived requests not currently running, oldest first; each is a dict with `id`, `arrival`, `prompt_len`, `max_new`, `generated` (tokens already produced before a preemption, else `0`) and `blocks_needed` (blocks to hold its prompt and prior output).\n- `running` lists the requests on the replica, each with `id`, `phase` (`'prefill'` or `'decode'`), `prompt_len`, `prefilled`, `generated`, `max_new`, `blocks_held`.\n- `free_blocks` is the number of unallocated KV blocks.\n- Return the ids from `waiting` to admit, in the order you want them prefilled; the ids from `running` to preempt, which return to the waiting queue and must re-prefill everything they had; and `prefill_budget`, the maximum prompt tokens the replica may prefill in the coming step across all prefilling requests (`None` means unlimited).\n\nAdmissions that do not fit, because the batch is full or the blocks are not free, are ignored. A running request that needs a block when none is free is preempted by the replica itself. Everything else, first-come-first-served or shortest-first, chunked or whole prefill, preempting early or never, is your design.\n\n## How it is graded\n\nThe simulator charges a step `decode_ms_base + decode_ms_per_seq x decoding sequences` plus `prefilled tokens / prefill_tps`. A request's time to first token is measured from arrival to the end of the step in which its prefill completes; its inter-token latency is the gap between consecutive steps it decodes in. A request meets its objective when its time to first token is at most `1.0` s and its largest inter-token gap at most `0.15` s. Goodput is the number of requests that finished and met both, divided by all requests in the trace; requests still unfinished when the trace's time limit expires count as failures. Higher is better. The traces mix short prompts with occasional very long ones and arrive faster than the cache can hold all of them at once. Only numpy is available.\n","tags":["scheduling","continuous-batching","chunked-prefill","kv-cache","preemption","serving","inference","open-ended"],"id":"e6b3d8f2-7a4c-4d1e-9b5f-3c2a1d0e9f8b","difficulty":"hard","evaluation_metric":"goodput","schema":"Scheduler(max_batch: int, total_blocks: int, block_size: int, prefill_tps: float, decode_ms_base: float, decode_ms_per_seq: float); plan(t: float, waiting: list[dict], running: list[dict], free_blocks: int) -> (list[int], list[int], int | None)","min_eval_metric":0.77,"category":"Inference","title":"Design Your Own Request Scheduler","time_limits_seconds":{"dev":120,"test":180}},{"created_at":"2026-10-28T19:04:13.177000+00:00","type":"general","test_cases":[{"test":"import numpy as np\n_r = np.random.default_rng(11)\n_x = np.sort(_r.uniform(0, 10, 8))\n_y = 2.0 + 0.5 * _x + _r.normal(0, 0.3, 8)\n_xt = np.linspace(0, 10, 50)\n_m, _s = predict(_x, _y, _xt)\n_m, _s = np.asarray(_m, dtype=float), np.asarray(_s, dtype=float)\nprint(_m.shape == (50,), _s.shape == (50,), bool(np.all(np.isfinite(_m)) and np.all(np.isfinite(_s)) and np.all(_s > 0)))","expected_output":"True True True"},{"test":"import numpy as np\n_r = np.random.default_rng(12)\n_x = _r.uniform(-3, 3, 30)\n_y = 1.0 - 2.0 * _x + _r.normal(0, 0.2, 30)\n_m, _s = predict(_x, _y, np.array([-2.5, 0.0, 2.5]))\n_m = np.asarray(_m, dtype=float)\nprint(\"follows the trend:\", bool(np.max(np.abs(_m - np.array([6.0, 1.0, -4.0]))) < 0.5))","expected_output":"follows the trend: True"},{"test":"import numpy as np\n_r = np.random.default_rng(13)\n_x = np.concatenate([_r.uniform(0, 1, 6), _r.uniform(4, 5, 6)])\n_y = np.sin(_x) + _r.normal(0, 0.05, 12)\n_m, _s = predict(_x, _y, np.array([0.5, 2.5, 4.5]))\n_s = np.asarray(_s, dtype=float)\nprint(\"less sure in the gap:\", bool(_s[1] > 1.5 * max(_s[0], _s[2])))","expected_output":"less sure in the gap: True"}],"lower_is_better":true,"approved_user_libraries":["numpy","scipy","pandas","sklearn"],"data_info":"Synthetic 1-D regression datasets generated inside the grader (no dataset download): n between 5 and 40 training pairs, 50 test inputs over the training range extended by 10% at each end, hidden smooth f (mostly polynomials of degree 0 to 4, plus other smooth shapes), homoskedastic Gaussian noise of unknown level, random shift and scale of x and y per dataset. Run: 600 datasets. Submit: 2,400 other datasets with different seeds and extra function shapes.","time_limits":{"test":300,"dev":120},"example":{"input":"predict(x_train (n = 5 to 40 floats), y_train (same length), x_test (50 floats)) for each of 600 (Run) or 2,400 (Submit) datasets","output":"(mean, std), two arrays of shape (50,), e.g. (array([3.1, 2.8, ...]), array([0.42, 0.57, ...])); Submit mean excess NLPD about 1.38 for a global Gaussian and 1.70 for a cross-validated polynomial with a plug-in noise level"},"gpu":false,"description":"You get a handful of noisy $(x, y)$ pairs, sometimes only five, and must say not just what $y$ will be at new inputs but how sure you are. The book picks a polynomial degree for exactly this kind of data (degree 1 wins at $N = 5$, degree 2 at $N = 30$), and warns that plugging one fitted model into the likelihood makes the predictions overconfident. Here you are scored on the whole predictive distribution, over thousands of tiny datasets.\n\n## Your function\n\n```python\ndef predict(x_train, y_train, x_test):\n    ...\n    return mean, std   # two numpy arrays, shape (len(x_test),)\n```\n\n- `x_train`, `y_train`: float arrays of the same length $n$, with $5 \\le n \\le 40$ (one dataset).\n- `x_test`: float array of 50 inputs from the same dataset.\n- Return a Gaussian predictive distribution $\\mathcal{N}(y \\mid \\text{mean}_j, \\text{std}_j^2)$ for every test input. Every mean must be finite and every std finite and greater than 0.\n\nThe grader calls `predict` once per dataset, with nothing carried between calls that it relies on. Approved libraries: numpy, scipy, pandas, scikit-learn. CPU only.\n\n## The data\n\nEach dataset is one-dimensional regression with homoskedastic Gaussian noise of unknown size: $y = f(x) + \\varepsilon$. The hidden $f$ is a smooth function, most often a low-degree polynomial, sometimes another smooth shape. The noise level ranges from a few percent of the signal to as large as the signal. Inputs and outputs come in arbitrary units (shifted and scaled differently in every dataset). The training inputs are spread over an interval, sometimes with an empty stretch in the middle; the test inputs are drawn over the training range extended by 10% at each end, so some fall between and just beyond the training points. The test targets are drawn from the same noisy process and are never shown to `predict`.\n\n## Score (lower is better)\n\nFor one dataset, with test targets $y_j$ and the hidden true predictive $\\mathcal{N}(f(x_j), \\sigma^2)$,\n\n$$e = \\frac{1}{50}\\sum_{j=1}^{50} \\Big[ -\\log \\mathcal{N}(y_j \\mid \\text{mean}_j, \\text{std}_j^2) + \\log \\mathcal{N}(y_j \\mid f(x_j), \\sigma^2) \\Big]$$\n\nis your **excess negative log predictive density** in nats per test point: how much worse your predictive distribution explains the held-out points than the true one does. It is 0 on average for the true distribution and grows both when your mean is off and when your std is too small or too large. Each dataset's $e$ counts at most 10 (so one blow-up cannot decide a ranking), and the score is the mean of $e$ over all datasets.\n\n**Run** scores 600 datasets. **Submit** scores 2,400 other datasets, drawn with different seeds and with function shapes that Run never shows. You pass at a mean excess of **0.62** nats or lower; below that, lower ranks higher.\n\n## Budget and gates\n\n`predict` gets 40 seconds in total on Run and 150 seconds in total on Submit (about 60 ms per dataset). The run fails (score 99) if `predict` raises, goes over the budget, returns arrays of the wrong shape, returns a non-finite mean or a std that is not finite and positive, or returns different values when called twice on the same dataset.\n\nThe report shows your score by training-set size ($n$ 5-9, 10-19, 20-40) and by function family (polynomial or other smooth shape), the median dataset, how many datasets hit the cap, and the score of a global Gaussian (training mean and standard deviation, ignoring $x$) on the same datasets.","tags":["bayesian-model-selection","posterior-predictive","marginal-likelihood","uncertainty","open-ended","leaderboard"],"id":"e7257d2a-bd82-46d2-860c-f35f66166909","img_type":"full","dataset_id":"synthetic","evaluation_metric":"excess_nlpd","difficulty":"hard","min_eval_metric":0.62,"category":"Regression","title":"Best Predictive Density from Tiny Regression Datasets","dataset":"Synthetic tiny 1-D regression datasets (generated in the grader)","time_limits_seconds":{"dev":120,"test":300}},{"created_at":"2026-10-27T14:19:52.671000+00:00","type":"general","test_cases":[{"test":"import numpy as np\nag = Agent(np.array([-1.2, -0.07]), np.array([0.5, 0.07]), 3)\nacts = [ag.start(np.array([-0.5, 0.0]))]\nacts += [ag.step(-1.0, np.array([-0.5 + 0.001 * k, 0.0005 * (k % 3 - 1)])) for k in range(25)]\nag.end(-1.0, False)\nacts.append(ag.start(np.array([-0.45, 0.0])))\nprint(all(isinstance(a, (int, np.integer)) and not isinstance(a, bool) and 0 <= int(a) <= 2 for a in acts))","expected_output":"True"},{"test":"import random\nimport math\nimport numpy as np\ndef _book_runs(n_eps, cap=1000):\n    ag = Agent(np.array([-1.2, -0.07]), np.array([0.5, 0.07]), 3)\n    rng = np.random.default_rng(3)\n    out = []\n    for _ in range(n_eps):\n        x, v = float(rng.uniform(-0.6, -0.4)), 0.0\n        a, n = ag.start(np.array([x, v])), 0\n        while True:\n            v = min(max(v + 0.001 * (int(a) - 1) - 0.0025 * math.cos(3 * x), -0.07), 0.07)\n            x += v\n            if x < -1.2:\n                x, v = -1.2, 0.0\n            n += 1\n            if x >= 0.5 or n >= cap:\n                ag.end(-1.0, x < 0.5)\n                break\n            a = ag.step(-1.0, np.array([x, v]))\n        out.append(n)\n    return out\ndef _play():\n    random.seed(5)\n    np.random.seed(5)\n    return _book_runs(3, cap=300)\nprint(_play() == _play())","expected_output":"True"},{"test":"import math\nimport numpy as np\ndef _book_runs(n_eps, cap=1000):\n    ag = Agent(np.array([-1.2, -0.07]), np.array([0.5, 0.07]), 3)\n    rng = np.random.default_rng(3)\n    out = []\n    for _ in range(n_eps):\n        x, v = float(rng.uniform(-0.6, -0.4)), 0.0\n        a, n = ag.start(np.array([x, v])), 0\n        while True:\n            v = min(max(v + 0.001 * (int(a) - 1) - 0.0025 * math.cos(3 * x), -0.07), 0.07)\n            x += v\n            if x < -1.2:\n                x, v = -1.2, 0.0\n            n += 1\n            if x >= 0.5 or n >= cap:\n                ag.end(-1.0, x < 0.5)\n                break\n            a = ag.step(-1.0, np.array([x, v]))\n        out.append(n)\n    return out\nsteps = _book_runs(30)\nprint(sum(steps[-10:]) / 10 < 400)","expected_output":"True"}],"approved_user_libraries":["numpy","math","collections","itertools","functools","random"],"lower_is_better":true,"data_info":"Simulated inside the grader, no data files. Run: the book's exact Mountain Car (Example 10.1) and one variant world, 3 runs x 50 episodes each. Submit: 8 held-out variant worlds (hidden action order, affine and possibly reversed observations, force, gravity and hill shape), 4 runs x 50 episodes each.","time_limits":{"test":300,"dev":120},"example":{"input":"agent = Agent(obs_low, obs_high, 3); a = agent.start(obs); a = agent.step(-1.0, obs); ...; agent.end(-1.0, False)","output":"an action in {0, 1, 2} per call; the grader reports the mean steps per episode over the first 50 episodes, e.g. 212.4"},"gpu":false,"description":"Teach an underpowered car to reach the top of a hill, and learn it as fast as possible. This is the Mountain Car task of Example 10.1 in Sutton and Barto, played on worlds your agent has never seen: it does not know which action is which, how its observations are scaled or oriented, or exactly how strong the engine and gravity are. The leaderboard ranks by the book's own \"early performance\" measure: **steps per episode averaged over the first 50 episodes, lower is better**.\n\n**Contract.** Define a class `Agent`:\n\n- `Agent(obs_low, obs_high, n_actions)` is created once per run; `obs_low` and `obs_high` are numpy arrays with the smallest and largest value each observation can take, and `n_actions` is 3.\n- `start(obs) -> action` is called at the start of every episode.\n- `step(reward, obs) -> action` is called after every step that did not end the episode.\n- `end(reward, timed_out)` is called when the episode ends: at the goal (`timed_out=False`) or when it is cut off (`timed_out=True`).\n\n`obs` is a numpy array of two floats. An action is the int `0`, `1` or `2`. The reward is `-1` on every step. One `Agent` lives through all 50 episodes of its run and may learn from all of them; a fresh one starts the next run.\n\n**The car (Example 10.1).** In the book's coordinates, position x and velocity v follow `v <- bound(v + force * A - gravity * slope(x))` and then `x <- x + v`, with A in {-1, 0, +1} (full reverse, coast, full throttle), `-0.07 <= v <= 0.07` and `-1.2 <= x`. At `x = -1.2` the car hits a wall and its velocity becomes 0. Reaching `x >= 0.5` is the goal and ends the episode. Every episode starts at a position drawn uniformly from [-0.6, -0.4) with velocity 0, and is cut off after 2,000 steps. In the book, `force = 0.001`, `gravity = 0.0025` and `slope(x) = cos(3x)`.\n\n**Hidden per world.** Each world fixes, and never tells your agent:\n- which action index is full throttle, which is reverse and which is coast;\n- an affine map from (x, v) to `obs`, with its own scale and offset per coordinate; the direction may be reversed, so the goal can sit at either end of the observed range (`obs_low`/`obs_high` are always the true bounds of what you will see);\n- `force` in [0.0009, 0.0011], `gravity` in [0.0023, 0.0027], and a slope `cos(k x) + b cos(w x + p)` with `k` in [2.7, 3.3], `b` in [0, 0.2], `w` in [5, 9].\n\n**Runs.** Run (the Run button): the book's exact task and one variant world, 3 runs each. Submit: 8 held-out worlds, 4 runs each, with different seeds. Start positions differ between runs.\n\n**Score.** For each run, the mean number of steps over its first 50 episodes (a cut-off episode counts 2,000). The score is the mean over all runs, lower is better. The report also shows, per world, the first episode, the last 10 episodes, cut-off episodes, and `optimal_steps_per_episode`: what a near-optimal policy that already knows the world would average. A score at or below **400** counts as solved; everything below that is leaderboard.\n\n**Budget and rules.** Total time spent inside your `Agent` (all methods, all runs) is capped at 60 s on Run and 150 s on Submit. `random` and `numpy.random` are seeded before every run. Your code may import only `numpy`, `math`, `collections`, `itertools`, `functools`, `random`, `heapq` and `bisect`, and may use an imported module only as `module.name`.\n\n**Gates.** The score is set to 1,000,000 and the run fails if any of these happen:\n- An action is anything but the int 0, 1 or 2.\n- Any method raises or tries to exit.\n- The time budget runs out.\n- Your code reads files, uses introspection (`globals`, `vars`, `getattr`/`setattr`, frames, tracebacks, `eval`/`exec`), or assigns to, aliases or reaches into the internals of an imported module.","tags":["reinforcement-learning","function-approximation","tile-coding","sarsa","mountain-car","sutton-barto","open-ended","leaderboard"],"id":"f14d8964-a419-4913-84b4-396d176dec6d","dataset_id":"synthetic","img_type":"full","difficulty":"hard","evaluation_metric":"steps_per_episode","min_eval_metric":400.0,"category":"Reinforcement Learning","dataset":"Simulated Mountain Car worlds (Sutton and Barto, Example 10.1)","title":"Fastest Learner on Mountain Car","time_limits_seconds":{"dev":120,"test":300}},{"created_at":"2026-10-28T18:52:26.341000+00:00","type":"general","constraints":["train <= 60 s (Run) / 90 s (Submit); each decide call <= 15 s","decide returns one action in {0, 1, 2} per row and is deterministic","numpy, pandas and scikit-learn only; the harness owns all data access"],"test_cases":[{"test":"import numpy as np, pandas as pd\n_r = np.random.default_rng(0)\n_n = 400\n_cat = lambda vals: pd.Categorical(_r.choice(vals, _n), categories=vals)\nXd = pd.DataFrame({'age': _r.integers(18, 80, _n), 'workclass': _cat(['Private', 'State-gov']),\n    'fnlwgt': _r.integers(20000, 400000, _n), 'education': _cat(['HS-grad', 'Bachelors', 'Masters']),\n    'education-num': _r.integers(5, 16, _n), 'marital-status': _cat(['Never-married', 'Married-civ-spouse']),\n    'occupation': _cat(['Sales', 'Exec-managerial']), 'relationship': _cat(['Husband', 'Own-child']),\n    'race': _cat(['White', 'Black']), 'sex': _cat(['Male', 'Female']),\n    'capital-gain': _r.choice([0, 0, 0, 15024], _n), 'capital-loss': _r.choice([0, 0, 1902], _n),\n    'hours-per-week': _r.integers(20, 60, _n), 'native-country': _cat(['United-States', 'Mexico'])})\nyd = ((Xd['education-num'] + _r.normal(0, 2, _n)) > 12).astype(np.int64).to_numpy()\nm = train(Xd.copy(), yd.copy())\na = np.asarray(decide(m, Xd.copy(), {'c_fp': 1.0, 'c_fn': 1.0, 'c_reject': 0.3}))\nprint(a.shape == (len(Xd),) and bool(np.isin(a, [0, 1, 2]).all()))","expected_output":"True"},{"test":"import numpy as np, pandas as pd\n_r = np.random.default_rng(0)\n_n = 400\n_cat = lambda vals: pd.Categorical(_r.choice(vals, _n), categories=vals)\nXd = pd.DataFrame({'age': _r.integers(18, 80, _n), 'workclass': _cat(['Private', 'State-gov']),\n    'fnlwgt': _r.integers(20000, 400000, _n), 'education': _cat(['HS-grad', 'Bachelors', 'Masters']),\n    'education-num': _r.integers(5, 16, _n), 'marital-status': _cat(['Never-married', 'Married-civ-spouse']),\n    'occupation': _cat(['Sales', 'Exec-managerial']), 'relationship': _cat(['Husband', 'Own-child']),\n    'race': _cat(['White', 'Black']), 'sex': _cat(['Male', 'Female']),\n    'capital-gain': _r.choice([0, 0, 0, 15024], _n), 'capital-loss': _r.choice([0, 0, 1902], _n),\n    'hours-per-week': _r.integers(20, 60, _n), 'native-country': _cat(['United-States', 'Mexico'])})\nyd = ((Xd['education-num'] + _r.normal(0, 2, _n)) > 12).astype(np.int64).to_numpy()\nm = train(Xd.copy(), yd.copy())\nlo = np.asarray(decide(m, Xd.copy(), {'c_fp': 1.0, 'c_fn': 1.0, 'c_reject': 0.05}))\nprint(bool((lo == 2).any()))","expected_output":"True"},{"test":"import numpy as np, pandas as pd\n_r = np.random.default_rng(0)\n_n = 400\n_cat = lambda vals: pd.Categorical(_r.choice(vals, _n), categories=vals)\nXd = pd.DataFrame({'age': _r.integers(18, 80, _n), 'workclass': _cat(['Private', 'State-gov']),\n    'fnlwgt': _r.integers(20000, 400000, _n), 'education': _cat(['HS-grad', 'Bachelors', 'Masters']),\n    'education-num': _r.integers(5, 16, _n), 'marital-status': _cat(['Never-married', 'Married-civ-spouse']),\n    'occupation': _cat(['Sales', 'Exec-managerial']), 'relationship': _cat(['Husband', 'Own-child']),\n    'race': _cat(['White', 'Black']), 'sex': _cat(['Male', 'Female']),\n    'capital-gain': _r.choice([0, 0, 0, 15024], _n), 'capital-loss': _r.choice([0, 0, 1902], _n),\n    'hours-per-week': _r.integers(20, 60, _n), 'native-country': _cat(['United-States', 'Mexico'])})\nyd = ((Xd['education-num'] + _r.normal(0, 2, _n)) > 12).astype(np.int64).to_numpy()\nm = train(Xd.copy(), yd.copy())\na1 = np.asarray(decide(m, Xd.copy(), {'c_fp': 1.0, 'c_fn': 10.0, 'c_reject': 50.0}))\na2 = np.asarray(decide(m, Xd.copy(), {'c_fp': 10.0, 'c_fn': 1.0, 'c_reject': 50.0}))\nprint(int((a1 == 1).sum()) > int((a2 == 1).sum()))","expected_output":"True"}],"lower_is_better":true,"approved_user_libraries":["numpy","pandas","sklearn"],"data_info":"Adult census income (OpenML adult v2, 48,842 rows, about 24% above 50K), loaded by the harness through dml_data. X DataFrames keep the 14 raw columns: age, workclass, fnlwgt, education, education-num, marital-status, occupation, relationship, race, sex, capital-gain, capital-loss, hours-per-week, native-country (categoricals as pandas category with NaN for missing). y_train is int64, 1 = income above 50K.\n\nRun (validation): seed 42 split, 20,000 training rows, 10,000 test rows, four regimes:\n1. c_fp = 1, c_fn = 1, c_reject = 0.3 (the book's symmetric Chow setting)\n2. c_fp = 1, c_fn = 2, c_reject = 0.8\n3. c_fp = 1, c_fn = 5, c_reject = 0.5\n4. c_fp = 4, c_fn = 1, c_reject = 0.4\n\nSubmit (test): a different seeded split, 32,000 training rows, 16,842 test rows, eight hidden regimes with c_fn / c_fp from about 0.2 to about 12, varying price levels, and reject costs from cheap to never worth it.","time_limits":{"test":360,"dev":240},"gpu":false,"description":"## Cheapest Decisions with a Reject Option\n\nEvery row of the Adult census table is a person. For each one you must pick an **action**: say their income is at most 50K a year (action `0`), say it is above 50K (action `1`), or **reject**, deferring the case to a human reviewer (action `2`). A wrong answer costs money, a deferral costs a fixed review fee, a right answer costs nothing, and the prices change from one deployment to the next. You only learn them when you are asked to decide. Make the decisions with the lowest total cost.\n\n### What you write\n\n```python\ndef train(X_train, y_train):\n    ...\n    return model                    # anything you like\n\ndef decide(model, X, costs):\n    ...\n    return actions                  # np.ndarray, shape (len(X),), each value 0, 1 or 2\n```\n\n- `X_train`, `X`: pandas DataFrames with the 14 raw Adult columns (integer columns and pandas `category` columns, `NaN` where a value is missing).\n- `y_train`: integer array, `1` when income is above 50K.\n- `costs`: a dict with `c_fp` (action `1` for a person at or below 50K), `c_fn` (action `0` for a person above 50K) and `c_reject` (action `2`, whatever the truth). A correct `0` or `1` costs `0`.\n\n### How it is graded\n\nThe harness calls `train` once, then calls `decide` on the same held-out rows once per **cost regime**.\n\n- **Run**: 20,000 training rows, 10,000 test rows, the four regimes listed under Data.\n- **Submit**: a different random split (32,000 training rows, 16,842 test rows) and **eight hidden regimes**. Across them `c_fn / c_fp` runs from about 0.2 to about 12, the overall price level changes, and `c_reject` ranges from cheap to so expensive that deferring never pays.\n\nFor each regime the harness computes the average cost per test row and divides it by the cost of the **best constant action** on that test set (everyone `0`, everyone `1`, or everyone rejected). Your score is the mean of this **relative cost** over the regimes. **Lower is better**: 1.0 means you did no better than the best constant action, and the lab is passed at **0.62 or below**. Per-regime costs, reject rates and error counts are printed so you can see where the cost comes from.\n\n### Budgets and rules\n\n- `train` gets 60 s on Run and 90 s on Submit; each `decide` call gets 15 s.\n- `decide` must be deterministic: the harness calls it twice on identical inputs and the answers must match.\n- Libraries: numpy, pandas and scikit-learn.\n- The harness owns the data. Code that imports `dml_data`, `os`, `sys` or file and serialisation modules, opens or reads files, or names the dataset in a string is refused.\n- A wrong output shape, an action outside `{0, 1, 2}`, an exception, a broken budget or a non-deterministic `decide` sets the score to 9.99 and fails the run.\n","tags":["decision-theory","reject-option","cost-sensitive","calibration","competitive","pml-book"],"id":"f357c9d3-9b96-466c-9e14-f4303e75205f","img_type":"full","dataset_id":"adult-income","difficulty":"medium","evaluation_metric":"relative_cost","min_eval_metric":0.62,"category":"Machine Learning","title":"Cheapest Decisions with a Reject Option","dataset":"Adult Census Income","time_limits_seconds":{"dev":240,"test":360}},{"created_at":"2026-10-28T18:52:18.919000+00:00","type":"general","constraints":["fit + predict: at most 180 s of process CPU time (all threads counted)","Peak resident memory of the whole run: at most 2048 MiB","Libraries: numpy, scipy, scikit-learn and small standard-library helpers","No file, network or dataset access; source at most 30,000 characters","predict returns finite (mean, var) arrays of shape (n_test,), var >= 0 (clamped to 1e-4 when scored)"],"test_cases":[{"test":"import numpy as np\nrng = np.random.default_rng(0)\nX = rng.normal(size=(800, 8))\ny = np.sin(2 * X[:, 0]) + 0.5 * X[:, 1] + 0.1 * rng.normal(size=800)\nfit(X, y)\nmu, var = predict(X[:50])\nmu = np.asarray(mu, float); var = np.asarray(var, float)\nprint(mu.shape == (50,) and var.shape == (50,) and bool(np.all(np.isfinite(mu))) and bool(np.all(var > 0)))","expected_output":"True"},{"test":"import numpy as np\nrng = np.random.default_rng(1)\nX = rng.normal(size=(800, 8))\ny = X[:, 2] + 0.2 * rng.normal(size=800)\nfit(X, y)\nmu, var = predict(X[:1])\nprint(np.asarray(mu).reshape(-1).shape == (1,) and np.asarray(var).reshape(-1).shape == (1,))","expected_output":"True"},{"test":"import numpy as np\nrng = np.random.default_rng(2)\nX = rng.normal(size=(1000, 8))\ny = np.sin(2 * X[:, 0]) + 0.1 * rng.normal(size=1000)\nfit(X[:800], y[:800])\nmu, var = predict(X[800:])\nrmse = float(np.sqrt(np.mean((np.asarray(mu) - y[800:]) ** 2)))\nprint(rmse < 0.5)","expected_output":"True"},{"test":"import numpy as np\nrng = np.random.default_rng(3)\nX = rng.normal(size=(1000, 8))\ny = np.sin(2 * X[:, 0]) + 0.1 * rng.normal(size=1000)\nfit(X[:800], y[:800])\nmu, var = predict(X[800:])\nv = np.maximum(np.asarray(var, float), 1e-4)\nnll = float(np.mean(0.5 * np.log(2 * np.pi * v) + (y[800:] - np.asarray(mu)) ** 2 / (2 * v)))\nprint(nll < 0.0)","expected_output":"True"}],"lower_is_better":true,"approved_user_libraries":["numpy","scipy","sklearn"],"data_info":"California Housing (StatLib, 1990 census): 20,640 block groups, 8 numeric features, target = median house value. The harness draws a random 16,000 / 4,640 train/test split (a different seed for Run and Submit), standardizes the features with train statistics and gives y = standardized log median value. fit gets X_train (16000, 8) and y_train; predict gets X_test (4640, 8) and returns (mean, var). Test labels stay inside the harness.","time_limits":{"test":300,"dev":300},"example":{"input":"fit(X_train, y_train) with X_train (16000, 8), then predict(X_test) with X_test (4640, 8)","output":"(mean, var), two float arrays of shape (4640,), e.g. mean [0.41, -1.02, ...], var [0.09, 0.21, ...]; score = mean Gaussian NLL of the hidden y"},"gpu":false,"description":"Predict the price of a California neighbourhood as a full predictive distribution, and make that distribution as sharp as you can while keeping it honest. Each row is a census block group from the 1990 California census; the target is its median house value. The leaderboard ranks by **mean test Gaussian negative log-likelihood** in nats per point, **lower is better**.\n\n**Contract.** Implement two functions:\n\n- `fit(X_train, y_train) -> None` receives `X_train`, float64 of shape `(16000, 8)`, and `y_train`, float64 of shape `(16000,)`. Keep whatever you need in module-level state.\n- `predict(X_test) -> (mean, var)` receives `X_test`, float64 of shape `(4640, 8)`, and returns two arrays of shape `(4640,)`: your predictive mean and predictive variance of `y` for each row (the variance of the noisy target, not of an underlying function).\n\n**Data.** The eight features are, in order, MedInc, HouseAge, AveRooms, AveBedrms, Population, AveOccup, Latitude, Longitude. The harness draws a random split of the 20,640 rows into 16,000 train and 4,640 test, standardizes every feature with the train mean and standard deviation, and sets `y = (log(median value) - m) / s` with `m`, `s` the train mean and standard deviation of the log value. Nothing else is transformed: the skewed features and the source data's cap at 500,001 dollars are as they come. Test labels never leave the harness. Run and Submit use different random splits.\n\n**Scoring.** With `v = max(var, 1e-4)`, each test point scores `0.5 * log(2 * pi * v) + (y - mean)^2 / (2 * v)`, and your score is the mean over the test set. A model that ignores the features scores about 1.43. Clearing **0.80** counts as solved; everything below that is leaderboard. The report also shows RMSE, the coverage of your central 90% intervals, the mean squared z-score (1 when your variances are calibrated on average), your mean predicted standard deviation, CPU seconds and peak memory.\n\n**Budgets.** `fit` and `predict` together get **180 seconds of process CPU time** (every thread counts, so the budget is the same on any number of cores), and the whole run must stay under **2048 MiB of peak resident memory** (libraries included). For scale: one dense 16,000 x 16,000 float64 matrix is 1,953 MiB on its own. You may use numpy, scipy, scikit-learn and small standard-library helpers (math, functools, itertools, collections, heapq, time, random and similar). Your code may not open files, reach the network or load datasets, and is limited to 30,000 characters.\n\n**Gates.** The run fails with a score of 99 if your code imports anything outside the allowed set or touches files or datasets, if `fit` or `predict` raises, if the CPU or memory budget is exceeded, or if `predict` returns the wrong shapes, a NaN or inf, or a negative variance.","tags":["gaussian-processes","uncertainty","probabilistic-regression","kernel-methods","calibration","open-ended","leaderboard"],"id":"f73b2ccf-affc-4daa-ad79-5a21fecad232","img_type":"full","dataset_id":"california-housing","evaluation_metric":"nll","difficulty":"hard","min_eval_metric":0.8,"category":"Machine Learning","title":"Calibrated Regression at Scale: Lowest Test NLL on California Housing","dataset":"California Housing","time_limits_seconds":{"dev":300,"test":300}},{"created_at":"2026-10-27T14:18:15.939000+00:00","type":"general","test_cases":[{"test":"import numpy as np\ndef _ep(obs, acts, rews, pi, b, term):\n    return {'obs': np.array(obs), 'actions': np.array(acts), 'rewards': np.array(rews, dtype=float),\n            'pi': np.array(pi, dtype=float), 'b': np.array(b, dtype=float), 'terminal': term}\nP, B = [0.9, 0.1], [0.5, 0.5]\neps = [_ep([0, 1, 2, -1], [0, 1, 0], [1.0, 0.0, 2.0], [P, P, P, [0, 0]], [B, B, B, [0, 0]], True),\n       _ep([1, 2, 0, 1], [1, 1, 0], [0.5, 1.0, 0.0], [P, P, P, P], [B, B, B, B], False)] * 3\ntask = {'kind': 'tabular', 'n_states': 3, 'n_actions': 2, 'gamma': 0.9, 'episodic': True,\n        'episodes': eps, 'query': np.array([0, 1, 2]), 'query_pi': np.array([P, P, P])}\nout = np.asarray(estimate(task), dtype=float).reshape(-1)\nprint(out.shape == (3,) and bool(np.all(np.isfinite(out))))","expected_output":"True"},{"test":"import numpy as np\ndef _ep(obs, acts, rews, pi, b, term):\n    return {'obs': np.array(obs), 'actions': np.array(acts), 'rewards': np.array(rews, dtype=float),\n            'pi': np.array(pi, dtype=float), 'b': np.array(b, dtype=float), 'terminal': term}\nP, B = [0.7, 0.3], [0.5, 0.5]\nx = [[0.1], [0.4], [0.8], [0.0]]\neps = [_ep(x, [0, 1, 1], [0.2, -0.1, 1.0], [P, P, P, [0, 0]], [B, B, B, [0, 0]], True)] * 4\ntask = {'kind': 'features', 'obs_dim': 1, 'n_actions': 2, 'gamma': 1.0, 'episodic': True,\n        'episodes': eps, 'query': np.array([[0.1], [0.5], [0.9]]), 'query_pi': np.array([P, P, P])}\nout = np.asarray(estimate(task), dtype=float).reshape(-1)\nprint(out.shape == (3,) and bool(np.all(np.isfinite(out))))","expected_output":"True"},{"test":"import numpy as np\ndef _ep(obs, acts, rews, pi, b, term):\n    return {'obs': np.array(obs), 'actions': np.array(acts), 'rewards': np.array(rews, dtype=float),\n            'pi': np.array(pi, dtype=float), 'b': np.array(b, dtype=float), 'terminal': term}\n# one state; action 0 ends with reward 1, action 1 ends with reward 0.\n# b picks each half the time, pi always picks action 0, so v_pi(0) = 1.\nP, B = [1.0, 0.0], [0.5, 0.5]\neps = [_ep([0, -1], [k % 2], [1.0 - (k % 2)], [P, [0, 0]], [B, [0, 0]], True) for k in range(20)]\ntask = {'kind': 'tabular', 'n_states': 1, 'n_actions': 2, 'gamma': 1.0, 'episodic': True,\n        'episodes': eps, 'query': np.array([0]), 'query_pi': np.array([P])}\nv = float(np.asarray(estimate(task), dtype=float).reshape(-1)[0])\nprint(abs(v - 1.0) < 0.1)","expected_output":"True"}],"approved_user_libraries":["numpy","math","collections","itertools","functools","random"],"lower_is_better":true,"data_info":"Synthetic, deterministic tasks generated inside the grader from fixed seeds. Run: 8 tasks (long-loop chain, three random sparse MDPs, a continuing MDP with truncated logs, 1D and 2D off-policy random walks, Baird's star). Submit: 11 held-out tasks from the same families with different seeds and settings. Each task gives logged episodes (obs, actions, rewards, pi and b probabilities, terminal flag), the discount, query states and pi at the queries.","time_limits":{"test":240,"dev":150},"example":{"input":"task = {'kind': 'tabular', 'n_states': 50, 'n_actions': 4, 'gamma': 0.95, 'episodic': True, 'episodes': [{'obs': array([7, 31, 2, -1]), 'actions': array([1, 3, 0]), 'rewards': array([0.4, -1.2, 0.9]), 'pi': (4, 4) array, 'b': (4, 4) array, 'terminal': True}, ...], 'query': array([0, 2, 5, ...]), 'query_pi': (n_q, 4) array}","output":"[1.83, -0.41, 0.27, ...]  (one value per query); the grader reports per-task normalised RMSE and the mean, e.g. 0.318"},"gpu":false,"description":"Estimate how well a **target policy** would do using only data logged by a different **behaviour policy**. Every task hides a Markov decision process. You get episodes generated by the behaviour policy `b`, both policies' action probabilities, the discount, and a set of query states. Return your estimate of the target policy's state value `v_pi(s)` at every query state. The leaderboard ranks by **mean normalised RMSE over all tasks, lower is better**.\n\n**Contract.** Define `estimate(task) -> sequence of floats` with one value per query state, in query order. It is called once per task. `task` is a dict:\n\n- `kind`: `\"tabular\"` (states are integer ids `0 .. n_states-1`, given in `n_states`) or `\"features\"` (you see a state only as an observation vector of length `obs_dim`).\n- `n_actions`, `gamma`, and `episodic`: `False` means a continuing task whose logs are consecutive windows cut from one long behaviour run.\n- `episodes`: a list of dicts, one per logged episode or window, each with:\n  - `obs`: the states `S_0 .. S_T`, as `T + 1` ids or a `(T + 1, obs_dim)` array.\n  - `actions` and `rewards`: arrays of length `T` holding `A_t` and `R_(t+1)`.\n  - `pi` and `b`: arrays of shape `(T + 1, n_actions)` with `pi(.|S_t)` and `b(.|S_t)` at every logged state.\n  - `terminal`: `True` if `S_T` is a terminal state (value 0 by definition; its `obs` entry is `-1` or all zeros and its `pi`/`b` rows are zeros). `False` means the log simply stops at `S_T`.\n- `query`: the query states (ids, or an `(n_q, obs_dim)` array).\n- `query_pi`: `pi(.|s)` at each query state.\n\nIn tabular tasks every query state appears at least 3 times in the logs. In feature tasks many query states never appear in the logs at all. The behaviour policy gives every action positive probability.\n\n**The tasks.** The hidden processes come from a few families, each a regime that the off-policy chapters of Sutton & Barto stress:\n\n- Chains where the target policy keeps repeating a state while the behaviour policy moves on, as in the book's Example 5.5.\n- Random sparse MDPs where the two policies prefer different actions: some with plenty of data, some with little, one where `b` stays close to `pi`.\n- Continuing MDPs observed through truncated windows.\n- Off-policy versions of the book's random walk (Example 9.1) in one or two dimensions. The observation is the cell's coordinates scaled to `(0, 1)`, and rewards and exits vary smoothly with position.\n- Baird's counterexample (Example 11.1) with non-zero rewards, seen through its feature vectors.\n\nRun grades 8 tasks. Submit grades 11 held-out tasks from the same families with different seeds and settings, including variants that Run does not contain.\n\n**Score.** For each task, the RMSE of your estimates against the exact `v_pi` at the query states, divided by the standard deviation of `v_pi` over those states, capped at 2. Predicting the correct mean everywhere scores 1.0. The score is the mean over tasks; the report lists every task's value. A score at or below **0.60** counts as solved; everything below that is leaderboard.\n\n**Budget and rules.** Total time spent inside `estimate` is capped at 60 s on Run and 120 s on Submit. `numpy.random` and `random` are seeded before every task: you may draw from them, but not create new generators or reseed them. Your code may import only `numpy`, `math`, `collections`, `itertools`, `functools`, `random`, `heapq` and `bisect`, and may use an imported module only as `module.name`.\n\n**Gates.** The score is set to 1,000,000 and the run fails if any of these happen:\n- `estimate` returns something that is not a list of numbers, the wrong number of values, or a NaN or infinite value.\n- `estimate` raises anything, including `SystemExit`.\n- The time budget runs out.\n- Your code reads files, uses introspection (`globals`, `vars`, `getattr`/`setattr`, frames, tracebacks, `eval`/`exec`), creates or reseeds random generators, or assigns to, aliases or reaches into the internals of an imported module.","tags":["reinforcement-learning","off-policy","importance-sampling","temporal-difference","lstd","function-approximation","sutton-barto","open-ended","leaderboard"],"id":"fa6624ef-d875-4ff5-a0cd-92f0423232c0","dataset_id":"synthetic","img_type":"full","difficulty":"hard","evaluation_metric":"nrmse","min_eval_metric":0.6,"category":"Reinforcement Learning","dataset":"Synthetic MDPs with episodes logged by a behaviour policy","title":"Most Accurate Off-Policy Evaluation","time_limits_seconds":{"dev":150,"test":240}},{"offline":true,"description":"A network with 1.3 million weights, 784-800-800-10, has to learn from only **1,000** MNIST digits. Trained the ordinary way it gets every training digit right and makes many mistakes on new ones: it overfits. Train it so that it generalises. The leaderboard ranks by **accuracy on MNIST test digits your code never sees**, higher is better. Reaching 0.925 counts as solved.\n\n**Contract.** Write one function, `train(X, y) -> params`.\n\n- `X` is a (1000, 784) float32 **torch tensor**: 1,000 training digits, each a 28x28 image flattened row by row, with pixel values in [0, 1]. `y` is a (1000,) int64 torch tensor of labels 0 to 9.\n- Return a dict with exactly six entries: `W1` (800, 784), `b1` (800,), `W2` (800, 800), `b2` (800,), `W3` (10, 800), `b3` (10,). Each may be a torch tensor or a numpy array of floats; they are converted to float32.\n\n**What is fixed: the network you are scored with.** For each test digit `x` the harness computes\n\n`logits = relu(relu(x @ W1.T + b1) @ W2.T + b2) @ W3.T + b3`\n\nand predicts the largest logit. So whatever happens during training, the result has to be this plain fully connected network: no masks, no extra layers, no normalisation at test time. Anything you want to apply at test time, such as rescaling weights, has to be built into the six tensors.\n\n**What is yours: everything about how you train it.** The optimizer and its schedule, the initialisation, dropout or any other kind of noise, altered copies of the training images (small shifts, rotations, ...), weight penalties, label smoothing, a max-norm constraint, a validation split of your own, several networks averaged or distilled into one. All of these are allowed, and quite different approaches clear the bar.\n\n**Budget.** `train` gets 120 seconds of wall-clock time on one CPU thread. torch, numpy and Python's `random` are seeded before it is called. Machines vary from run to run by up to about 1.5x in speed, so leave some headroom.\n\n**Score.** Accuracy on 8,000 MNIST test digits on Submit (2,000 others on Run), with a different draw of the 1,000 training digits on each. The test digits are loaded only after `train` has returned. The report also shows `train_seconds`, the training accuracy of the weights you returned and the number of test errors.\n\n**Gates.** The score is 0 (a fail) if `train` is missing or takes more than 120 seconds, if the result is not a dict with exactly those six keys, or if a value has the wrong shape, is not a floating-point tensor or array, or holds NaN or infinite values.\n\n**What your code may use.** torch, numpy and small standard-library helpers (math, random, ...). Graded runs have no network, and your code may not open files, load datasets or embed data. In this lab it may also not use private attributes (ones that start with `_`, such as `x._foo`), the names `sys`, `os`, `builtins`, `bltns`, `importlib`, `import_module`, `inspect`, `getmembers`, `getmembers_static`, `getattr_static`, `ctypes`, `gc`, `pickle`, `copyreg`, `marshal`, `subprocess`, `Popen`, `json`, `shutil`, `tempfile`, `glob`, `pathlib`, `codecs`, `weakref`, `linecache`, `traceback`, `dis`, `types`, `operator`, `modules` or `dml_data`, `torch.set_num_threads`, or functions that write files (`save`, `savez`, `savetxt`, `tofile`, `dump`). (So use `net.children()` or `net.parameters()` instead of `net.modules()`.)","type":"general","tags":["dropout","regularization","overfitting","augmentation","mnist","pytorch","paper","leaderboard"],"id":"fc2007d3-ad7f-4ad3-bb6d-d49d4b773562","created_at":"2026-11-23T14:20:30.361000+00:00","img_type":"pytorch","test_cases":[{"test":"import torch\ntorch.manual_seed(0)\nX = torch.rand(100, 784)\ny = torch.arange(100) % 10\nP = train(X, y)\nshapes = {'W1': (800, 784), 'b1': (800,), 'W2': (800, 800), 'b2': (800,), 'W3': (10, 800), 'b3': (10,)}\nprint(sorted(P) == sorted(shapes), all(tuple(P[k].shape) == s for k, s in shapes.items()), all(bool(torch.isfinite(torch.as_tensor(P[k])).all()) for k in shapes))","expected_output":"True True True"}],"dataset_id":"mnist","evaluation_metric":"accuracy","difficulty":"medium","data_info":"MNIST (dml_data \"mnist\", CC BY-SA 3.0). Training: 1,000 of the 60,000 training digits, drawn with numpy default_rng(123).permutation on Submit (42 on Run), passed to train(X, y) as a (1000, 784) float32 torch tensor in [0, 1] (pixel / 255, the 28x28 image flattened row by row) and a (1000,) int64 torch tensor of labels 0-9. torch, numpy and random are seeded with the run's seed before train() is called, on one CPU thread with a 120 s wall-clock budget. Scored: the 10,000 MNIST test digits shuffled once with default_rng(20261122), the last 8,000 on Submit and the first 2,000 on Run, loaded only after train() returns and scored by the harness's own numpy forward pass, argmax of relu(relu(x W1^T + b1) W2^T + b2) W3^T + b3, on the returned weights cast to float32.","time_limits":{"test":240,"dev":180},"lower_is_better":false,"approved_user_libraries":["numpy","torch","math","random"],"min_eval_metric":0.925,"example":{"input":"train(X, y) with X a (1000, 784) float32 tensor in [0, 1] and y a (1000,) int64 tensor","output":"{'W1': (800, 784), 'b1': (800,), 'W2': (800, 800), 'b2': (800,), 'W3': (10, 800), 'b3': (10,)} as tensors or arrays; scored as argmax of relu(relu(x @ W1.T + b1) @ W2.T + b2) @ W3.T + b3"},"category":"Deep Learning","title":"Big Net, Small Data: Make 1,000 Digits Generalize","dataset":"MNIST","gpu":false,"time_limits_seconds":{"dev":180,"test":240}},{"created_at":"2026-11-15T18:21:53.060000+00:00","type":"general","test_cases":[{"test":"import torch\nP = Positions(64, 4, 16, 2, 256)\nx = torch.randn(2, 10, 64)\nprint(tuple(P.embed(x, torch.arange(10)).shape))","expected_output":"(2, 10, 64)"},{"test":"import torch\nP = Positions(64, 4, 16, 2, 256)\nq, k = torch.randn(2, 4, 10, 16), torch.randn(2, 4, 10, 16)\nq2, k2 = P.rotate(q, k, torch.arange(10), 0)\nprint(tuple(q2.shape), tuple(k2.shape))","expected_output":"(2, 4, 10, 16) (2, 4, 10, 16)"},{"test":"import torch\nP = Positions(64, 4, 16, 2, 256)\nb = P.bias(torch.arange(10), 1)\nprint(b is None or tuple(b.shape[-2:]) == (10, 10))","expected_output":"True"},{"test":"import torch\nP = Positions(64, 4, 16, 2, 256)\nprint(sum(p.numel() for p in P.parameters()) <= 20000)","expected_output":"True"}],"lower_is_better":true,"approved_user_libraries":["torch","numpy","math"],"data_info":"TinyStories validation text, mapped to 97 symbols (printable ASCII, newline, one slot for anything else). Submit: 600 training steps of 32 random 64-character windows from characters 6,000,000-8,000,000; scoring on 96 windows of 256 characters starting at character 12,000,000. Run: 600 steps from characters 0-500,000; 32 windows from character 3,000,000. The harness reports bits per character overall, on the first 64 positions and beyond them, plus training time and the number of parameters in your Positions module.","time_limits":{"test":90,"dev":60},"example":{"input":"Run, with rotate() applying full RoPE to every pair of q and k in both layers","output":"{\"bits_per_char\": 3.4478, \"bpc_first_64\": 2.014, \"bpc_beyond_64\": 3.9258, ...}  (good at the trained length, much worse past it)"},"gpu":false,"offline":true,"description":"A transformer only knows where a token sits if something tells it. This lab trains the same tiny character-level transformer on TinyStories with **your** position method, on 64-character windows, and then scores it on held-out windows of **256** characters: four times longer than anything it saw in training. The leaderboard ranks by **bits per character** over those long windows, lower is better.\n\n**Contract.** Write one class, `Positions(nn.Module)`, constructed as `Positions(d_model, n_heads, head_dim, n_layers, max_len)` with `d_model = 64`, `n_heads = 4`, `head_dim = 16`, `n_layers = 2`, `max_len = 256`. The harness calls three hooks; leave any of them as the starter has it:\n\n- `embed(x, pos)`: `x` is `(batch, T, 64)` token embeddings, `pos` is `torch.arange(T)`. Return `x` with position added. This is where learned absolute embeddings (GPT-2) and sinusoidal encodings go.\n- `rotate(q, k, pos, layer)`: `q` and `k` are `(batch, 4, T, 16)` inside attention layer `layer` (0 or 1). Return the `(q, k)` pair whose dot products become the attention scores. RoPE, partial RoPE and skipping position in some layers (NoPE) go here. Values are never passed to you.\n- `bias(pos, layer)`: return `None`, or a `(T, T)` or `(4, T, T)` tensor that is added to the scaled scores before softmax. A learned relative position bias goes here. The causal mask is applied after your bias.\n\nTraining uses `T = 64`; scoring uses `T = 256`. Parameters you create in `Positions` are trained with the rest of the model (at most 20,000 of them).\n\n**What the harness does.** It builds a 2-layer transformer (width 64, 4 heads, pre-LayerNorm, GELU feed-forward), trains it for a fixed number of AdamW steps (batch 32, one-cycle learning rate 3e-3) on 64-character windows, and scores 96 held-out windows of 256 characters from a different part of the corpus. Run and Submit both train 600 steps; Run uses a different part of the corpus and scores 32 windows, so it is a close preview of your Submit score. Both finish in under a minute.\n\n**Score.** bits per character = mean cross-entropy over all 256 positions of each window / ln 2. The report also splits it into the first 64 positions (lengths seen in training) and positions 64 to 255 (lengths never seen). Clearing 2.9 counts as solved; everything below that is leaderboard.\n\n**Gates.** The score is set to 99.0 (a fail) if a hook returns the wrong shape, the loss becomes non-finite, training runs past 30 seconds (your hooks are too slow), or the model is not causal: the harness changes one character and requires every earlier prediction to stay the same. Hooks that mix information across positions in `x`, `q` or `k` will fail that check.\n\n**What your code may use.** torch, numpy and small standard-library helpers (math, itertools, functools, ...). Graded runs have no network, and your code may not open files, load datasets, or embed data.","tags":["positional-encoding","rope","length-generalization","transformer","leaderboard"],"id":"fc2accf2-62d7-4169-a045-691824ae7fdd","img_type":"pytorch","dataset_id":"tinystories","evaluation_metric":"bits_per_char","difficulty":"medium","min_eval_metric":2.9,"category":"Language Modeling","title":"Train Short, Test Long","dataset":"TinyStories","time_limits_seconds":{"dev":60,"test":90}}]}