diff --git a/.github/workflows/docker-build.yaml b/.github/workflows/docker-build.yaml new file mode 100644 index 0000000..67777da --- /dev/null +++ b/.github/workflows/docker-build.yaml @@ -0,0 +1,67 @@ +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 + # Keep this image list in sync with the publish matrix in publish.yaml. + 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 }} diff --git a/.github/workflows/publish.yaml b/.github/workflows/publish.yaml index b463486..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 @@ -42,6 +43,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..836272b 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 the [PyTorch grading](quick_start.md#pytorch-grading) section of the quick start guide. ## Related Issues 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" ] diff --git a/docker/Dockerfile.torch b/docker/Dockerfile.torch new file mode 100644 index 0000000..c0a5848 --- /dev/null +++ b/docker/Dockerfile.torch @@ -0,0 +1,51 @@ +# 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-torch.txt / +ARG PACKAGE_VERSION=latest +# 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 \ + --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 +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..ca69061 --- /dev/null +++ b/docker/requirements-torch.txt @@ -0,0 +1,44 @@ +# Self-contained, fully pinned dependency set for the torch grader image. +# +# 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. +# +# 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 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