diff --git a/.ci/scripts/tests/test_cortex_m_reporting.py b/.ci/scripts/tests/test_cortex_m_reporting.py index cbb911cdacb..5bb0af9019c 100644 --- a/.ci/scripts/tests/test_cortex_m_reporting.py +++ b/.ci/scripts/tests/test_cortex_m_reporting.py @@ -18,12 +18,10 @@ ROOT = Path(__file__).resolve().parents[3] CONFIG = "backends/arm/test/pytest.ini" SUITE = "backends/cortex_m/test" -HELPER = ".ci/scripts/torchci-report-args.sh" @unittest.skipUnless( - sys.platform == "linux" and shutil.which("bash"), - "Cortex-M reporting uses Linux Bash", + os.name == "posix" and shutil.which("bash"), "Cortex-M workflows use Bash" ) class CortexMReportingTest(unittest.TestCase): def test_workflows_keep_the_arm_config_and_repo_relative_test_ids(self): @@ -34,10 +32,19 @@ def test_workflows_keep_the_arm_config_and_repo_relative_test_ids(self): ) with tempfile.TemporaryDirectory() as directory: repo = Path(directory) - for name in (CONFIG, HELPER): + for name in (CONFIG, "tools/__init__.py", "tools/pytest_torchci.py"): target = repo / name target.parent.mkdir(parents=True, exist_ok=True) shutil.copyfile(ROOT / name, target) + torchci = repo / "torch/testing/_internal/torchci" + torchci.mkdir(parents=True) + (repo / "torch/__init__.py").touch() + (torchci / "report.py").write_text("SCHEMA_VERSION = '1.0'\n") + (torchci / "plugin.py").write_text( + "from pathlib import Path\n" + "def pytest_sessionstart(session):\n" + " Path(session.config.option.torchci_report_prefix).touch()\n" + ) # Widening confcutdir would also load ExecuTorch's root seed hook. (repo / "conftest.py").write_text( "raise RuntimeError('root hook loaded')\n" @@ -60,14 +67,17 @@ def test_workflows_keep_the_arm_config_and_repo_relative_test_ids(self): " assert target == os.environ['EXPECTED_TARGET']\n" ) env = dict( - os.environ, PYTEST_DISABLE_PLUGIN_AUTOLOAD="1", PYTHON=sys.executable + os.environ, + PATH=os.pathsep.join( + (str(Path(sys.executable).parent), os.environ["PATH"]) + ), + PYTEST_DISABLE_PLUGIN_AUTOLOAD="1", + PYTEST_ADDOPTS="-v", + RUNNER_TEST_RUN_REPORTS_DIR=str(repo), + JOB_ID="1", + GITHUB_REPOSITORY="pytorch/executorch", ) - for name in ( - "PYTEST_ADDOPTS", - "PYTEST_PLUGINS", - "RUNNER_TEST_RUN_REPORTS_DIR", - ): - env.pop(name, None) + env.pop("PYTEST_PLUGINS", None) for workflow, job, target in jobs: with self.subTest(target=target): path = ROOT / ".github/workflows" / workflow @@ -75,15 +85,12 @@ def test_workflows_keep_the_arm_config_and_repo_relative_test_ids(self): job ]["with"] self.assertIs(inputs["upload-test-run-reports"], True) - tail = inputs["script"].split(f"source {HELPER} ", 1)[1] - tail = tail.replace("${{ matrix.target }}", target) + script = inputs["script"] + command = script[script.index("TORCHCI_REPORT_NAME=") :].replace( + "${{ matrix.target }}", target + ) result = subprocess.run( - [ - "bash", - "-eu", - "-c", - f'pytest() {{ "$PYTHON" -m pytest -v "$@"; }}\nsource {HELPER} {tail}', - ], + ["bash", "-eu", "-c", command], cwd=repo, env=dict(env, EXPECTED_TARGET=target), capture_output=True, @@ -96,3 +103,9 @@ def test_workflows_keep_the_arm_config_and_repo_relative_test_ids(self): self.assertIn( f"{SUITE}/ops/test_smoke.py::test_target PASSED", result.stdout ) + prefix = ( + "cortex-m" + if workflow == "pull.yml" + else f"cortex-m-ops-{target}" + ) + self.assertTrue((repo / prefix).is_file(), result.stdout) diff --git a/.ci/scripts/tests/test_torchci_conftest.py b/.ci/scripts/tests/test_torchci_conftest.py index b45179c923b..c79d77ab402 100644 --- a/.ci/scripts/tests/test_torchci_conftest.py +++ b/.ci/scripts/tests/test_torchci_conftest.py @@ -76,6 +76,9 @@ def configure(env, config=None, **stubs): with contextlib.ExitStack() as stack: stack.enter_context(mock.patch.dict(sys.modules, stub_modules(**stubs))) stack.enter_context(mock.patch.dict(os.environ, env, clear=True)) + stack.enter_context(mock.patch.object(sys, "path", [str(ROOT), *sys.path])) + sys.modules.pop("tools", None) + sys.modules.pop("tools.pytest_torchci", None) spec.loader.exec_module(module) module.pytest_configure(config) return module, config diff --git a/.ci/scripts/tests/test_torchci_report_args.py b/.ci/scripts/tests/test_torchci_report_args.py deleted file mode 100644 index 9c874601324..00000000000 --- a/.ci/scripts/tests/test_torchci_report_args.py +++ /dev/null @@ -1,188 +0,0 @@ -# Copyright (c) Meta Platforms, Inc. and affiliates. -# All rights reserved. -# -# This source code is licensed under the BSD-style license found in the -# LICENSE file in the root directory of this source tree. - -import os -import shlex -import subprocess -import sys -import tempfile -import unittest -from pathlib import Path - - -ROOT = Path(__file__).resolve().parents[3] -HELPER = ROOT / ".ci/scripts/torchci-report-args.sh" -PROBE = """ -import os -import sys -from types import ModuleType, SimpleNamespace - -sys.modules['pytest'] = SimpleNamespace(__version__=os.environ['PROBE_PYTEST']) -for name in ('torch', 'torch.testing', 'torch.testing._internal', - 'torch.testing._internal.torchci'): - sys.modules[name] = ModuleType(name) -torchci = sys.modules['torch.testing._internal.torchci'] -def capture(): - os.environ['TORCHCI_POLLUTION'] = 'child-only' - if os.environ.get('PROBE_CAPTURE_ERROR'): - raise RuntimeError('capture failed') - print('CAPTURE') -torchci.environment = SimpleNamespace(capture=capture) -torchci.report = SimpleNamespace(SCHEMA_VERSION=os.environ['PROBE_SCHEMA']) -if not os.environ.get('PROBE_MISSING_PLUGIN'): - torchci.plugin = ModuleType('plugin') -exec(sys.argv[2]) -""" - - -class TorchciReportArgumentsTest(unittest.TestCase): - ARGS_THEN_TESTS = ( - "printf 'ARG <%s>\\n' " - '${TORCHCI_REPORT_ARGS[@]+"${TORCHCI_REPORT_ARGS[@]}"}; ' - "echo TESTS_STARTED" - ) - - def run_helper(self, extra=None, command=None): - with tempfile.TemporaryDirectory(dir=ROOT, prefix="torchci-test-") as tmp: - probe = Path(tmp) / "probe.py" - probe.write_text(PROBE) - env = dict(os.environ) - for name in ( - "RUNNER_TEST_RUN_REPORTS_DIR", - "JOB_ID", - "GITHUB_REPOSITORY", - "TORCHCI_PYTHON", - "PYTHON_EXECUTABLE", - "TORCHCI_POLLUTION", - "PYTHONOPTIMIZE", - ): - env.pop(name, None) - env.update( - PROBE_PYTEST="7.3.0", - PROBE_SCHEMA="1.0", - TORCHCI_PYTHON=f"{sys.executable} -B {probe}", - ) - env.update(extra or {}) - command = command or ( - "printf 'ARG <%s>\\n' " - '${TORCHCI_REPORT_ARGS[@]+"${TORCHCI_REPORT_ARGS[@]}"}; ' - 'printf "POLLUTION <%s>\\n" "${TORCHCI_POLLUTION:-}"' - ) - return subprocess.run( - [ - "bash", - "-c", - f"set -eu; source {shlex.quote(str(HELPER))} smoke; {command}", - ], - env=env, - capture_output=True, - text=True, - ) - - def opted_env(self, **extra): - return { - "RUNNER_TEST_RUN_REPORTS_DIR": "/tmp/torchci reports", - "JOB_ID": "51234567890", - "GITHUB_REPOSITORY": "pytorch/executorch", - **extra, - } - - def test_unopted_run_does_not_start_an_interpreter(self): - for directory in (None, ""): - with self.subTest(directory=directory): - extra = {"TORCHCI_PYTHON": "/missing/python"} - if directory is not None: - extra["RUNNER_TEST_RUN_REPORTS_DIR"] = directory - result = self.run_helper(extra) - self.assertEqual(result.returncode, 0, result.stderr) - self.assertNotIn("CAPTURE", result.stdout) - self.assertNotIn("torchci.plugin", result.stdout) - - def test_valid_preflight_preserves_argument_boundaries_and_parent_environment(self): - result = self.run_helper(self.opted_env()) - self.assertEqual(result.returncode, 0, result.stderr) - self.assertEqual( - result.stdout.splitlines(), - [ - "CAPTURE", - "ARG <-p>", - "ARG ", - "ARG <--torchci-report-prefix=/tmp/torchci reports/smoke>", - "POLLUTION <>", - ], - ) - - def assert_reporting_disabled(self, result, message): - self.assertEqual(result.returncode, 0, result.stderr) - self.assertIn(message, result.stderr) - self.assertIn("::warning::torchci: test-run reports disabled", result.stdout) - self.assertNotIn("torchci.plugin", result.stdout) - self.assertNotIn("--torchci-report-prefix", result.stdout) - self.assertIn("TESTS_STARTED", result.stdout) - - def test_invalid_preflight_disables_reporting_and_runs_the_tests(self): - cases = ( - ({"PROBE_PYTEST": "7.2.0"}, "pytest >= 7.3"), - ({"PROBE_SCHEMA": "2.0"}, "schema 1.0"), - ({"JOB_ID": ""}, "positive JOB_ID"), - ({"JOB_ID": "0"}, "positive JOB_ID"), - ({"JOB_ID": "-1"}, "positive JOB_ID"), - ({"JOB_ID": "abc"}, "positive JOB_ID"), - ({"GITHUB_REPOSITORY": ""}, "GITHUB_REPOSITORY"), - ({"PROBE_MISSING_PLUGIN": "1"}, "plugin"), - ({"PROBE_CAPTURE_ERROR": "1"}, "capture failed"), - ({"TORCHCI_PYTHON": "/missing/python"}, "/missing/python"), - ) - for extra, message in cases: - with self.subTest(extra=extra): - result = self.run_helper(self.opted_env(**extra), self.ARGS_THEN_TESTS) - self.assert_reporting_disabled(result, message) - - def test_python_optimization_cannot_bypass_preflight(self): - for extra, message in ( - ({"JOB_ID": "0"}, "positive JOB_ID"), - ({"PROBE_SCHEMA": "2.0"}, "schema 1.0"), - ): - with self.subTest(extra=extra): - result = self.run_helper( - self.opted_env(PYTHONOPTIMIZE="1", **extra), self.ARGS_THEN_TESTS - ) - self.assert_reporting_disabled(result, message) - - def test_linux_invocation_preserves_coverage_and_cpp_failure_order(self): - script = (ROOT / ".ci/scripts/unittest-linux-cmake.sh").read_text() - invocation = script.split("# Run pytest with coverage\n", 1)[1] - for status in (0, 1): - with self.subTest(status=status): - command = ( - "pytest() { printf 'PYTEST'; printf ' <%s>' \"$@\"; " - f"printf '\\n'; return {status}; }}; " - "test() { echo CPP; }; " - + invocation.replace("test/run_oss_cpp_tests.sh", "test") - ) - result = self.run_helper(self.opted_env(), command) - self.assertEqual(result.returncode, status, result.stderr) - self.assertIn( - "PYTEST <-n> <--cov=./> <--cov-report=xml> <-p> " - " " - "<--torchci-report-prefix=/tmp/torchci reports/smoke>", - result.stdout, - ) - self.assertEqual("CPP" in result.stdout, status == 0) - - def test_unopted_linux_invocation_has_no_reporting_arguments(self): - script = (ROOT / ".ci/scripts/unittest-linux-cmake.sh").read_text() - invocation = script.split("# Run pytest with coverage\n", 1)[1] - command = ( - 'pytest() { printf "ARG <%s>\\n" "$@"; }; ' - "test() { :; }; " + invocation.replace("test/run_oss_cpp_tests.sh", "test") - ) - result = self.run_helper({"TORCHCI_PYTHON": "/missing/python"}, command) - self.assertEqual(result.returncode, 0, result.stderr) - self.assertEqual( - result.stdout.splitlines(), - ["ARG <-n>", "ARG ", "ARG <--cov=./>", "ARG <--cov-report=xml>"], - ) diff --git a/.ci/scripts/torchci-report-args.sh b/.ci/scripts/torchci-report-args.sh deleted file mode 100644 index b0b0e1265c9..00000000000 --- a/.ci/scripts/torchci-report-args.sh +++ /dev/null @@ -1,38 +0,0 @@ -#!/usr/bin/env bash -# shellcheck disable=SC2034 -# Copyright (c) Meta Platforms, Inc. and affiliates. -# All rights reserved. -# -# This source code is licensed under the BSD-style license found in the -# LICENSE file in the root directory of this source tree. - -TORCHCI_REPORT_ARGS=() -if [[ -n "${RUNNER_TEST_RUN_REPORTS_DIR:-}" ]]; then - # Reporting is best-effort, as in PyTorch: a failed preflight warns and - # leaves the tests running without the plugin. - # The interpreter may include a launcher such as conda run. - # shellcheck disable=SC2086 - if ${TORCHCI_PYTHON:-${PYTHON_EXECUTABLE:-python}} -c ' -import os -import pytest -from torch.testing._internal.torchci import environment, plugin, report - -if report.SCHEMA_VERSION != "1.0": - raise RuntimeError("torchci requires report schema 1.0") -if tuple(map(int, pytest.__version__.split(".")[:2])) < (7, 3): - raise RuntimeError("torchci requires pytest >= 7.3") -job_id = os.environ.get("JOB_ID", "") -if not job_id.isdigit() or int(job_id) <= 0: - raise RuntimeError("torchci requires a positive JOB_ID") -if not os.environ.get("GITHUB_REPOSITORY"): - raise RuntimeError("torchci requires GITHUB_REPOSITORY") -environment.capture() -'; then - TORCHCI_REPORT_ARGS=( - -p torch.testing._internal.torchci.plugin - "--torchci-report-prefix=${RUNNER_TEST_RUN_REPORTS_DIR}/${1:-pytest}" - ) - else - echo "::warning::torchci: test-run reports disabled because the preflight failed; tests run without them" - fi -fi diff --git a/.ci/scripts/unittest-linux-cmake.sh b/.ci/scripts/unittest-linux-cmake.sh index a927c5bd398..c2a9e888f7e 100755 --- a/.ci/scripts/unittest-linux-cmake.sh +++ b/.ci/scripts/unittest-linux-cmake.sh @@ -31,13 +31,10 @@ fi bash .ci/scripts/tests/vulkan/test_vulkan_cmake_package.sh -source .ci/scripts/torchci-report-args.sh unittest-linux-cmake - source .ci/scripts/setup-hf-cache.sh # Run pytest with coverage -pytest -n auto --cov=./ --cov-report=xml \ - ${TORCHCI_REPORT_ARGS[@]+"${TORCHCI_REPORT_ARGS[@]}"} +pytest -n auto --cov=./ --cov-report=xml # Run gtest LLVM_PROFDATA=llvm-profdata-12 LLVM_COV=llvm-cov-12 \ test/run_oss_cpp_tests.sh diff --git a/.github/workflows/_test_cortex_m_ops.yml b/.github/workflows/_test_cortex_m_ops.yml index a5eb2ed38d0..4f2f5f70524 100644 --- a/.github/workflows/_test_cortex_m_ops.yml +++ b/.github/workflows/_test_cortex_m_ops.yml @@ -60,8 +60,8 @@ jobs: # op set, implementation tests check FVP numerics. Both are parametrized # over --cortex-m-target, so a future target-dependent lowering change is # caught here. (cortex-m55 runs on pull via the full-suite job.) - source .ci/scripts/torchci-report-args.sh cortex-m-ops-${{ matrix.target }} - pytest ${TORCHCI_REPORT_ARGS[@]+"${TORCHCI_REPORT_ARGS[@]}"} --rootdir=. \ + TORCHCI_REPORT_NAME=cortex-m-ops-${{ matrix.target }} \ + python -m pytest -p tools.pytest_torchci --rootdir=. \ -c backends/arm/test/pytest.ini \ backends/cortex_m/test/ops \ --cortex-m-target=${{ matrix.target }} diff --git a/.github/workflows/pull.yml b/.github/workflows/pull.yml index 9a3c1a03c2e..a35ba394b49 100644 --- a/.github/workflows/pull.yml +++ b/.github/workflows/pull.yml @@ -907,8 +907,8 @@ jobs: backends/cortex_m/test/build_test_runner.sh # Use repo-relative report identities without loading the root seed hook. - source .ci/scripts/torchci-report-args.sh cortex-m - pytest ${TORCHCI_REPORT_ARGS[@]+"${TORCHCI_REPORT_ARGS[@]}"} --rootdir=. \ + TORCHCI_REPORT_NAME=cortex-m \ + python -m pytest -p tools.pytest_torchci --rootdir=. \ -c backends/arm/test/pytest.ini backends/cortex_m/test android: diff --git a/backends/cadence/generic/operators/tests/test_op_quantized_fully_connected.cpp b/backends/cadence/generic/operators/tests/test_op_quantized_fully_connected.cpp index d8fa550d8a4..9ffb88bdd4f 100644 --- a/backends/cadence/generic/operators/tests/test_op_quantized_fully_connected.cpp +++ b/backends/cadence/generic/operators/tests/test_op_quantized_fully_connected.cpp @@ -116,9 +116,8 @@ TEST_F( EXPECT_TENSOR_EQ(out_pc, out_pt); } -// The uint8 typed entry, on the first row of the linear test's input. -// Expected values are aot/ref_implementations.py's with the multiplier negated, -// for the reason test_op_quantized_linear.cpp gives. +// The uint8 typed entry, on the first row of the linear test's input, with +// the scale test_op_quantized_linear.cpp works out. TEST_F(GenericQuantizedFullyConnectedPerChannelTest, Asym8uPerTensor) { TensorFactory tf_uint8; TensorFactory tf_int32; diff --git a/backends/cadence/generic/operators/tests/test_op_quantized_linear.cpp b/backends/cadence/generic/operators/tests/test_op_quantized_linear.cpp index c264fe65c15..99e82f37ca2 100644 --- a/backends/cadence/generic/operators/tests/test_op_quantized_linear.cpp +++ b/backends/cadence/generic/operators/tests/test_op_quantized_linear.cpp @@ -143,9 +143,8 @@ TEST_F(GenericQuantizedLinearPerChannelTest, LengthOneMatchesPerTensor) { // The uint8 typed entry. The kernel computes -out_multiplier / (1 << 31), and // 1 << 31 is INT_MIN, so the scale is +out_multiplier / 2^31, as -// quantize_tensor_multiplier produces. aot/ref_implementations.py computes -// -out_multiplier / 2^31, so the expected values come from it with the -// multiplier negated: (src - 128) @ (weight - 128)^T + bias = +// quantize_tensor_multiplier produces and aot/ref_implementations.py +// computes: (src - 128) @ (weight - 128)^T + bias = // [[-3, 80], [-4, 0]], times 1/4, plus 100. TEST_F(GenericQuantizedLinearPerChannelTest, Asym8uPerTensor) { TensorFactory tf_uint8; diff --git a/backends/cadence/generic/operators/tests/test_op_quantized_matmul.cpp b/backends/cadence/generic/operators/tests/test_op_quantized_matmul.cpp index c9173c19ae1..f0fe4a8fbed 100644 --- a/backends/cadence/generic/operators/tests/test_op_quantized_matmul.cpp +++ b/backends/cadence/generic/operators/tests/test_op_quantized_matmul.cpp @@ -28,9 +28,8 @@ using ::executorch::runtime::testing::TensorFactory; // The kernel computes -out_multiplier / (1 << 31) * 2^out_shift, and 1 << 31 is // INT_MIN, so the scale is +out_multiplier / 2^31 * 2^out_shift, as -// quantize_tensor_multiplier produces: 1 << 29 is 1/4. -// aot/ref_implementations.py computes -out_multiplier / 2^31, so the expected -// values come from it with -(1 << 29). +// quantize_tensor_multiplier produces and aot/ref_implementations.py +// computes: 1 << 29 is 1/4. constexpr int64_t kQuarter = 1 << 29; class GenericQuantizedMatmulAsym8uTest : public OperatorTest { diff --git a/backends/cuda/tests/test_int4_quantized_gemm.py b/backends/cuda/tests/test_int4_quantized_gemm.py index 89ab1c62015..816cd719c08 100644 --- a/backends/cuda/tests/test_int4_quantized_gemm.py +++ b/backends/cuda/tests/test_int4_quantized_gemm.py @@ -20,6 +20,7 @@ import contextlib import os import pickle +import re import statistics import tempfile import types @@ -887,10 +888,10 @@ def linear(x): ) source = "\n".join(code) name = autotuner.fn.fn.__name__ - self.assertIn(f"def {name}(", source) - block = source[ - source.rindex("user_autotune(", 0, source.index(f"def {name}(")) : - ] + # A module-level kernel's def is renamed to Inductor's kernel name: name plus a suffix. + kernel_def = re.search(rf"^def {re.escape(name)}\w*\(", source, re.MULTILINE) + self.assertIsNotNone(kernel_def, source) + block = source[source.rindex("user_autotune(", 0, kernel_def.start()) :] configs = block[: block.index("],")] self.assertEqual(configs.count("'num_warps'"), 1) _check_close(self, compiled, eager) diff --git a/conftest.py b/conftest.py index aa34be5e254..37bf641ab9c 100644 --- a/conftest.py +++ b/conftest.py @@ -1,12 +1,11 @@ import hashlib -import importlib -import os import platform import sys -import pytest import torch +from tools.pytest_torchci import pytest_configure # noqa: F401 + collect_ignore_glob: list[str] = [] # Skip Apple tests on Windows. Note that some Core ML tests can run on Linux, as the AOT flow @@ -35,68 +34,6 @@ ] -_TORCHCI_PLUGIN = "torch.testing._internal.torchci.plugin" - - -def _torchci_preflight(env): - """Why PyTorch's test-run reporter cannot run in this CI job, or None. - - linux_job_v3 sets RUNNER_TEST_RUN_REPORTS_DIR only for jobs that opt in. - """ - try: - importlib.import_module(_TORCHCI_PLUGIN) - report = importlib.import_module("torch.testing._internal.torchci.report") - if report.SCHEMA_VERSION != "1.0": - raise RuntimeError("requires report schema 1.0") - if tuple(map(int, pytest.__version__.split(".")[:2])) < (7, 3): - raise RuntimeError("requires pytest >= 7.3") - job_id = env.get("JOB_ID", "") - if not job_id.isdigit() or int(job_id) <= 0: - raise RuntimeError("requires a positive JOB_ID") - if not env.get("GITHUB_REPOSITORY"): - raise RuntimeError("requires GITHUB_REPOSITORY") - except Exception as error: - return error - return None - - -def _torchci_warn(config, error): - line = f"::warning::torchci: test-run reports disabled: {error}" - try: - reporter = config.pluginmanager.get_plugin("terminalreporter") - if reporter is not None: - reporter.write_line(line) - return - except Exception: - pass # Fall back to stdout below; a warning must not fail the run. - print(line) - - -# trylast: pytest's terminal reporter registers in its own pytest_configure. -@pytest.hookimpl(trylast=True) -def pytest_configure(config): - # Registered here rather than with pytest_plugins, which pytest rejects in a - # conftest.py it loads after startup. Reporting is best-effort, as in - # PyTorch: any failure only disables the report and never fails the tests. - env = os.environ - if not env.get("RUNNER_TEST_RUN_REPORTS_DIR"): - return - error = _torchci_preflight(env) - try: - if error is None: - if not config.getoption("torchci_report_prefix", None): - config.option.torchci_report_prefix = os.path.join( - env["RUNNER_TEST_RUN_REPORTS_DIR"], - env.get("TORCHCI_REPORT_NAME", "pytest"), - ) - config.pluginmanager.import_plugin(_TORCHCI_PLUGIN) - elif not env.get("PYTEST_XDIST_WORKER"): - _torchci_warn(config, error) - except Exception as e: - if not env.get("PYTEST_XDIST_WORKER"): - _torchci_warn(config, e) - - def pytest_runtest_setup(item): # Set a stable seed for each test based on a hash of the test name. seed = int(hashlib.sha256(item.nodeid.encode()).hexdigest(), 16) % (2**32) diff --git a/shim_et/xplat/executorch/extension/pybindings/pybindings.bzl b/shim_et/xplat/executorch/extension/pybindings/pybindings.bzl index a4850133539..4d9a66f3a7c 100644 --- a/shim_et/xplat/executorch/extension/pybindings/pybindings.bzl +++ b/shim_et/xplat/executorch/extension/pybindings/pybindings.bzl @@ -67,6 +67,7 @@ def executorch_pybindings( srcs = [ "//executorch/extension/pybindings:pybindings.cpp", ] + srcs, + header_namespace = "executorch/extension/pybindings", headers = [ "//executorch/extension/pybindings:pybindings_cuda.h", "//executorch/extension/pybindings:pybindings_dlpack.h", diff --git a/tools/pytest_torchci.py b/tools/pytest_torchci.py new file mode 100644 index 00000000000..0df591c2402 --- /dev/null +++ b/tools/pytest_torchci.py @@ -0,0 +1,74 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +"""Configure HUD test-run reporting for opted-in CI jobs.""" + +import importlib +import os + +import pytest + + +_TORCHCI_PLUGIN = "torch.testing._internal.torchci.plugin" + + +def _torchci_preflight(env): + """Why PyTorch's test-run reporter cannot run in this CI job, or None. + + linux_job_v3 sets RUNNER_TEST_RUN_REPORTS_DIR only for jobs that opt in. + """ + try: + importlib.import_module(_TORCHCI_PLUGIN) + report = importlib.import_module("torch.testing._internal.torchci.report") + if report.SCHEMA_VERSION != "1.0": + raise RuntimeError("requires report schema 1.0") + if tuple(map(int, pytest.__version__.split(".")[:2])) < (7, 3): + raise RuntimeError("requires pytest >= 7.3") + job_id = env.get("JOB_ID", "") + if not job_id.isdigit() or int(job_id) <= 0: + raise RuntimeError("requires a positive JOB_ID") + if not env.get("GITHUB_REPOSITORY"): + raise RuntimeError("requires GITHUB_REPOSITORY") + except Exception as error: + return error + return None + + +def _torchci_warn(config, error): + line = f"::warning::torchci: test-run reports disabled: {error}" + try: + reporter = config.pluginmanager.get_plugin("terminalreporter") + if reporter is not None: + reporter.write_line(line) + return + except Exception: + pass # Fall back to stdout below; a warning must not fail the run. + print(line) + + +# trylast: pytest's terminal reporter registers in its own pytest_configure. +@pytest.hookimpl(trylast=True) +def pytest_configure(config): + # Registered here rather than with pytest_plugins, which pytest rejects in a + # conftest.py it loads after startup. Reporting is best-effort, as in + # PyTorch: any failure only disables the report and never fails the tests. + env = os.environ + if not env.get("RUNNER_TEST_RUN_REPORTS_DIR"): + return + error = _torchci_preflight(env) + try: + if error is None: + if not config.getoption("torchci_report_prefix", None): + config.option.torchci_report_prefix = os.path.join( + env["RUNNER_TEST_RUN_REPORTS_DIR"], + env.get("TORCHCI_REPORT_NAME", "pytest"), + ) + config.pluginmanager.import_plugin(_TORCHCI_PLUGIN) + elif not env.get("PYTEST_XDIST_WORKER"): + _torchci_warn(config, error) + except Exception as e: + if not env.get("PYTEST_XDIST_WORKER"): + _torchci_warn(config, e)