From b20c1697ec3ea963573707ccb3226148b3a8ef16 Mon Sep 17 00:00:00 2001 From: Eliot Robson Date: Wed, 25 Nov 2026 18:45:09 -0500 Subject: [PATCH 1/6] Add a torch grader image with sensible baked-in defaults Add Dockerfile.torch (a glibc base, since PyTorch has no musl wheels) with a CPU build of torch, torchvision and torchinfo on top of the full scientific stack, and publish it as the :torch tag. The image bakes in a 10s default sandbox timeout (via PL_GRADER_SANDBOX_TIMEOUT) and single-threaded numeric defaults, all overridable per question. Documents the image, the tensor assertion helpers, and the dataset/determinism gotchas in torch.md. Co-Authored-By: Claude Opus 4.8 --- .github/workflows/publish.yaml | 4 ++ README.md | 3 ++ docker/Dockerfile.torch | 48 +++++++++++++++++++++ docker/requirements-torch.txt | 12 ++++++ torch.md | 77 ++++++++++++++++++++++++++++++++++ 5 files changed, 144 insertions(+) create mode 100644 docker/Dockerfile.torch create mode 100644 docker/requirements-torch.txt create mode 100644 torch.md diff --git a/.github/workflows/publish.yaml b/.github/workflows/publish.yaml index b463486..880f305 100644 --- a/.github/workflows/publish.yaml +++ b/.github/workflows/publish.yaml @@ -42,6 +42,10 @@ jobs: dockerfile: Dockerfile.lite latest_tag: lite version_suffix: "-lite" + - variant: torch + dockerfile: Dockerfile.torch + latest_tag: torch + version_suffix: "-torch" steps: - uses: actions/checkout@v4 with: diff --git a/README.md b/README.md index 5becb0a..925abf6 100644 --- a/README.md +++ b/README.md @@ -81,6 +81,8 @@ Available helpers: - `assert_fn_approx_equal(sandbox, func_name, args=..., expected=...)` — call + approx compare - `assert_true(condition)` / `assert_false(condition)` — boolean checks - `assert_plot_equal(plot, expected)` — compare a matplotlib plot with a reference plot +- `assert_tensor_allclose(actual, expected, rtol=1e-5, atol=1e-8)` — compare PyTorch tensors within a tolerance (torch image) +- `assert_tensor_equal(actual, expected)` — compare PyTorch tensors exactly (torch image) ### Partial Credit Across Inputs @@ -190,6 +192,7 @@ mypy src/ - `prairielearn/grader-python-pytest:latest` — full image with numpy, pandas, matplotlib, sympy - `prairielearn/grader-python-pytest:lite` — minimal image with core dependencies only +- `prairielearn/grader-python-pytest:torch` — full image plus a CPU build of PyTorch, torchvision, and torchinfo. See [torch.md](torch.md). ## Related Issues diff --git a/docker/Dockerfile.torch b/docker/Dockerfile.torch new file mode 100644 index 0000000..8fef0dd --- /dev/null +++ b/docker/Dockerfile.torch @@ -0,0 +1,48 @@ +# Torch grader image. +# +# Unlike the lite/full images, this one uses a glibc (Debian) base instead of Alpine, because +# PyTorch publishes only manylinux (glibc) wheels — there are no musl wheels to install on Alpine. +# It is pinned to Python 3.13, the newest version with stable CPU torch wheels. +# +# https://docs.astral.sh/uv/guides/integration/docker/#available-images +FROM ghcr.io/astral-sh/uv:python3.13-bookworm-slim + +# Needed to properly handle UTF-8 +ENV PYTHONIOENCODING=UTF-8 +ENV LANG=C.UTF-8 + +WORKDIR / + +RUN apt-get update \ + && apt-get install -y --no-install-recommends \ + util-linux \ + sudo \ + && rm -rf /var/lib/apt/lists/* + +COPY requirements-full.txt requirements-torch.txt / +ARG PACKAGE_VERSION=latest +# Install the CPU-only torch build from the PyTorch index so the image doesn't pull the +# multi-gigabyte CUDA packages. torchinfo and the grader itself come from PyPI. +RUN uv venv --seed \ + && uv pip install --no-cache-dir -r requirements-full.txt \ + && uv pip install --no-cache-dir --index-url https://download.pytorch.org/whl/cpu torch torchvision \ + && uv pip install --no-cache-dir torchinfo \ + && uv pip install --no-cache-dir pytest-prairielearn-grader==${PACKAGE_VERSION} + +# Create 'ag' user for privilege dropping in student code sandbox +RUN adduser --disabled-password --gecos "" ag +COPY --chmod=755 run.sh /run.sh + +# Add serverFilesCourse to Python path +ENV PYTHONPATH=/grade/serverFilesCourse/ + +# --- Baked-in defaults (all overridable per question) --- +# Importing torch and running a model easily exceeds the 1-second default, so give questions more +# head-room. A question can still set any value via sandbox_timeout in its ConfigObject. +ENV PL_GRADER_SANDBOX_TIMEOUT=10 +# Keep the numeric libraries single-threaded by default for reproducible grading within the grader's +# CPU budget. Student code can override this by setting the thread count itself. +ENV OMP_NUM_THREADS=1 +ENV MKL_NUM_THREADS=1 + +ENTRYPOINT [ "/run.sh" ] diff --git a/docker/requirements-torch.txt b/docker/requirements-torch.txt new file mode 100644 index 0000000..02ed9b3 --- /dev/null +++ b/docker/requirements-torch.txt @@ -0,0 +1,12 @@ +# Extra packages for the torch image, on top of requirements-full.txt. +# +# torch and torchvision are installed from the PyTorch CPU index +# (https://download.pytorch.org/whl/cpu) in Dockerfile.torch so that no CUDA packages are pulled. +# torchinfo (the maintained successor to torchsummary, for model/parameter summaries) comes from +# PyPI. +# +# Versions are intentionally left as floors for now; pin them before cutting a release once the +# resolved CPU wheels have been validated in the image. +torch>=2.4 +torchvision>=0.19 +torchinfo>=1.8 diff --git a/torch.md b/torch.md new file mode 100644 index 0000000..1571a7c --- /dev/null +++ b/torch.md @@ -0,0 +1,77 @@ +# PyTorch grading + +The `prairielearn/grader-python-pytest:torch` image adds a CPU build of PyTorch (plus `torchvision` +and `torchinfo`) on top of the full scientific stack, for grading machine-learning and data-science +questions. + +Use it by setting the image in a question's `info.json`: + +```json +{ + "externalGradingOptions": { + "enabled": true, + "image": "prairielearn/grader-python-pytest:torch", + "timeout": 60 + } +} +``` + +The image uses a Debian (glibc) base rather than the Alpine base of the `lite`/`latest` images, +because PyTorch publishes only glibc wheels. Only the CPU build is installed, so the image stays far +smaller than a CUDA image and runs anywhere. + +## Baked-in defaults (all overridable) + +Importing torch and running a model takes much longer than the grader's usual 1-second budget, so +the image ships more sensible defaults. Every one of these can be overridden per question. + +| Setting | Image default | How to override | +| ------------------------- | ------------- | ----------------------------------------------------------------- | +| Sandbox timeout (seconds) | `10` | Set `sandbox_timeout` in the question's `ConfigObject` | +| `OMP_NUM_THREADS` | `1` | Set the thread count in student/setup code, or override the env | +| `MKL_NUM_THREADS` | `1` | Set the thread count in student/setup code, or override the env | + +The sandbox-timeout default comes from the `PL_GRADER_SANDBOX_TIMEOUT` environment variable, which +the image sets. A question that sets `sandbox_timeout` in its `ConfigObject` always wins: + +```python +from pytest_prairielearn_grader import ConfigObject + +# This question needs longer than the image's 10s default. +autograder_config = ConfigObject(sandbox_timeout=30.0) +``` + +Threads are pinned to 1 for reproducible grading within the grader's CPU budget. Raise them in setup +or student code if a question genuinely needs parallelism. + +## Comparing tensors + +Two assertion helpers produce clean, student-facing messages for tensor comparisons. Both accept +anything `torch.as_tensor` understands (a tensor, a NumPy array, or a nested list) and compare on the +CPU after detaching from autograd. + +```python +from pytest_prairielearn_grader.assertions import assert_tensor_allclose, assert_tensor_equal + +@pytest.mark.grading_data(name="forward pass", points=5) +def test_forward(sandbox: StudentFixture) -> None: + output = sandbox.query_function("forward", sample_input) + assert_tensor_allclose(output, expected_output, rtol=1e-4) +``` + +- `assert_tensor_allclose(actual, expected, *, rtol, atol, check_dtype=False, equal_nan=True)` — for + floating-point tensors. Reports shape mismatches, the number of differing elements, and the + maximum absolute difference. +- `assert_tensor_equal(actual, expected, *, check_dtype=False)` — for integer, boolean, or index + tensors where exact equality is meaningful. + +Student functions may also simply return a `torch.Tensor`; the grader serializes it automatically, +so `sandbox.query_function(...)` returns a tensor you can compare directly. + +## Gotchas + +- **No dataset downloads.** The grading sandbox has no network access, so + `torchvision.datasets(..., download=True)` won't work. Ship any dataset the question needs as a + `data_files` entry and load it from the local path instead. +- **Determinism.** Seed torch (and NumPy/`random`) in `setup_code.py` so grading is reproducible, + e.g. `torch.manual_seed(0)`. From 721a02aebc47c006ca77ce621a2dfc6fb113599c Mon Sep 17 00:00:00 2001 From: Eliot Robson Date: Wed, 25 Nov 2026 22:56:37 -0500 Subject: [PATCH 2/6] Make the torch image's dependencies self-contained and pinned Give the torch image its own fully pinned requirements file instead of layering on requirements-full.txt. The torch image runs on a different Python and libc than the full image and pins torch tightly to specific numpy/Pillow versions, so it should pin its scientific stack on its own terms rather than silently inheriting the full image's bumps. Also fixes a latent bug: Dockerfile.torch copied requirements-torch.txt but installed torch/torchvision/torchinfo by bare name, so the file was never actually used. The whole set now installs from that one file, with the PyTorch CPU index as the primary index so only CPU wheels are pulled. Co-Authored-By: Claude Opus 4.8 --- docker/Dockerfile.torch | 15 ++++++---- docker/requirements-torch.txt | 52 ++++++++++++++++++++++++++++------- 2 files changed, 51 insertions(+), 16 deletions(-) diff --git a/docker/Dockerfile.torch b/docker/Dockerfile.torch index 8fef0dd..c0a5848 100644 --- a/docker/Dockerfile.torch +++ b/docker/Dockerfile.torch @@ -19,14 +19,17 @@ RUN apt-get update \ sudo \ && rm -rf /var/lib/apt/lists/* -COPY requirements-full.txt requirements-torch.txt / +COPY requirements-torch.txt / ARG PACKAGE_VERSION=latest -# Install the CPU-only torch build from the PyTorch index so the image doesn't pull the -# multi-gigabyte CUDA packages. torchinfo and the grader itself come from PyPI. +# Install everything from one self-contained, pinned requirements file. The PyTorch CPU index is the +# primary index, so torch/torchvision resolve to CPU-only wheels (no multi-gigabyte CUDA packages); +# every other package falls through to PyPI. uv's default first-index strategy keeps that routing +# safe because the PyTorch index hosts only torch packages. RUN uv venv --seed \ - && uv pip install --no-cache-dir -r requirements-full.txt \ - && uv pip install --no-cache-dir --index-url https://download.pytorch.org/whl/cpu torch torchvision \ - && uv pip install --no-cache-dir torchinfo \ + && uv pip install --no-cache-dir \ + --index-url https://download.pytorch.org/whl/cpu \ + --extra-index-url https://pypi.org/simple \ + -r requirements-torch.txt \ && uv pip install --no-cache-dir pytest-prairielearn-grader==${PACKAGE_VERSION} # Create 'ag' user for privilege dropping in student code sandbox diff --git a/docker/requirements-torch.txt b/docker/requirements-torch.txt index 02ed9b3..ca69061 100644 --- a/docker/requirements-torch.txt +++ b/docker/requirements-torch.txt @@ -1,12 +1,44 @@ -# Extra packages for the torch image, on top of requirements-full.txt. +# Self-contained, fully pinned dependency set for the torch grader image. # -# torch and torchvision are installed from the PyTorch CPU index -# (https://download.pytorch.org/whl/cpu) in Dockerfile.torch so that no CUDA packages are pulled. -# torchinfo (the maintained successor to torchsummary, for model/parameter summaries) comes from -# PyPI. +# This image is NOT built on top of requirements-full.txt: it carries its own copy of the scientific +# stack so its build is reproducible and can pin versions independently of the full image. PyTorch is +# tightly coupled to specific numpy/Pillow versions, and this image runs on a different Python and +# libc (glibc / 3.13) than the full image (musl / 3.14), so it needs to pin those on its own terms. # -# Versions are intentionally left as floors for now; pin them before cutting a release once the -# resolved CPU wheels have been validated in the image. -torch>=2.4 -torchvision>=0.19 -torchinfo>=1.8 +# Trade-off: when a package is added to the full image it must be mirrored here by hand; that drift is +# intentional, so that changes to this heavy ML image are always explicit and reviewed. +# +# torch and torchvision are served from the PyTorch CPU index (https://download.pytorch.org/whl/cpu), +# which Dockerfile.torch sets as the primary index so only CPU wheels are pulled (no CUDA). Every +# other package falls through to PyPI. torchinfo (the maintained successor to torchsummary, for +# model/parameter summaries) comes from PyPI. + +# --- Scientific stack (kept in sync with the full image, pinned independently) --- +beautifulsoup4==4.15.0 +defusedxml==0.7.1 +Faker==40.44.0 +matplotcheck2==0.2.1 +matplotlib==3.11.2 +nbformat==5.11.1 +networkx==3.7 +nltk==3.10.4 +numpy==2.5.4 +openpyxl==3.1.5 +pandas==3.1.0 +Pillow==13.0.0 +PuLP==4.2.0 +Pygments==2.21.0 +pytest==9.2.0 +requests==2.34.2 +scikit-learn==1.9.1 +scipy==1.18.1 +seaborn==0.13.2 +sympy==1.14.0 +typing-extensions==4.16.0 + +# --- Torch stack (CPU wheels from the PyTorch index; torchinfo from PyPI) --- +# These exact versions are provisional until a torch image build validates that the CPU wheels +# resolve against the pinned numpy/Pillow above. Bump them once that build is green. +torch==2.8.0 +torchvision==0.23.0 +torchinfo==1.8.0 From de6ca585ab1e431e5d3b540a9664d9d3aaa5ff77 Mon Sep 17 00:00:00 2001 From: Eliot Robson Date: Wed, 25 Nov 2026 23:08:07 -0500 Subject: [PATCH 3/6] Build the full grader image on a glibc base instead of Alpine MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On the Alpine (musl) base, scikit-learn has no prebuilt wheel, so it compiled from source on every build — pulling in the build-base toolchain and pushing the image build to close to an hour. Every compiled dependency (numpy, scipy, scikit-learn, pandas, matplotlib, Pillow) ships a manylinux wheel for Python 3.14, so switching to the Debian slim base the torch image already uses lets the whole stack install from wheels. No compiler is needed, the build drops to a few minutes, and the image no longer carries build-base. Co-Authored-By: Claude Opus 4.8 --- docker/Dockerfile | 29 ++++++++++++++--------------- 1 file changed, 14 insertions(+), 15 deletions(-) diff --git a/docker/Dockerfile b/docker/Dockerfile index c91f913..fef4ef9 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -1,37 +1,36 @@ +# Full grader image: the lite image plus the scientific Python stack. +# +# Uses a glibc (Debian) base rather than Alpine so numpy/scipy/scikit-learn/pandas/matplotlib/Pillow +# all install from prebuilt manylinux wheels. On Alpine (musl), scikit-learn has no wheel and +# compiles from source, which needs a full C/C++ toolchain (build-base) and pushes the build to +# close to an hour. On glibc no compiler is needed, so the build is a few minutes and the image no +# longer carries the toolchain. +# # https://docs.astral.sh/uv/guides/integration/docker/#available-images -FROM ghcr.io/astral-sh/uv:python3.14-alpine -#ARG CACHEBUST=2025-07-15-14-16-18 +FROM ghcr.io/astral-sh/uv:python3.14-bookworm-slim # Needed to properly handle UTF-8 ENV PYTHONIOENCODING=UTF-8 -ENV LANG=en_US.UTF-8 +ENV LANG=C.UTF-8 WORKDIR / -RUN apk update \ - && apk add --no-cache \ +RUN apt-get update \ + && apt-get install -y --no-install-recommends \ util-linux \ sudo \ - build-base - -# NOTE all the crap below is needed to make pygraphviz work, but we probably don't need to include this -# in the new grader image? We can add back if necessary but not sure what the use cases are. -# dos2unix \ -# graphviz \ -# graphviz-devel + && rm -rf /var/lib/apt/lists/* COPY requirements-full.txt / ARG PACKAGE_VERSION=latest RUN uv venv --seed && uv pip install --no-cache-dir -r requirements-full.txt && \ uv pip install --no-cache-dir pytest-prairielearn-grader==${PACKAGE_VERSION} -# Anything that needs to be run post-install # Create 'ag' user for privilege dropping in student code sandbox -RUN adduser -D ag +RUN adduser --disabled-password --gecos "" ag COPY --chmod=755 run.sh /run.sh # Add serverFilesCourse to Python path -# TODO do we need to copy anything here? ENV PYTHONPATH=/grade/serverFilesCourse/ ENTRYPOINT [ "/run.sh" ] From 47846a9e2ed66be692fb734aeb9976288fde0e99 Mon Sep 17 00:00:00 2001 From: Eliot Robson Date: Wed, 25 Nov 2026 23:08:07 -0500 Subject: [PATCH 4/6] Add a build-only CI workflow for the grader images The publish workflow only builds the images on a release tag, so a broken dependency combination wouldn't surface until release. This builds all three images on PRs and pushes that touch docker/**, amd64-only and without pushing, with per-variant layer caching so unchanged images stay fast. Co-Authored-By: Claude Opus 4.8 --- .github/workflows/docker-build.yaml | 66 +++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 .github/workflows/docker-build.yaml diff --git a/.github/workflows/docker-build.yaml b/.github/workflows/docker-build.yaml new file mode 100644 index 0000000..aa90676 --- /dev/null +++ b/.github/workflows/docker-build.yaml @@ -0,0 +1,66 @@ +name: Docker build + +# Validates that the grader images actually build, without publishing anything. The publish +# workflow only runs on a release tag, so without this a broken dependency combination (for example +# a torch/numpy pin that doesn't resolve) wouldn't surface until release time. +# +# Builds are amd64-only and never pushed. Per-variant layer caching keeps unchanged images close to +# instant, so a change to one image's files doesn't pay to rebuild the others from scratch. + +on: + push: + branches: [main] + paths: + - "docker/**" + - ".github/workflows/docker-build.yaml" + pull_request: + branches: [main] + paths: + - "docker/**" + - ".github/workflows/docker-build.yaml" + +jobs: + build: + runs-on: ubuntu-latest + permissions: + contents: read + strategy: + fail-fast: false + matrix: + include: + - variant: lite + dockerfile: Dockerfile.lite + - variant: full + dockerfile: Dockerfile + - variant: torch + dockerfile: Dockerfile.torch + steps: + - uses: actions/checkout@v4 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: Resolve latest published grader version + id: pkg + run: | + VERSION=$(curl -fsSL https://pypi.org/pypi/pytest-prairielearn-grader/json \ + | python3 -c "import sys, json; print(json.load(sys.stdin)['info']['version'])") + if [ -z "$VERSION" ]; then + echo "Could not resolve grader version from PyPI" >&2 + exit 1 + fi + echo "version=$VERSION" >> "$GITHUB_OUTPUT" + + - name: Build ${{ matrix.variant }} image (no push) + uses: docker/build-push-action@v5 + with: + context: ./docker + file: ./docker/${{ matrix.dockerfile }} + push: false + # amd64 only: this validates the dependency resolution (the real risk) without paying for a + # second architecture. arm64 wheels resolve the same way and can be added if needed. + platforms: linux/amd64 + build-args: | + PACKAGE_VERSION=${{ steps.pkg.outputs.version }} + cache-from: type=gha,scope=${{ matrix.variant }} + cache-to: type=gha,mode=max,scope=${{ matrix.variant }} From 7df2129c1255aa86a1ef932e62bae43b2044dd51 Mon Sep 17 00:00:00 2001 From: Eliot Robson Date: Wed, 25 Nov 2026 23:41:52 -0500 Subject: [PATCH 5/6] Cross-reference the two image matrices to keep them in sync The publish and build-only workflows each carry their own copy of the image matrix. Add a comment in each pointing at the other so a new image isn't added to one and forgotten in the other. Co-Authored-By: Claude Opus 4.8 --- .github/workflows/docker-build.yaml | 1 + .github/workflows/publish.yaml | 1 + 2 files changed, 2 insertions(+) diff --git a/.github/workflows/docker-build.yaml b/.github/workflows/docker-build.yaml index aa90676..67777da 100644 --- a/.github/workflows/docker-build.yaml +++ b/.github/workflows/docker-build.yaml @@ -26,6 +26,7 @@ jobs: contents: read strategy: fail-fast: false + # Keep this image list in sync with the publish matrix in publish.yaml. matrix: include: - variant: lite diff --git a/.github/workflows/publish.yaml b/.github/workflows/publish.yaml index 880f305..34c5755 100644 --- a/.github/workflows/publish.yaml +++ b/.github/workflows/publish.yaml @@ -32,6 +32,7 @@ jobs: permissions: contents: read strategy: + # Keep this image list in sync with the build-only matrix in docker-build.yaml. matrix: include: - variant: full From e117646f183802c3dd63a1faacc8af37e216e57b Mon Sep 17 00:00:00 2001 From: Eliot Robson Date: Wed, 25 Nov 2026 23:49:34 -0500 Subject: [PATCH 6/6] Fold the torch docs into the quick start guide Move the standalone torch.md into a PyTorch grading section of quick_start.md, add the :torch row to the image table (which still listed only two variants), and point the README there. A later PR will reorganize these docs further. Co-Authored-By: Claude Opus 4.8 --- README.md | 2 +- quick_start.md | 81 ++++++++++++++++++++++++++++++++++++++++++++++++-- torch.md | 77 ----------------------------------------------- 3 files changed, 80 insertions(+), 80 deletions(-) delete mode 100644 torch.md diff --git a/README.md b/README.md index 925abf6..836272b 100644 --- a/README.md +++ b/README.md @@ -192,7 +192,7 @@ mypy src/ - `prairielearn/grader-python-pytest:latest` — full image with numpy, pandas, matplotlib, sympy - `prairielearn/grader-python-pytest:lite` — minimal image with core dependencies only -- `prairielearn/grader-python-pytest:torch` — full image plus a CPU build of PyTorch, torchvision, and torchinfo. See [torch.md](torch.md). +- `prairielearn/grader-python-pytest:torch` — full image plus a CPU build of PyTorch, torchvision, and torchinfo. See the [PyTorch grading](quick_start.md#pytorch-grading) section of the quick start guide. ## Related Issues diff --git a/quick_start.md b/quick_start.md index 78ec905..3ded6e1 100644 --- a/quick_start.md +++ b/quick_start.md @@ -57,16 +57,17 @@ Set `gradingMethod` to `"External"` and pick a grader image: ### Choosing an Image -Two image variants are published. Pick the smallest one that includes what your question needs — a smaller image means faster cold-start pull times and a reduced security surface. +Three image variants are published. Pick the smallest one that includes what your question needs — a smaller image means faster cold-start pull times and a reduced security surface. | Tag | Size (approx.) | Includes | Best for | | --------- | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | | `:latest` | ~400–500 MB | Full scientific stack: `numpy`, `pandas`, `scipy`, `matplotlib` + `matplotcheck2`, `seaborn`, `scikit-learn`, `sympy`, `networkx`, `nltk`, `nbformat`, and more | Any course that needs scientific computing, data science, plotting, or Jupyter notebook grading | | `:lite` | ~60–80 MB | Grader core only: `pytest-prairielearn-grader`, `Pygments`, `beautifulsoup4`, `defusedxml`, `requests` | Introductory CS courses where student code uses only the Python standard library | +| `:torch` | ~1–1.5 GB | Everything in `:latest` plus a CPU build of PyTorch, `torchvision`, and `torchinfo` | Machine-learning and data-science questions that grade PyTorch tensors or models. See [PyTorch grading](#pytorch-grading) | > **Note:** If a student's code imports a package that isn't present in the image (e.g., `numpy` in `:lite`), it will raise an `ImportError` and the test will fail with an exception. Make sure the image you choose contains everything both your test code and the expected student solution require. -Pinned version tags (e.g., `:v1.2.3` and `:v1.2.3-lite`) are also published alongside each release if you need a reproducible build. +Pinned version tags (e.g., `:v1.2.3`, `:v1.2.3-lite`, and `:v1.2.3-torch`) are also published alongside each release if you need a reproducible build. ### `question.html` @@ -2095,6 +2096,82 @@ def divide(a, b): return a / b ``` +## PyTorch grading + +The `prairielearn/grader-python-pytest:torch` image adds a CPU build of PyTorch (plus `torchvision` +and `torchinfo`) on top of the full scientific stack, for grading machine-learning and data-science +questions. Select it like any other image (see [Choosing an Image](#choosing-an-image)): + +```json +{ + "externalGradingOptions": { + "enabled": true, + "image": "prairielearn/grader-python-pytest:torch", + "timeout": 60 + } +} +``` + +The image uses a Debian (glibc) base rather than the Alpine base of the `lite`/`latest` images, +because PyTorch publishes only glibc wheels. Only the CPU build is installed, so the image stays far +smaller than a CUDA image and runs anywhere. + +### Baked-in defaults (all overridable) + +Importing torch and running a model takes much longer than the grader's usual 1-second budget, so +the image ships more sensible defaults. Every one of these can be overridden per question. + +| Setting | Image default | How to override | +| ------------------------- | ------------- | --------------------------------------------------------------- | +| Sandbox timeout (seconds) | `10` | Set `sandbox_timeout` in the question's `ConfigObject` | +| `OMP_NUM_THREADS` | `1` | Set the thread count in student/setup code, or override the env | +| `MKL_NUM_THREADS` | `1` | Set the thread count in student/setup code, or override the env | + +The sandbox-timeout default comes from the `PL_GRADER_SANDBOX_TIMEOUT` environment variable, which +the image sets. A question that sets `sandbox_timeout` in its `ConfigObject` always wins: + +```python +from pytest_prairielearn_grader import ConfigObject + +# This question needs longer than the image's 10s default. +autograder_config = ConfigObject(sandbox_timeout=30.0) +``` + +Threads are pinned to 1 for reproducible grading within the grader's CPU budget. Raise them in setup +or student code if a question genuinely needs parallelism. + +### Comparing tensors + +Two assertion helpers produce clean, student-facing messages for tensor comparisons. Both accept +anything `torch.as_tensor` understands (a tensor, a NumPy array, or a nested list) and compare on the +CPU after detaching from autograd. + +```python +from pytest_prairielearn_grader.assertions import assert_tensor_allclose, assert_tensor_equal + +@pytest.mark.grading_data(name="forward pass", points=5) +def test_forward(sandbox: StudentFixture) -> None: + output = sandbox.query_function("forward", sample_input) + assert_tensor_allclose(output, expected_output, rtol=1e-4) +``` + +- `assert_tensor_allclose(actual, expected, *, rtol, atol, check_dtype=False, equal_nan=True)` — for + floating-point tensors. Reports shape mismatches, the number of differing elements, and the + maximum absolute difference. +- `assert_tensor_equal(actual, expected, *, check_dtype=False)` — for integer, boolean, or index + tensors where exact equality is meaningful. + +Student functions may also simply return a `torch.Tensor`; the grader serializes it automatically, +so `sandbox.query_function(...)` returns a tensor you can compare directly. + +### Gotchas + +- **No dataset downloads.** The grading sandbox has no network access, so + `torchvision.datasets(..., download=True)` won't work. Ship any dataset the question needs as a + `data_files` entry and load it from the local path instead. +- **Determinism.** Seed torch (and NumPy/`random`) in `setup_code.py` so grading is reproducible, + e.g. `torch.manual_seed(0)`. + ## More Examples To see more examples of what is possible in these test files, look at the test cases in diff --git a/torch.md b/torch.md deleted file mode 100644 index 1571a7c..0000000 --- a/torch.md +++ /dev/null @@ -1,77 +0,0 @@ -# PyTorch grading - -The `prairielearn/grader-python-pytest:torch` image adds a CPU build of PyTorch (plus `torchvision` -and `torchinfo`) on top of the full scientific stack, for grading machine-learning and data-science -questions. - -Use it by setting the image in a question's `info.json`: - -```json -{ - "externalGradingOptions": { - "enabled": true, - "image": "prairielearn/grader-python-pytest:torch", - "timeout": 60 - } -} -``` - -The image uses a Debian (glibc) base rather than the Alpine base of the `lite`/`latest` images, -because PyTorch publishes only glibc wheels. Only the CPU build is installed, so the image stays far -smaller than a CUDA image and runs anywhere. - -## Baked-in defaults (all overridable) - -Importing torch and running a model takes much longer than the grader's usual 1-second budget, so -the image ships more sensible defaults. Every one of these can be overridden per question. - -| Setting | Image default | How to override | -| ------------------------- | ------------- | ----------------------------------------------------------------- | -| Sandbox timeout (seconds) | `10` | Set `sandbox_timeout` in the question's `ConfigObject` | -| `OMP_NUM_THREADS` | `1` | Set the thread count in student/setup code, or override the env | -| `MKL_NUM_THREADS` | `1` | Set the thread count in student/setup code, or override the env | - -The sandbox-timeout default comes from the `PL_GRADER_SANDBOX_TIMEOUT` environment variable, which -the image sets. A question that sets `sandbox_timeout` in its `ConfigObject` always wins: - -```python -from pytest_prairielearn_grader import ConfigObject - -# This question needs longer than the image's 10s default. -autograder_config = ConfigObject(sandbox_timeout=30.0) -``` - -Threads are pinned to 1 for reproducible grading within the grader's CPU budget. Raise them in setup -or student code if a question genuinely needs parallelism. - -## Comparing tensors - -Two assertion helpers produce clean, student-facing messages for tensor comparisons. Both accept -anything `torch.as_tensor` understands (a tensor, a NumPy array, or a nested list) and compare on the -CPU after detaching from autograd. - -```python -from pytest_prairielearn_grader.assertions import assert_tensor_allclose, assert_tensor_equal - -@pytest.mark.grading_data(name="forward pass", points=5) -def test_forward(sandbox: StudentFixture) -> None: - output = sandbox.query_function("forward", sample_input) - assert_tensor_allclose(output, expected_output, rtol=1e-4) -``` - -- `assert_tensor_allclose(actual, expected, *, rtol, atol, check_dtype=False, equal_nan=True)` — for - floating-point tensors. Reports shape mismatches, the number of differing elements, and the - maximum absolute difference. -- `assert_tensor_equal(actual, expected, *, check_dtype=False)` — for integer, boolean, or index - tensors where exact equality is meaningful. - -Student functions may also simply return a `torch.Tensor`; the grader serializes it automatically, -so `sandbox.query_function(...)` returns a tensor you can compare directly. - -## Gotchas - -- **No dataset downloads.** The grading sandbox has no network access, so - `torchvision.datasets(..., download=True)` won't work. Ship any dataset the question needs as a - `data_files` entry and load it from the local path instead. -- **Determinism.** Seed torch (and NumPy/`random`) in `setup_code.py` so grading is reproducible, - e.g. `torch.manual_seed(0)`.