From 82177a261958ef98a343345c1e46396eebd9c5f1 Mon Sep 17 00:00:00 2001 From: Yuxuan <31838999+Essoz@users.noreply.github.com> Date: Sun, 29 Nov 2026 03:28:24 -0800 Subject: [PATCH 01/12] Add TrainCheck Modal L4 correctness runner --- ci/modal_gpu.py | 74 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 ci/modal_gpu.py diff --git a/ci/modal_gpu.py b/ci/modal_gpu.py new file mode 100644 index 00000000..6b4a4db3 --- /dev/null +++ b/ci/modal_gpu.py @@ -0,0 +1,74 @@ +"""Run TrainCheck's CUDA correctness smoke tests on one Modal L4.""" + +import sys +import tomllib +import unittest +from pathlib import Path + +import modal + +ROOT = Path(__file__).resolve().parents[1] +REMOTE_ROOT = "/root/traincheck-ci" + +with (ROOT / "pyproject.toml").open("rb") as config: + dependencies: list[str] = tomllib.load(config)["project"]["dependencies"] + +image = ( + # Numba compiles CUDA kernels at runtime and needs the toolkit's NVVM. + modal.Image.from_registry("nvidia/cuda:12.8.1-devel-ubuntu22.04", add_python="3.12") + .env({"CUDA_HOME": "/usr/local/cuda"}) + .pip_install("torch==2.7.1", index_url="https://download.pytorch.org/whl/cu128") + .pip_install(*dependencies, "numba==0.63.1") + .workdir(REMOTE_ROOT) + .add_local_dir(ROOT / "traincheck", f"{REMOTE_ROOT}/traincheck") + .add_local_dir(ROOT / "tests", f"{REMOTE_ROOT}/tests") +) +app = modal.App("traincheck-cuda-ci", image=image) + + +@app.function( + gpu="L4", + cpu=2, + memory=4096, + timeout=600, + scaledown_window=2, + serialized=True, + include_source=False, +) +def gpu_tests() -> None: + # Ship only the two mounted directories, not the CLI checkout or secrets. + sys.path.insert(0, REMOTE_ROOT) + + import numba + import torch + + if not torch.cuda.is_available(): + raise RuntimeError("TrainCheck CUDA CI requires a real CUDA device") + + print( + f"GPU: {torch.cuda.get_device_name(0)}; " + f"PyTorch: {torch.__version__}; CUDA: {torch.version.cuda}; " + f"Numba: {numba.__version__}", + flush=True, + ) + # Import only after the CUDA check: the module can skip GPU tests on CPU. + from tests import test_cuda_hashing_contracts + + loader = unittest.defaultTestLoader + gpu_suite = loader.loadTestsFromTestCase( + test_cuda_hashing_contracts.CudaHashValueTests + ) + if not gpu_suite.countTestCases(): + raise RuntimeError("No CUDA test cases were collected") + suite = loader.loadTestsFromModule(test_cuda_hashing_contracts) + result = unittest.TextTestRunner(verbosity=2).run(suite) + if not result.wasSuccessful() or result.skipped: + raise RuntimeError( + f"CUDA smoke suite did not pass without skips " + f"({result.testsRun} tests, {len(result.skipped)} skipped)" + ) + + +@app.local_entrypoint() +def main() -> None: + gpu_tests.remote() From 3f449c16928cccb2804fdc0abfed2ec3b85fadac Mon Sep 17 00:00:00 2001 From: Yuxuan <31838999+Essoz@users.noreply.github.com> Date: Sun, 29 Nov 2026 03:30:25 -0800 Subject: [PATCH 02/12] Run unit tests on GitHub and CUDA tests on Modal --- .github/workflows/modal-gpu-ci.yml | 58 ++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 .github/workflows/modal-gpu-ci.yml diff --git a/.github/workflows/modal-gpu-ci.yml b/.github/workflows/modal-gpu-ci.yml new file mode 100644 index 00000000..218b0d1b --- /dev/null +++ b/.github/workflows/modal-gpu-ci.yml @@ -0,0 +1,58 @@ +name: TrainCheck tests + +on: + pull_request: + push: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + +jobs: + unit-tests: + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + persist-credentials: false + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065b # v5.6.0 + with: + python-version: '3.12' + - name: Install CPU test dependencies + run: | + python -m pip install torch==2.13.0 --index-url https://download.pytorch.org/whl/cpu + python -m pip install -e . pytest==8.4.2 + - name: Run unit and small regression tests + run: python -m pytest -q -rs tests/ + + cuda-tests: + concurrency: + group: modal-cuda-tests + cancel-in-progress: false + # Only reviewed code on main should be able to use the Modal credentials. + if: github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main' + runs-on: ubuntu-latest + environment: modal-gpu-ci + timeout-minutes: 20 + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + persist-credentials: false + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065b # v5.6.0 + with: + python-version: '3.12' + - name: Install Modal CLI + run: python -m pip install modal==1.6.4 + - name: Run the CUDA correctness suite + env: + MODAL_TOKEN_ID: ${{ secrets.MODAL_TOKEN_ID }} + MODAL_TOKEN_SECRET: ${{ secrets.MODAL_TOKEN_SECRET }} + run: | + set -euo pipefail + if [[ -z "$MODAL_TOKEN_ID" || -z "$MODAL_TOKEN_SECRET" ]]; then + echo "::error::Modal token secrets are missing from the modal-gpu-ci environment" + exit 1 + fi + modal run ci/modal_gpu.py From 7712082549f81578aa29f396a2ee66bb057f6048 Mon Sep 17 00:00:00 2001 From: Yuxuan <31838999+Essoz@users.noreply.github.com> Date: Sun, 29 Nov 2026 03:31:01 -0800 Subject: [PATCH 03/12] Make legacy correctness-check workflow manual --- .github/workflows/correctness_checks.yml | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/.github/workflows/correctness_checks.yml b/.github/workflows/correctness_checks.yml index 3574fca3..17111429 100644 --- a/.github/workflows/correctness_checks.yml +++ b/.github/workflows/correctness_checks.yml @@ -1,15 +1,6 @@ name: Correctness Checks on: - push: - branches: - - main - pull_request: - paths: - - '.github/workflows/**' - - 'traincheck/invariant/**' - - 'traincheck/onlinechecker/**' - - 'traincheck/checker_online.py' - - 'traincheck/checker.py' + workflow_dispatch: permissions: contents: write @@ -18,6 +9,7 @@ permissions: jobs: correctness-check: + if: github.ref == 'refs/heads/main' runs-on: self-hosted name: Run Correctness Checks From ae728ea423be41157afec19f19d47bd1edb8c9f4 Mon Sep 17 00:00:00 2001 From: Yuxuan <31838999+Essoz@users.noreply.github.com> Date: Sun, 29 Nov 2026 03:31:17 -0800 Subject: [PATCH 04/12] Make legacy benchmark workflow manual --- .github/workflows/eval-overhead-e2e.yml | 17 +++-------------- 1 file changed, 3 insertions(+), 14 deletions(-) diff --git a/.github/workflows/eval-overhead-e2e.yml b/.github/workflows/eval-overhead-e2e.yml index f765ae78..bf13819a 100644 --- a/.github/workflows/eval-overhead-e2e.yml +++ b/.github/workflows/eval-overhead-e2e.yml @@ -1,18 +1,6 @@ name: Instrumentor Benchmark -on: - push: - branches: - - main - paths: - - '.github/workflows/**' - - 'traincheck/instrumentor/**' - - 'traincheck/collect_trace.py' - pull_request: - paths: - - '.github/workflows/**' - - 'traincheck/instrumentor/**' - - 'traincheck/collect_trace.py' - +on: + workflow_dispatch: permissions: contents: write @@ -21,6 +9,7 @@ permissions: jobs: benchmark: + if: github.ref == 'refs/heads/main' runs-on: self-hosted name: Run Overhead Benchmarks From 998ca29d8cad34c7c471e6a3f968c4f56085bcc9 Mon Sep 17 00:00:00 2001 From: Yuxuan <31838999+Essoz@users.noreply.github.com> Date: Sun, 29 Nov 2026 03:33:02 -0800 Subject: [PATCH 05/12] Pin the tested pandas and NumPy versions in CPU CI --- .github/workflows/modal-gpu-ci.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/modal-gpu-ci.yml b/.github/workflows/modal-gpu-ci.yml index 218b0d1b..466c481d 100644 --- a/.github/workflows/modal-gpu-ci.yml +++ b/.github/workflows/modal-gpu-ci.yml @@ -23,7 +23,8 @@ jobs: - name: Install CPU test dependencies run: | python -m pip install torch==2.13.0 --index-url https://download.pytorch.org/whl/cpu - python -m pip install -e . pytest==8.4.2 + # Match the tested pandas 2.x trace backend; pandas 3.x infers string dtypes differently. + python -m pip install -e . pytest==8.4.2 pandas==2.3.3 numpy==2.1.0 - name: Run unit and small regression tests run: python -m pytest -q -rs tests/ From 786db10632415f53b1491f9d81bf65010bb3f419 Mon Sep 17 00:00:00 2001 From: Yuxuan <31838999+Essoz@users.noreply.github.com> Date: Sun, 29 Nov 2026 03:33:49 -0800 Subject: [PATCH 06/12] Test eval injection with an explicit evaluation signal --- tests/test_loop_injection.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/tests/test_loop_injection.py b/tests/test_loop_injection.py index 0ec20ecc..461bf966 100644 --- a/tests/test_loop_injection.py +++ b/tests/test_loop_injection.py @@ -36,12 +36,13 @@ def train(): self.assertIn("start_step", new_source) - def test_inject_eval_loop(self): + def test_inject_eval_loop(self) -> None: source = """ import torch -def test(): - for i in range(10): - print(i) +def evaluate(model, inputs): + for batch in inputs: + with torch.no_grad(): + model(batch) """ visitor = InsertTracerVisitor( @@ -60,7 +61,7 @@ def test(): new_source = ast.unparse(tree) new_source = ast.unparse(tree) - # Should detect "test" function name and inject start_eval_step + # An explicit no_grad context makes this an evaluation loop. self.assertIn("import start_eval_step", new_source) self.assertIn("start_eval_step()", new_source) From 8059cb680c5167bb421bd22ec3eb7d06602e06f7 Mon Sep 17 00:00:00 2001 From: Yuxuan <31838999+Essoz@users.noreply.github.com> Date: Sun, 29 Nov 2026 03:34:00 -0800 Subject: [PATCH 07/12] Test display-name normalization without dropping the attribute --- tests/test_display_names.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/tests/test_display_names.py b/tests/test_display_names.py index 68ffd112..bcb60e71 100644 --- a/tests/test_display_names.py +++ b/tests/test_display_names.py @@ -76,8 +76,8 @@ def test_post_value_non_zero_normalized(self): assert "non_zero" not in name assert "non-zero" in name - def test_traincheck_internal_attr_hidden(self): - """Attributes starting with _TRAINCHECK_ are internal proxy IDs and should be filtered.""" + def test_traincheck_internal_prefix_stripped(self) -> None: + """Proxy bookkeeping prefixes are hidden but the attribute stays visible.""" params = [ APIParam("torch.optim.sgd.SGD.step"), VarTypeParam( @@ -87,7 +87,10 @@ def test_traincheck_internal_attr_hidden(self): post_value="above_zero", ), ] - assert APIContainRelation.to_display_name(params) is None + name = APIContainRelation.to_display_name(params) + assert name is not None + assert "Parameter.grad_ID" in name + assert "_TRAINCHECK_" not in name def test_returns_none_for_empty_params(self): assert APIContainRelation.to_display_name([]) is None From 4be4a50a071b7b54d0125c2b50e0b1deb1246b65 Mon Sep 17 00:00:00 2001 From: Yuxuan <31838999+Essoz@users.noreply.github.com> Date: Sun, 29 Nov 2026 03:49:23 -0800 Subject: [PATCH 08/12] Move pre-commit checks to GitHub-hosted CPU --- .github/workflows/pre-commit-checks.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/pre-commit-checks.yml b/.github/workflows/pre-commit-checks.yml index 52e97e68..7f22d8f8 100644 --- a/.github/workflows/pre-commit-checks.yml +++ b/.github/workflows/pre-commit-checks.yml @@ -16,7 +16,7 @@ on: jobs: pre-commit: - runs-on: self-hosted + runs-on: ubuntu-latest steps: - name: Checkout repository @@ -34,7 +34,7 @@ jobs: pip install mypy==1.9.0 pip install isort pip install ruff==0.3.3 - pip install torch + pip install torch --index-url https://download.pytorch.org/whl/cpu pip install tqdm pip install bytecode From 3ecf539f46869b9cc49ca71323c25cb8868d8320 Mon Sep 17 00:00:00 2001 From: Yuxuan <31838999+Essoz@users.noreply.github.com> Date: Sun, 29 Nov 2026 03:50:25 -0800 Subject: [PATCH 09/12] Remove trailing whitespace caught by Black --- traincheck/config/config.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/traincheck/config/config.py b/traincheck/config/config.py index 51b570fa..81658aca 100644 --- a/traincheck/config/config.py +++ b/traincheck/config/config.py @@ -198,7 +198,7 @@ def should_disable_proxy_dumping() -> bool: MAX_PRECOND_DEPTH = 8 # the maximum depth of the precondition inference ENABLE_PRECOND_SAMPLING = True # whether to enable sampling of positive and negative examples for precondition inference, can be overridden by the command line argument PRECOND_SAMPLING_THRESHOLD = 10000 # the number of samples to take for precondition inference, if the number of samples is larger than this threshold, we will sample this number of samples -MAX_EXAMPLE_LIST_SIZE = 5000 +MAX_EXAMPLE_LIST_SIZE = 5000 EXAMPLE_SAMPLING_SEED = 42 NOT_USE_AS_CLAUSE_FIELDS = [ "func_call_id", From 1613c8141f69119bdeb362b78c9b73b1b5bd4d00 Mon Sep 17 00:00:00 2001 From: Yuxuan <31838999+Essoz@users.noreply.github.com> Date: Sun, 29 Nov 2026 03:53:43 -0800 Subject: [PATCH 10/12] Install the typed Module setattr hook as a runtime patch --- traincheck/instrumentor/proxy_wrapper/subclass.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/traincheck/instrumentor/proxy_wrapper/subclass.py b/traincheck/instrumentor/proxy_wrapper/subclass.py index baf2838a..28195055 100644 --- a/traincheck/instrumentor/proxy_wrapper/subclass.py +++ b/traincheck/instrumentor/proxy_wrapper/subclass.py @@ -525,4 +525,5 @@ def wrapped_setattr(self: nn.Module, name: str, value: object) -> None: hook(self, name) -torch.nn.Module.__setattr__ = wrapped_setattr +# Install the typed replacement intentionally at runtime. +setattr(torch.nn.Module, "__setattr__", wrapped_setattr) From 17d147f0cd54bc1a926d26d3372310f0029a6926 Mon Sep 17 00:00:00 2001 From: Yuxuan <31838999+Essoz@users.noreply.github.com> Date: Sun, 29 Nov 2026 03:53:55 -0800 Subject: [PATCH 11/12] Let maintainers dispatch CUDA tests for a reviewed PR commit --- .github/workflows/modal-gpu-ci.yml | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/.github/workflows/modal-gpu-ci.yml b/.github/workflows/modal-gpu-ci.yml index 466c481d..55dbc226 100644 --- a/.github/workflows/modal-gpu-ci.yml +++ b/.github/workflows/modal-gpu-ci.yml @@ -5,6 +5,18 @@ on: push: branches: [main] workflow_dispatch: + inputs: + pr_number: + description: "Optional PR number (leave blank to test main)" + type: string + head_sha: + description: "Full 40-character reviewed PR head SHA (required with PR number)" + type: string + cuda_suite: + description: "CUDA regression suite" + type: choice + options: [cuda-hashing, sgd-momentum] + default: cuda-hashing permissions: contents: read @@ -32,7 +44,7 @@ jobs: concurrency: group: modal-cuda-tests cancel-in-progress: false - # Only reviewed code on main should be able to use the Modal credentials. + # Run the trusted launcher from main; reviewed PR code is fetched only in Modal. if: github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main' runs-on: ubuntu-latest environment: modal-gpu-ci @@ -48,6 +60,9 @@ jobs: run: python -m pip install modal==1.6.4 - name: Run the CUDA correctness suite env: + PR_NUMBER: ${{ inputs.pr_number }} + HEAD_SHA: ${{ inputs.head_sha }} + CUDA_SUITE: ${{ inputs.cuda_suite }} MODAL_TOKEN_ID: ${{ secrets.MODAL_TOKEN_ID }} MODAL_TOKEN_SECRET: ${{ secrets.MODAL_TOKEN_SECRET }} run: | @@ -56,4 +71,4 @@ jobs: echo "::error::Modal token secrets are missing from the modal-gpu-ci environment" exit 1 fi - modal run ci/modal_gpu.py + modal run ci/modal_gpu.py --pr-number "${PR_NUMBER:-0}" --head-sha "$HEAD_SHA" --suite "$CUDA_SUITE" From 2ed2e835aa8fecd44c322f3f406ecdcf1575d0bf Mon Sep 17 00:00:00 2001 From: Yuxuan <31838999+Essoz@users.noreply.github.com> Date: Sun, 29 Nov 2026 03:54:22 -0800 Subject: [PATCH 12/12] Run reviewed PR code only inside Modal and add the SGD CUDA probe --- ci/modal_gpu.py | 110 ++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 106 insertions(+), 4 deletions(-) diff --git a/ci/modal_gpu.py b/ci/modal_gpu.py index 6b4a4db3..92ad0a04 100644 --- a/ci/modal_gpu.py +++ b/ci/modal_gpu.py @@ -1,6 +1,10 @@ """Run TrainCheck's CUDA correctness smoke tests on one Modal L4.""" +import os +import re +import subprocess import sys +import tempfile import tomllib import unittest from pathlib import Path @@ -16,9 +20,10 @@ image = ( # Numba compiles CUDA kernels at runtime and needs the toolkit's NVVM. modal.Image.from_registry("nvidia/cuda:12.8.1-devel-ubuntu22.04", add_python="3.12") + .apt_install("git") .env({"CUDA_HOME": "/usr/local/cuda"}) .pip_install("torch==2.7.1", index_url="https://download.pytorch.org/whl/cu128") - .pip_install(*dependencies, "numba==0.63.1") + .pip_install(*dependencies, "numba==0.63.1", "setuptools", "wheel") .workdir(REMOTE_ROOT) .add_local_dir(ROOT / "traincheck", f"{REMOTE_ROOT}/traincheck") .add_local_dir(ROOT / "tests", f"{REMOTE_ROOT}/tests") @@ -35,7 +40,9 @@ serialized=True, include_source=False, ) -def gpu_tests() -> None: +def gpu_tests( + pr_number: int = 0, head_sha: str = "", suite: str = "cuda-hashing" +) -> None: # Ship only the two mounted directories, not the CLI checkout or secrets. sys.path.insert(0, REMOTE_ROOT) @@ -51,6 +58,93 @@ def gpu_tests() -> None: f"Numba: {numba.__version__}", flush=True, ) + if pr_number: + if not re.fullmatch(r"[0-9a-f]{40}", head_sha): + raise ValueError("PR CUDA testing requires a full, reviewed commit SHA") + # Fetch and execute contributor code only inside the GPU container. + # No GitHub or Modal credentials are supplied to this function. + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + git = ["git", "-C", str(root)] + subprocess.run([*git, "init", "-q"], check=True) + subprocess.run( + [ + *git, + "fetch", + "--no-tags", + "--depth=1", + "https://github.com/OrderLab/TrainCheck.git", + f"refs/pull/{pr_number}/head", + ], + check=True, + timeout=90, + ) + fetched = subprocess.check_output( + [*git, "rev-parse", "FETCH_HEAD"], text=True + ).strip() + if fetched != head_sha: + raise RuntimeError( + f"PR #{pr_number} moved: expected {head_sha}, got {fetched}" + ) + print(f"Testing PR #{pr_number} at {head_sha}", flush=True) + subprocess.run( + [*git, "-c", "advice.detachedHead=false", "checkout", "--detach", head_sha], + check=True, + ) + env = {**os.environ, "PYTHONPATH": str(root)} + if suite == "sgd-momentum": + probe = root / "tests/fixtures/sgd_momentum_probe.py" + source = probe.read_text(encoding="utf-8") + old = ( + " optimizer = torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9)\n" + " inputs = torch.randn(8, 4)\n" + " targets = torch.randn(8, 1)" + ) + new = ( + ' model = model.to("cuda:0")\n' + ' inputs = torch.randn(8, 4, device="cuda:0")\n' + ' targets = torch.randn(8, 1, device="cuda:0")\n' + " assert inputs.is_cuda and targets.is_cuda\n" + " assert all(parameter.is_cuda for parameter in model.parameters())\n" + " optimizer = torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9)" + ) + buffer_line = ( + " buffers.append(None if buffer is None else hex_values(buffer))" + ) + if source.count(old) != 1 or source.count(buffer_line) != 1: + raise RuntimeError("SGD probe fixture changed; review its CUDA adaptation") + probe.write_text( + source.replace(old, new).replace( + buffer_line, " assert buffer is None or buffer.is_cuda\n" + buffer_line + ), + encoding="utf-8", + ) + subprocess.run( + [sys.executable, "-m", "pip", "install", "--no-deps", "--no-build-isolation", "-e", "."], + cwd=root, + env=env, + check=True, + timeout=90, + ) + tests = "tests.test_unproxy_list_writeback.CollectedTrainingMatchesPlainTraining" + else: + tests = "tests.test_cuda_hashing_contracts" + subprocess.run( + [ + sys.executable, + "-c", + "import sys, unittest; " + "suite = unittest.defaultTestLoader.loadTestsFromName(sys.argv[1]); " + "result = unittest.TextTestRunner(verbosity=2).run(suite); " + "sys.exit(not (result.testsRun and result.wasSuccessful() and not result.skipped))", + tests, + ], + cwd=root, + env=env, + check=True, + ) + return + # Import only after the CUDA check: the module can skip GPU tests on CPU. from tests import test_cuda_hashing_contracts @@ -70,5 +164,13 @@ def gpu_tests() -> None: @app.local_entrypoint() -def main() -> None: - gpu_tests.remote() +def main(pr_number: int = 0, head_sha: str = "", suite: str = "cuda-hashing") -> None: + if suite not in {"cuda-hashing", "sgd-momentum"}: + raise ValueError("Unknown CUDA suite") + if pr_number < 0 or bool(pr_number) != bool(head_sha): + raise ValueError("Provide both a positive PR number and its reviewed head SHA") + if head_sha and not re.fullmatch(r"[0-9a-f]{40}", head_sha): + raise ValueError("Use a full, lowercase Git commit SHA") + if not pr_number and suite != "cuda-hashing": + raise ValueError("The SGD momentum suite requires a PR with its probe fixture") + gpu_tests.remote(pr_number, head_sha, suite)