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 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 diff --git a/.github/workflows/modal-gpu-ci.yml b/.github/workflows/modal-gpu-ci.yml new file mode 100644 index 00000000..55dbc226 --- /dev/null +++ b/.github/workflows/modal-gpu-ci.yml @@ -0,0 +1,74 @@ +name: TrainCheck tests + +on: + pull_request: + 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 + +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 + # 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/ + + cuda-tests: + concurrency: + group: modal-cuda-tests + cancel-in-progress: false + # 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 + 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: + 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: | + 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 --pr-number "${PR_NUMBER:-0}" --head-sha "$HEAD_SHA" --suite "$CUDA_SUITE" 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 diff --git a/ci/modal_gpu.py b/ci/modal_gpu.py new file mode 100644 index 00000000..92ad0a04 --- /dev/null +++ b/ci/modal_gpu.py @@ -0,0 +1,176 @@ +"""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 + +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") + .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", "setuptools", "wheel") + .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( + 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) + + 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, + ) + 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 + + 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(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) 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 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) 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", 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)