From f8dd36bc372312604b01576d57c7fcc32b1ad6cb Mon Sep 17 00:00:00 2001 From: Sameer Sheorey Date: Thu, 23 Jul 2026 06:52:36 +0200 Subject: [PATCH 01/14] WIP xpu vs cpu parity tests. --- ml3d/torch/models/pvcnn.py | 4 +- ml3d/torch/pipelines/base_pipeline.py | 14 +- ml3d/torch/pipelines/object_detection.py | 4 +- ml3d/torch/pipelines/semantic_segmentation.py | 4 +- ml3d/torch/utils/pointnet/pointnet2_utils.py | 28 ++-- ml3d/torch/utils/roipool3d/roipool3d_utils.py | 7 +- ml3d/utils/builder.py | 14 +- tests/test_models.py | 127 ++++++++++++++---- 8 files changed, 146 insertions(+), 56 deletions(-) diff --git a/ml3d/torch/models/pvcnn.py b/ml3d/torch/models/pvcnn.py index 13908bddd..ea47d4787 100644 --- a/ml3d/torch/models/pvcnn.py +++ b/ml3d/torch/models/pvcnn.py @@ -10,7 +10,9 @@ from ..modules.losses import filter_valid_label from ...datasets.augment import SemsegAugmentation -if open3d.core.cuda.device_count() > 0: +from ...utils.open3d_ops import pytorch_ops_built + +if pytorch_ops_built(): from open3d.ml.torch.ops import trilinear_devoxelize_forward, trilinear_devoxelize_backward diff --git a/ml3d/torch/pipelines/base_pipeline.py b/ml3d/torch/pipelines/base_pipeline.py index f466868b9..7aa52b9f2 100644 --- a/ml3d/torch/pipelines/base_pipeline.py +++ b/ml3d/torch/pipelines/base_pipeline.py @@ -57,7 +57,19 @@ def __init__(self, make_dir(self.cfg.main_log_dir) make_dir(self.cfg.logs_dir) - if device == 'cpu' or not torch.cuda.is_available(): + if device == 'cpu': + if distributed: + raise NotImplementedError( + "Distributed training for CPU is not supported yet.") + self.device = torch.device('cpu') + elif (device == 'xpu' or str(device).startswith('xpu')) and hasattr( + torch, 'xpu') and torch.xpu.is_available(): + if distributed: + raise NotImplementedError( + "Distributed training for XPU is not supported yet.") + self.device = torch.device( + device if ':' in str(device) else 'xpu') + elif not torch.cuda.is_available(): if distributed: raise NotImplementedError( "Distributed training for CPU is not supported yet.") diff --git a/ml3d/torch/pipelines/object_detection.py b/ml3d/torch/pipelines/object_detection.py index 892d86154..0e6f739d6 100644 --- a/ml3d/torch/pipelines/object_detection.py +++ b/ml3d/torch/pipelines/object_detection.py @@ -13,8 +13,7 @@ from .base_pipeline import BasePipeline from ..dataloaders import TorchDataloader, ConcatBatcher from torch.utils.tensorboard import SummaryWriter -# pylint: disable-next=unused-import -from open3d.visualization.tensorboard_plugin import summary +from ...utils.tensorboard_o3d import ensure_tensorboard_plugin from ..utils import latest_torch_ckpt from ...utils import make_dir, PIPELINE, get_runid, code2md from ...datasets.utils import BEVBox3D @@ -523,6 +522,7 @@ def save_logs(self, writer, epoch): for key, val in self.valid_losses.items(): writer.add_scalar("valid/" + key, np.mean(val), epoch) for stage in self.summary.keys(): + ensure_tensorboard_plugin() for key, summary_dict in self.summary[stage].items(): label_to_names = summary_dict.pop('label_to_names', None) writer.add_3d('/'.join((stage, key)), diff --git a/ml3d/torch/pipelines/semantic_segmentation.py b/ml3d/torch/pipelines/semantic_segmentation.py index bed7205b7..f44990e16 100644 --- a/ml3d/torch/pipelines/semantic_segmentation.py +++ b/ml3d/torch/pipelines/semantic_segmentation.py @@ -9,11 +9,10 @@ from torch.utils.tensorboard import SummaryWriter from torch.utils.data import DataLoader -# pylint: disable-next=unused-import -from open3d.visualization.tensorboard_plugin import summary from .base_pipeline import BasePipeline from ..dataloaders import get_sampler, TorchDataloader, DefaultBatcher, ConcatBatcher from ..utils import latest_torch_ckpt +from ...utils.tensorboard_o3d import ensure_tensorboard_plugin from ..modules.losses import SemSegLoss, filter_valid_label from ..modules.metrics import SemSegMetric from ...utils import make_dir, PIPELINE, get_runid, code2md @@ -654,6 +653,7 @@ def save_logs(self, writer, epoch): f" eval: {iou_dicts[-1]['Validation IoU']:.3f}") for stage in self.summary: + ensure_tensorboard_plugin() for key, summary_dict in self.summary[stage].items(): label_to_names = summary_dict.pop('label_to_names', None) writer.add_3d('/'.join((stage, key)), diff --git a/ml3d/torch/utils/pointnet/pointnet2_utils.py b/ml3d/torch/utils/pointnet/pointnet2_utils.py index 635c5783a..6b58474fa 100644 --- a/ml3d/torch/utils/pointnet/pointnet2_utils.py +++ b/ml3d/torch/utils/pointnet/pointnet2_utils.py @@ -30,9 +30,11 @@ import torch.nn as nn from typing import Tuple +from ....utils.open3d_ops import pytorch_ops_built, require_pytorch_ops + import open3d -if open3d.core.cuda.device_count() > 0: +if pytorch_ops_built(): from open3d.ml.torch.ops import furthest_point_sampling, three_nn, three_interpolate, three_interpolate_grad, ball_query @@ -48,8 +50,7 @@ def forward(ctx, xyz: torch.Tensor, npoint: int) -> torch.Tensor: :param npoint: int, number of features in the sampled set :return:tensor containing the set """ - if not open3d.core.cuda.device_count() > 0: - raise NotImplementedError + require_pytorch_ops() assert xyz.is_contiguous() output = furthest_point_sampling(xyz, npoint) @@ -79,8 +80,7 @@ def forward(ctx, xyz, row_splits, new_row_splits): Returns: Returns indices of sampled points with shape (new_row_splits[-1], ). """ - if not open3d.core.cuda.device_count() > 0: - raise NotImplementedError + require_pytorch_ops() if not xyz.is_contiguous(): raise ValueError( @@ -120,8 +120,7 @@ def forward(ctx, query_pts: torch.Tensor, dist: (B, N, 3) l2 distance to the three nearest neighbors idx: (B, N, 3) index of 3 nearest neighbors """ - if not open3d.core.cuda.device_count() > 0: - raise NotImplementedError + require_pytorch_ops() assert query_pts.is_contiguous() assert data_pts.is_contiguous() @@ -151,8 +150,7 @@ def forward(ctx, features: torch.Tensor, idx: torch.Tensor, :return: output: (B, C, N) tensor of the interpolated features """ - if not open3d.core.cuda.device_count() > 0: - raise NotImplementedError + require_pytorch_ops() assert features.is_contiguous() assert idx.is_contiguous() @@ -175,8 +173,7 @@ def backward( None: None: """ - if not open3d.core.cuda.device_count() > 0: - raise NotImplementedError + require_pytorch_ops() idx, weight, m = ctx.three_interpolate_for_backward @@ -203,8 +200,7 @@ def forward(ctx, radius: float, nsample: int, xyz: torch.Tensor, :return: idx: (B, npoint, nsample) tensor with the indices of the features that form the query balls """ - if not open3d.core.cuda.device_count() > 0: - raise NotImplementedError + require_pytorch_ops() assert new_xyz.is_contiguous() assert xyz.is_contiguous() @@ -244,8 +240,7 @@ def forward(self, :return: new_features: (B, 3 + C, npoint, nsample) """ - if not open3d.core.cuda.device_count() > 0: - raise NotImplementedError + require_pytorch_ops() batch_size = xyz.shape[0] @@ -296,8 +291,7 @@ def forward(self, :return: new_features: (B, C + 3, 1, N) """ - if not open3d.core.cuda.device_count() > 0: - raise NotImplementedError + require_pytorch_ops() grouped_xyz = xyz.transpose(1, 2).unsqueeze(2) if features is not None: diff --git a/ml3d/torch/utils/roipool3d/roipool3d_utils.py b/ml3d/torch/utils/roipool3d/roipool3d_utils.py index 1c4a165fe..50e921d61 100644 --- a/ml3d/torch/utils/roipool3d/roipool3d_utils.py +++ b/ml3d/torch/utils/roipool3d/roipool3d_utils.py @@ -1,6 +1,8 @@ import torch import open3d -if open3d.core.cuda.device_count() > 0: +from ....utils.open3d_ops import pytorch_ops_built, require_pytorch_ops + +if pytorch_ops_built(): from open3d.ml.torch.ops import roi_pool import numpy as np @@ -39,8 +41,7 @@ def roipool3d_gpu(pts, pooled_features: (B, M, 512, 3 + C) pooled_empty_flag: (B, M) """ - if not open3d.core.cuda.device_count() > 0: - raise NotImplementedError + require_pytorch_ops() batch_size = pts.shape[0] pooled_boxes3d = enlarge_box3d(boxes3d.view(-1, 7), diff --git a/ml3d/utils/builder.py b/ml3d/utils/builder.py index e5c68ef72..abce7d8dd 100644 --- a/ml3d/utils/builder.py +++ b/ml3d/utils/builder.py @@ -15,12 +15,13 @@ def build_network(cfg): def convert_device_name(device_type, device_ids): - """Convert device to either cpu or cuda.""" + """Convert device to cpu, cuda, or xpu.""" gpu_names = ["gpu", "cuda"] + xpu_names = ["xpu", "sycl"] cpu_names = ["cpu"] - if device_type not in cpu_names + gpu_names: - raise KeyError("the device should either " - "be cuda or cpu but got {}".format(device_type)) + if device_type not in cpu_names + gpu_names + xpu_names: + raise KeyError("the device should be cpu, cuda, or xpu but got " + "{}".format(device_type)) assert type(device_ids) is list device_ids_new = [] for device in device_ids: @@ -28,8 +29,9 @@ def convert_device_name(device_type, device_ids): if device_type in gpu_names: return "cuda", device_ids_new - else: - return "cpu", device_ids_new + if device_type in xpu_names: + return "xpu", device_ids_new + return "cpu", device_ids_new def convert_framework_name(framework): diff --git a/tests/test_models.py b/tests/test_models.py index 45dd8e171..fbab547ec 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -1,12 +1,18 @@ -import pytest +import copy import os + import numpy as np import open3d as o3d +import pytest + try: import torch except ImportError: torch = None +from torch_backend_parity import (assert_cpu_accelerator_parity, clone_module_to_device, + move_to_device, parity_accelerator) + if 'PATH_TO_OPEN3D_ML' in os.environ.keys(): base = os.environ['PATH_TO_OPEN3D_ML'] else: @@ -27,14 +33,25 @@ try: from open3d.ml.torch.models import OpenVINOModel openvino_available = True -except: +except Exception: openvino_available = False +# Looser tolerance on XPU; CUDA and CPU-only use defaults in helper calls. +def _parity_tolerance(): + accel = parity_accelerator() + if accel is not None and accel.type == "xpu": + return 1e-3, 1e-4 + return 1e-4, 1e-5 + + @pytest.mark.skipif("not o3d._build_config['BUILD_PYTORCH_OPS']") def test_randlanet_torch(): import open3d.ml.torch as ml3d + np.random.seed(11) + torch.manual_seed(11) + net = ml3d.models.RandLANet(num_points=5000, num_classes=10, in_channels=6) net.device = 'cpu' @@ -68,9 +85,33 @@ def test_randlanet_torch(): 'features': torch.from_numpy(np.array([inputs['features']])), 'labels': torch.from_numpy(np.array([inputs['labels']])) } - out = net(inputs).detach().numpy() - assert out.shape == (1, 5000, 10) + net.eval() + with torch.no_grad(): + out_cpu = net(inputs) + + assert out_cpu.detach().numpy().shape == (1, 5000, 10) + + state = copy.deepcopy(net.state_dict()) + + def forward_on_device(device): + model = ml3d.models.RandLANet(num_points=5000, + num_classes=10, + in_channels=6) + model.load_state_dict(state) + model.device = str(device) + model.to(device) + model.eval() + with torch.no_grad(): + return model(move_to_device(inputs, device)) + + rtol, atol = _parity_tolerance() + assert_cpu_accelerator_parity( + out_cpu, + forward_on_device, + rtol=rtol, + atol=atol, + ) @pytest.mark.skipif("not o3d._build_config['BUILD_TENSORFLOW_OPS']") @@ -118,6 +159,9 @@ def test_randlanet_tf(): def test_kpconv_torch(): import open3d.ml.torch as ml3d + np.random.seed(22) + torch.manual_seed(22) + net = ml3d.models.KPFCNN(lbl_values=[0, 1, 2, 3, 4, 5], num_classes=4, ignored_label_inds=[0], @@ -134,23 +178,37 @@ def test_kpconv_torch(): dtype=np.int32) } attr = {'split': 'train'} - batcher = ml3d.dataloaders.ConcatBatcher('cpu') data = net.preprocess(data, attr) - inputs = {'data': net.transform(data, attr), 'attr': attr} - inputs = batcher.collate_fn([inputs]) - - net.eval() - out = net(inputs['data']).detach().numpy() - - assert out.shape[1] == 5 + transform_data = net.transform(data, attr) + sample = {'data': transform_data, 'attr': attr} + + def run_forward(device): + batcher = ml3d.dataloaders.ConcatBatcher(str(device)) + model = clone_module_to_device(net, device) + batch = batcher.collate_fn([sample]) + with torch.no_grad(): + return model(batch['data']) + + out_cpu = run_forward('cpu') + assert out_cpu.detach().numpy().shape[1] == 5 + + rtol, atol = _parity_tolerance() + assert_cpu_accelerator_parity( + out_cpu, + lambda dev: run_forward(dev), + rtol=rtol, + atol=atol, + ) if openvino_available: + batcher = ml3d.dataloaders.ConcatBatcher('cpu') + inputs = batcher.collate_fn([sample]) ov_net = ml3d.models.OpenVINOModel(net) ov_net.to("cpu") ov_out = ov_net(inputs['data']).detach().numpy() - assert ov_out.shape == out.shape - assert np.max(np.abs(ov_out - out)) < 1e-7 + assert ov_out.shape == out_cpu.detach().numpy().shape + assert np.max(np.abs(ov_out - out_cpu.detach().numpy())) < 1e-7 @pytest.mark.skipif("not o3d._build_config['BUILD_TENSORFLOW_OPS']") @@ -206,12 +264,14 @@ def test_pointpillars_torch(): import open3d.ml.torch as ml3d from open3d.ml.utils import Config + np.random.seed(33) + torch.manual_seed(33) + cfg_path = base + '/ml3d/configs/pointpillars_kitti.yml' cfg = Config.load_from_file(cfg_path) net = ml3d.models.PointPillars(**cfg.model, device='cpu') - batcher = ml3d.dataloaders.ConcatBatcher('cpu', model='PointPillars') data = { 'point': np.array(np.random.random((10000, 4)), dtype=np.float32), 'calib': None, @@ -219,19 +279,38 @@ def test_pointpillars_torch(): } data = net.preprocess(data, {'split': 'test'}) data = net.transform(data, {'split': 'test'}) - data = batcher.collate_fn([{'data': data, 'attr': {'split': 'test'}}]) + sample = {'data': data, 'attr': {'split': 'test'}} + + def run_forward(device): + dev = device if isinstance(device, torch.device) else torch.device( + device) + batcher = ml3d.dataloaders.ConcatBatcher(str(dev), + model='PointPillars') + model = clone_module_to_device(net, dev) + batch = batcher.collate_fn([sample]) + if dev.type != 'cpu': + batch.to(dev) + with torch.no_grad(): + return model(batch), batch + + results_cpu, batch_cpu = run_forward('cpu') + boxes = net.inference_end(results_cpu, batch_cpu) + assert type(boxes) == list - net.eval() - with torch.no_grad(): - results = net(data) - boxes = net.inference_end(results, data) - assert type(boxes) == list + rtol, atol = _parity_tolerance() + assert_cpu_accelerator_parity( + results_cpu, + lambda dev: run_forward(dev)[0], + rtol=rtol, + atol=atol, + ) if openvino_available: + batcher = ml3d.dataloaders.ConcatBatcher('cpu', model='PointPillars') + batch = batcher.collate_fn([sample]) ov_net = ml3d.models.OpenVINOModel(net) - ov_results = ov_net(data) - - for out, ref in zip(ov_results, results): + ov_results = ov_net(batch) + for out, ref in zip(ov_results, results_cpu): assert out.shape == ref.shape assert torch.max(torch.abs(out - ref)) < 1e-5 From db4f5a7031f2bdae16a3861b6e39cfce6b1b0c35 Mon Sep 17 00:00:00 2001 From: Sameer Sheorey Date: Fri, 24 Jul 2026 20:26:21 +0200 Subject: [PATCH 02/14] remaining code --- ml3d/utils/open3d_ops.py | 15 ++++++ ml3d/utils/tensorboard_o3d.py | 15 ++++++ tests/torch_backend_parity.py | 97 +++++++++++++++++++++++++++++++++++ 3 files changed, 127 insertions(+) create mode 100644 ml3d/utils/open3d_ops.py create mode 100644 ml3d/utils/tensorboard_o3d.py create mode 100644 tests/torch_backend_parity.py diff --git a/ml3d/utils/open3d_ops.py b/ml3d/utils/open3d_ops.py new file mode 100644 index 000000000..c40f983c6 --- /dev/null +++ b/ml3d/utils/open3d_ops.py @@ -0,0 +1,15 @@ +"""Helpers for Open3D ML PyTorch custom ops (CPU, CUDA, and SYCL/XPU).""" + +import open3d + + +def pytorch_ops_built(): + """Return True if this Open3D build includes PyTorch custom ops.""" + return bool(open3d._build_config.get("BUILD_PYTORCH_OPS")) + + +def require_pytorch_ops(): + """Raise NotImplementedError when PyTorch ops were not built.""" + if not pytorch_ops_built(): + raise NotImplementedError( + "Open3D was built without PyTorch ops (BUILD_PYTORCH_OPS=OFF).") diff --git a/ml3d/utils/tensorboard_o3d.py b/ml3d/utils/tensorboard_o3d.py new file mode 100644 index 000000000..8d4e069c1 --- /dev/null +++ b/ml3d/utils/tensorboard_o3d.py @@ -0,0 +1,15 @@ +"""Register Open3D TensorBoard helpers when the GUI build is available.""" + + +def ensure_tensorboard_plugin(): + """Import the Open3D TensorBoard plugin (registers SummaryWriter.add_3d). + + Headless Open3D builds (BUILD_GUI=OFF) omit Filament rendering; skip import + so ML pipelines and tests can run without visualization support. + """ + import open3d as o3d + + if not o3d._build_config.get("BUILD_GUI"): + return False + from open3d.visualization.tensorboard_plugin import summary # noqa: F401 + return True diff --git a/tests/torch_backend_parity.py b/tests/torch_backend_parity.py new file mode 100644 index 000000000..e27c6a55c --- /dev/null +++ b/tests/torch_backend_parity.py @@ -0,0 +1,97 @@ +"""CPU vs CUDA / XPU parity helpers for Open3D-ML PyTorch model tests.""" + +import copy + +import numpy as np +import open3d as o3d +import pytest +import torch + + +def parity_accelerator(): + """Torch device for accelerator parity, or None if only CPU applies.""" + cfg = o3d._build_config + if cfg.get("BUILD_CUDA_MODULE") and torch.cuda.is_available(): + cuda_version = cfg.get("CUDA_VERSION") + if cuda_version and torch.version.cuda == cuda_version: + return torch.device("cuda") + if (cfg.get("BUILD_SYCL_MODULE") and hasattr(torch, "xpu") and + torch.xpu.is_available()): + return torch.device("xpu") + return None + + +def move_to_device(obj, device): + """Recursively move tensors in nested batch structures to ``device``.""" + if torch.is_tensor(obj): + return obj.to(device) + if isinstance(obj, dict): + return {key: move_to_device(val, device) for key, val in obj.items()} + if isinstance(obj, list): + return [move_to_device(val, device) for val in obj] + if isinstance(obj, tuple): + return tuple(move_to_device(val, device) for val in obj) + return obj + + +def _compare_tensors(ref, actual, rtol, atol, path): + ref_np = ref.detach().cpu().numpy() if torch.is_tensor(ref) else ref + act_np = actual.detach().cpu().numpy() if torch.is_tensor(actual) else actual + if ref_np.shape != act_np.shape: + pytest.fail(f"Shape mismatch at {path}: {ref_np.shape} vs {act_np.shape}") + if not np.all(np.isfinite(ref_np)) or not np.all(np.isfinite(act_np)): + pytest.fail(f"Non-finite values at {path}") + np.testing.assert_allclose(ref_np, act_np, rtol=rtol, atol=atol, + err_msg=f"CPU vs accelerator mismatch at {path}") + + +def assert_outputs_allclose(ref, actual, rtol=1e-4, atol=1e-5, path="root"): + """Compare nested model outputs (tensors, lists, tuples, dicts).""" + if torch.is_tensor(ref) or isinstance(ref, np.ndarray): + _compare_tensors(ref, actual, rtol, atol, path) + return + if isinstance(ref, dict): + if ref.keys() != actual.keys(): + pytest.fail(f"Dict keys differ at {path}: {ref.keys()} vs {actual.keys()}") + for key in ref: + assert_outputs_allclose(ref[key], actual[key], rtol, atol, + f"{path}.{key}") + return + if isinstance(ref, (list, tuple)): + if len(ref) != len(actual): + pytest.fail( + f"Length mismatch at {path}: {len(ref)} vs {len(actual)}") + for idx, (r, a) in enumerate(zip(ref, actual)): + assert_outputs_allclose(r, a, rtol, atol, f"{path}[{idx}]") + return + if ref == actual: + return + pytest.fail(f"Unsupported or unequal values at {path}: {type(ref)}") + + +def assert_cpu_accelerator_parity(cpu_output, + forward_on_device, + rtol=1e-4, + atol=1e-5): + """Compare in-process CPU forward with ``forward_on_device(accel_device)``. + + Uses the same loaded ``open3d_torch_ops.so``; CPU and accelerator paths + dispatch inside the op library. + """ + accel = parity_accelerator() + if accel is None: + return + + accel_output = forward_on_device(accel) + assert_outputs_allclose(cpu_output, accel_output, rtol=rtol, atol=atol) + + +def clone_module_to_device(module, device): + """Copy ``module`` weights onto ``device`` for a second forward pass.""" + clone = copy.deepcopy(module) + dev = device if isinstance(device, torch.device) else torch.device(device) + clone.to(dev) + if hasattr(clone, "device"): + clone.device = str(dev) + clone.eval() + return clone From 43737c99d8d31febf184218efbc024cddd424f19 Mon Sep 17 00:00:00 2001 From: Sameer Sheorey Date: Wed, 29 Jul 2026 15:19:55 -0700 Subject: [PATCH 03/14] point transformer cuda -> xpu update CI to use prebuilt wheel cpu parity tests (simplified) --- .github/workflows/ubuntu.yml | 31 +- ci/run_ci.sh | 87 ++--- ml3d/torch/models/point_transformer.py | 5 +- tests/run_tests.sh | 34 ++ tests/test_models.py | 336 ---------------- tests/test_models_tf.py | 140 +++++++ tests/test_models_torch.py | 514 +++++++++++++++++++++++++ tests/torch_backend_parity.py | 120 +++--- 8 files changed, 779 insertions(+), 488 deletions(-) create mode 100755 tests/run_tests.sh delete mode 100644 tests/test_models.py create mode 100644 tests/test_models_tf.py create mode 100644 tests/test_models_torch.py diff --git a/.github/workflows/ubuntu.yml b/.github/workflows/ubuntu.yml index d09e9e827..7e823cf89 100644 --- a/.github/workflows/ubuntu.yml +++ b/.github/workflows/ubuntu.yml @@ -12,9 +12,6 @@ concurrency: group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} cancel-in-progress: true -env: - NPROC: 3 - jobs: ubuntu: permissions: @@ -25,31 +22,11 @@ jobs: steps: - name: Checkout source code uses: actions/checkout@v4 - - name: Setup cache - uses: actions/cache@v3 - with: - # Ref: https://github.com/apache/incubator-mxnet/pull/18459/files - path: ~/.ccache - # We include the commit sha in the cache key, as new cache entries are - # only created if there is no existing entry for the key yet. - key: ${{ runner.os }}-ccache-${{ github.sha }} - # Restore any ccache cache entry, if none for - # ${{ runner.os }}-ccache-${{ github.sha }} exists. - # Common prefix will be used so that ccache can be used across commits. - restore-keys: | - ${{ runner.os }}-ccache - name: Set up Python version uses: actions/setup-python@v5 with: python-version: "3.12" - # Pre-installed packages: https://github.com/actions/runner-images/tree/main/images - - name: Install ccache - run: | - sudo apt-get --yes install ccache - ccache -M 2G # GitHub's total cache limit is 5GB for all OSes. - - name: Config and build - run: | - PATH=/usr/lib/ccache:$PATH - ccache -s - ./ci/run_ci.sh - ccache -s + - name: Run Open3D-ML tests against the prebuilt open3d_xpu wheel + env: + GH_TOKEN: ${{ github.token }} + run: ./ci/run_ci.sh diff --git a/ci/run_ci.sh b/ci/run_ci.sh index efc33cc00..b499b7ca0 100755 --- a/ci/run_ci.sh +++ b/ci/run_ci.sh @@ -2,65 +2,54 @@ set -euo pipefail -NPROC=${NPROC:?'env var must be set to number of available CPUs.'} PIP_VER="24.3.1" +OPEN3D_REPO="isl-org/Open3D" +RELEASE_TAG="main-devel" +PY_TAG="cp312" -echo 1. Prepare the Open3D-ML repo and install dependencies +echo "1. Download the latest open3d_cpu devel wheel from ${OPEN3D_REPO}@${RELEASE_TAG}" echo -export PATH_TO_OPEN3D_ML="$PWD" -echo "$PATH_TO_OPEN3D_ML" -# the build system of the main repo expects a main branch. make sure main exists -git checkout -b main || true -python -m pip install -U pip==$PIP_VER -python -m pip install -r requirements.txt \ - -r requirements-torch.txt \ - -r requirements-tensorflow.txt -# -r requirements-openvino.txt # Numpy version conflict with TF 2.8.2 -cd .. -python -m pip install -U Cython - -echo 2. clone Open3D and install dependencies +gh release download "${RELEASE_TAG}" \ + --repo "${OPEN3D_REPO}" \ + --pattern "open3d_cpu-*-${PY_TAG}-${PY_TAG}-manylinux*_x86_64.whl" \ + --dir . \ + --clobber +WHEEL_PATH="$(ls open3d_cpu-*-"${PY_TAG}"-*.whl)" +echo "Downloaded: ${WHEEL_PATH}" + +echo "2. Install the wheel in a fresh virtual environment" echo -git clone --branch main --depth 1 https://github.com/isl-org/Open3D.git - -./Open3D/util/install_deps_ubuntu.sh assume-yes -python -m pip install -r Open3D/python/requirements.txt \ - -r Open3D/python/requirements_style.txt \ - -r Open3D/python/requirements_test.txt +python -m venv open3d_test.venv +# shellcheck disable=SC1091 +source open3d_test.venv/bin/activate +python -m pip install -U pip=="${PIP_VER}" +python -m pip install "${WHEEL_PATH}" -echo 3. Configure for bundling the Open3D-ML part +echo "3. Sanity-check the installed package" echo -mkdir Open3D/build -pushd Open3D/build -cmake -DBUNDLE_OPEN3D_ML=ON \ - -DOPEN3D_ML_ROOT="${PATH_TO_OPEN3D_ML}" \ - -DBUILD_TENSORFLOW_OPS=ON \ - -DBUILD_PYTORCH_OPS=ON \ - -DBUILD_GUI=ON \ - -DBUILD_UNIT_TESTS=OFF \ - -DBUILD_BENCHMARKS=OFF \ - -DBUILD_EXAMPLES=OFF \ - .. - -echo 4. Build and install wheel +python -W default -c " +import open3d +print('Installed:', open3d) +print('BUILD_PYTORCH_OPS:', open3d._build_config['BUILD_PYTORCH_OPS']) +print('BUILD_SYCL_MODULE:', open3d._build_config['BUILD_SYCL_MODULE']) +" + +echo "4. Install Open3D-ML's own dependencies (torch flavor + base requirements)" echo -make -j"$NPROC" install-pip-package +export PATH_TO_OPEN3D_ML="$PWD" +python -m pip install -r requirements.txt -r requirements-torch.txt \ + -r requirements-tensorflow.txt -echo 5. run examples/tests in the Open3D-ML repo outside of the repo directory to -echo make sure that the installed package works. +echo "5. Run the Open3D-ML pytest suite against the installed wheel" echo -popd -mkdir test_workdir -pushd test_workdir -mv "$PATH_TO_OPEN3D_ML/tests" . -echo Add --randomly-seed=SEED to the test command to reproduce test order. -python -m pytest tests +echo "Add --randomly-seed=SEED to the test command to reproduce test order." +./tests/run_tests.sh -echo "... now do the same but in dev mode by setting OPEN3D_ML_ROOT" +echo "6. Also verify the OPEN3D_ML_ROOT dev-mode path (bundled models loaded from the" +echo " Open3D-ML checkout instead of whatever the wheel itself bundled)" echo -export OPEN3D_ML_ROOT="$PATH_TO_OPEN3D_ML" -echo Add --randomly-seed=SEED to the test command to reproduce test order. -python -m pytest tests +export OPEN3D_ML_ROOT="${PATH_TO_OPEN3D_ML}" +./tests/run_tests.sh unset OPEN3D_ML_ROOT -popd +deactivate diff --git a/ml3d/torch/models/point_transformer.py b/ml3d/torch/models/point_transformer.py index a28293e19..328b359f7 100644 --- a/ml3d/torch/models/point_transformer.py +++ b/ml3d/torch/models/point_transformer.py @@ -717,6 +717,7 @@ def knn_batch(points, if points_row_splits.shape[0] != queries_row_splits.shape[0]: raise ValueError("KNN(points and queries must have same batch size)") + device = points.device points = points.cpu() queries = queries.cpu() @@ -729,9 +730,9 @@ def knn_batch(points, return_distances=True) if return_distances: return ans.neighbors_index.reshape( - -1, k).long().cuda(), ans.neighbors_distance.reshape(-1, k).cuda() + -1, k).long().cuda(), ans.neighbors_distance.reshape(-1, k).to(device) else: - return ans.neighbors_index.reshape(-1, k).long().cuda() + return ans.neighbors_index.reshape(-1, k).long().to(device) def interpolation(points, diff --git a/tests/run_tests.sh b/tests/run_tests.sh new file mode 100755 index 000000000..059b40b49 --- /dev/null +++ b/tests/run_tests.sh @@ -0,0 +1,34 @@ +#!/usr/bin/env bash +# Run each test in its own pytest process. +# +# Torch XPU / SYCL state left behind by one model test can deadlock the next when +# they share an interpreter, so tests are not run in a single process. Extra +# arguments select tests, e.g. ./tests/run_tests.sh tests/test_models_torch.py -k +# "not sparse". +set -uo pipefail + +TIMEOUT=${TIMEOUT:-120} +cd "$(dirname "$0")/.." +targets=("${@:-tests}") + +mapfile -t test_ids < <(python -m pytest --collect-only -q "${targets[@]}" | + grep '::') +if [ ${#test_ids[@]} -eq 0 ]; then + echo "No tests collected for: ${targets[*]}" >&2 + exit 1 +fi + +failed=() +for test_id in "${test_ids[@]}"; do + timeout "$TIMEOUT" python -m pytest "$test_id" + # Exit code 1 is a test failure, 124 a timeout, 134 an abort during shutdown. + status=$? + [ $status -eq 0 ] || failed+=("$test_id (exit $status)") +done + +echo +echo "Ran ${#test_ids[@]} tests, ${#failed[@]} failed." +for test_id in "${failed[@]}"; do + echo "FAILED $test_id" +done +[ ${#failed[@]} -eq 0 ] diff --git a/tests/test_models.py b/tests/test_models.py deleted file mode 100644 index fbab547ec..000000000 --- a/tests/test_models.py +++ /dev/null @@ -1,336 +0,0 @@ -import copy -import os - -import numpy as np -import open3d as o3d -import pytest - -try: - import torch -except ImportError: - torch = None - -from torch_backend_parity import (assert_cpu_accelerator_parity, clone_module_to_device, - move_to_device, parity_accelerator) - -if 'PATH_TO_OPEN3D_ML' in os.environ.keys(): - base = os.environ['PATH_TO_OPEN3D_ML'] -else: - base = '.' - -try: - import tensorflow as tf - gpus = tf.config.list_physical_devices('GPU') - if gpus: - # Use first GPU and restrict memory growth. - tf.config.experimental.set_visible_devices(gpus[0], 'GPU') - tf.config.set_memory_growth(gpus[0], True) -except RuntimeError as e: - print(e) -except ImportError: - tf = None - -try: - from open3d.ml.torch.models import OpenVINOModel - openvino_available = True -except Exception: - openvino_available = False - - -# Looser tolerance on XPU; CUDA and CPU-only use defaults in helper calls. -def _parity_tolerance(): - accel = parity_accelerator() - if accel is not None and accel.type == "xpu": - return 1e-3, 1e-4 - return 1e-4, 1e-5 - - -@pytest.mark.skipif("not o3d._build_config['BUILD_PYTORCH_OPS']") -def test_randlanet_torch(): - import open3d.ml.torch as ml3d - - np.random.seed(11) - torch.manual_seed(11) - - net = ml3d.models.RandLANet(num_points=5000, num_classes=10, in_channels=6) - net.device = 'cpu' - - data = { - 'point': - np.array(np.random.random((1000, 3)), dtype=np.float32), - 'feat': - np.array(np.random.random((1000, 3)), dtype=np.float32), - 'label': - np.array([np.random.randint(10) for i in range(1000)], - dtype=np.int32) - } - attr = {'split': 'train'} - - data = net.preprocess(data, attr) - inputs = net.transform(data, attr) - inputs = { - 'coords': [ - torch.from_numpy(np.array([item])) for item in inputs['coords'] - ], - 'neighbor_indices': [ - torch.from_numpy(np.array([item])) - for item in inputs['neighbor_indices'] - ], - 'sub_idx': [ - torch.from_numpy(np.array([item])) for item in inputs['sub_idx'] - ], - 'interp_idx': [ - torch.from_numpy(np.array([item])) for item in inputs['interp_idx'] - ], - 'features': torch.from_numpy(np.array([inputs['features']])), - 'labels': torch.from_numpy(np.array([inputs['labels']])) - } - - net.eval() - with torch.no_grad(): - out_cpu = net(inputs) - - assert out_cpu.detach().numpy().shape == (1, 5000, 10) - - state = copy.deepcopy(net.state_dict()) - - def forward_on_device(device): - model = ml3d.models.RandLANet(num_points=5000, - num_classes=10, - in_channels=6) - model.load_state_dict(state) - model.device = str(device) - model.to(device) - model.eval() - with torch.no_grad(): - return model(move_to_device(inputs, device)) - - rtol, atol = _parity_tolerance() - assert_cpu_accelerator_parity( - out_cpu, - forward_on_device, - rtol=rtol, - atol=atol, - ) - - -@pytest.mark.skipif("not o3d._build_config['BUILD_TENSORFLOW_OPS']") -def test_randlanet_tf(): - import open3d.ml.tf as ml3d - - net = ml3d.models.RandLANet(num_points=5000, - num_classes=10, - dim_input=6, - num_layers=4) - - data = { - 'point': - np.array(np.random.random((1000, 3)), dtype=np.float32), - 'feat': - np.array(np.random.random((1000, 3)), dtype=np.float32), - 'label': - np.array([np.random.randint(10) for i in range(1000)], - dtype=np.int32) - } - attr = {'split': 'train'} - - data = net.preprocess(data, attr) - pc, feat, label, _ = ml3d.datasets.utils.trans_crop_pc( - data['point'], data['feat'], data['label'], data['search_tree'], 0, - 5000) - - inputs = net.transform(tf.convert_to_tensor(pc), tf.convert_to_tensor(feat), - tf.convert_to_tensor(label)) - for i in range(18): # num_layers * 4 + 2 - inputs[i] = tf.expand_dims(inputs[i], 0) - - out = net(inputs, training=False).numpy() - - assert out.shape == (1, 5000, 10) - - if openvino_available: - ov_net = ml3d.models.OpenVINOModel(net) - ov_out = ov_net(inputs) - assert ov_out.shape == out.shape - assert np.max(np.abs(ov_out - out)) < 1e-6 - - -@pytest.mark.skipif("not o3d._build_config['BUILD_PYTORCH_OPS']") -def test_kpconv_torch(): - import open3d.ml.torch as ml3d - - np.random.seed(22) - torch.manual_seed(22) - - net = ml3d.models.KPFCNN(lbl_values=[0, 1, 2, 3, 4, 5], - num_classes=4, - ignored_label_inds=[0], - in_features_dim=5) - net.device = 'cpu' - - data = { - 'point': - np.array(np.random.random((1000, 3)), dtype=np.float32), - 'feat': - np.array(np.random.random((1000, 3)), dtype=np.float32), - 'label': - np.array([np.random.randint(5) for i in range(1000)], - dtype=np.int32) - } - attr = {'split': 'train'} - - data = net.preprocess(data, attr) - transform_data = net.transform(data, attr) - sample = {'data': transform_data, 'attr': attr} - - def run_forward(device): - batcher = ml3d.dataloaders.ConcatBatcher(str(device)) - model = clone_module_to_device(net, device) - batch = batcher.collate_fn([sample]) - with torch.no_grad(): - return model(batch['data']) - - out_cpu = run_forward('cpu') - assert out_cpu.detach().numpy().shape[1] == 5 - - rtol, atol = _parity_tolerance() - assert_cpu_accelerator_parity( - out_cpu, - lambda dev: run_forward(dev), - rtol=rtol, - atol=atol, - ) - - if openvino_available: - batcher = ml3d.dataloaders.ConcatBatcher('cpu') - inputs = batcher.collate_fn([sample]) - ov_net = ml3d.models.OpenVINOModel(net) - ov_net.to("cpu") - ov_out = ov_net(inputs['data']).detach().numpy() - assert ov_out.shape == out_cpu.detach().numpy().shape - assert np.max(np.abs(ov_out - out_cpu.detach().numpy())) < 1e-7 - - -@pytest.mark.skipif("not o3d._build_config['BUILD_TENSORFLOW_OPS']") -def test_kpconv_tf(): - import open3d.ml.tf as ml3d - - np.random.seed(32) - - net = ml3d.models.KPFCNN(lbl_values=[0, 1, 2, 3, 4, 5], - num_classes=4, - ignored_label_inds=[0], - in_features_dim=5) - - data = { - 'point': - np.array(np.random.random((10000, 3)), dtype=np.float32), - 'feat': - np.array(np.random.random((10000, 3)), dtype=np.float32), - 'label': - np.array([np.random.randint(5) for i in range(10000)], - dtype=np.int32) - } - attr = {'split': 'train'} - - data = net.preprocess(data, attr) - p_list = tf.convert_to_tensor(data['point'][:1000]) - c_list = tf.convert_to_tensor( - np.concatenate([data['point'][:1000], data['feat'][:1000]], axis=1)) - pl_list = tf.convert_to_tensor(data['label'][:1000]) - - pi_list = tf.convert_to_tensor( - np.array([i for i in range(1000)], dtype=np.int32)) - ci_list = tf.convert_to_tensor(np.array([0], dtype=np.int32)) - - inputs = net.transform( - p_list, c_list, pl_list, - tf.convert_to_tensor(np.array([500, 500], dtype=np.int32)), pi_list, - ci_list) - - out = net(inputs) - - assert out.shape == (1000, 5) - - if openvino_available: - ov_net = ml3d.models.OpenVINOModel(net) - ov_out = ov_net(inputs) - assert ov_out.shape == out.shape - assert np.max(np.abs(ov_out - out)) < 1e-5 - - -@pytest.mark.skipif("not o3d._build_config['BUILD_PYTORCH_OPS']") -def test_pointpillars_torch(): - import open3d.ml.torch as ml3d - from open3d.ml.utils import Config - - np.random.seed(33) - torch.manual_seed(33) - - cfg_path = base + '/ml3d/configs/pointpillars_kitti.yml' - cfg = Config.load_from_file(cfg_path) - - net = ml3d.models.PointPillars(**cfg.model, device='cpu') - - data = { - 'point': np.array(np.random.random((10000, 4)), dtype=np.float32), - 'calib': None, - 'bounding_boxes': [], - } - data = net.preprocess(data, {'split': 'test'}) - data = net.transform(data, {'split': 'test'}) - sample = {'data': data, 'attr': {'split': 'test'}} - - def run_forward(device): - dev = device if isinstance(device, torch.device) else torch.device( - device) - batcher = ml3d.dataloaders.ConcatBatcher(str(dev), - model='PointPillars') - model = clone_module_to_device(net, dev) - batch = batcher.collate_fn([sample]) - if dev.type != 'cpu': - batch.to(dev) - with torch.no_grad(): - return model(batch), batch - - results_cpu, batch_cpu = run_forward('cpu') - boxes = net.inference_end(results_cpu, batch_cpu) - assert type(boxes) == list - - rtol, atol = _parity_tolerance() - assert_cpu_accelerator_parity( - results_cpu, - lambda dev: run_forward(dev)[0], - rtol=rtol, - atol=atol, - ) - - if openvino_available: - batcher = ml3d.dataloaders.ConcatBatcher('cpu', model='PointPillars') - batch = batcher.collate_fn([sample]) - ov_net = ml3d.models.OpenVINOModel(net) - ov_results = ov_net(batch) - for out, ref in zip(ov_results, results_cpu): - assert out.shape == ref.shape - assert torch.max(torch.abs(out - ref)) < 1e-5 - - -@pytest.mark.skipif("not o3d._build_config['BUILD_TENSORFLOW_OPS']") -def test_pointpillars_tf(): - import open3d.ml.tf as ml3d - from open3d.ml.utils import Config - - cfg_path = base + '/ml3d/configs/pointpillars_kitti.yml' - cfg = Config.load_from_file(cfg_path) - - net = ml3d.models.PointPillars(**cfg.model, device='cpu') - - data = [ - tf.constant(np.random.random((10000, 4)), dtype=tf.float32), None, None, - [tf.constant(np.stack([np.eye(4), np.eye(4)], axis=0))] - ] - - results = net(data, training=False) - boxes = net.inference_end(results, data) - - assert type(boxes) == list diff --git a/tests/test_models_tf.py b/tests/test_models_tf.py new file mode 100644 index 000000000..4eeede463 --- /dev/null +++ b/tests/test_models_tf.py @@ -0,0 +1,140 @@ +import os + +import numpy as np +import open3d as o3d +import pytest + +if 'PATH_TO_OPEN3D_ML' in os.environ.keys(): + base = os.environ['PATH_TO_OPEN3D_ML'] +elif 'OPEN3D_ML_ROOT' in os.environ.keys(): + base = os.environ['OPEN3D_ML_ROOT'] +else: + base = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) + +try: + import tensorflow as tf + gpus = tf.config.list_physical_devices('GPU') + if gpus: + # Use first GPU and restrict memory growth. + tf.config.experimental.set_visible_devices(gpus[0], 'GPU') + tf.config.set_memory_growth(gpus[0], True) +except RuntimeError as e: + print(e) +except ImportError: + tf = None + +try: + from open3d.ml.torch.models import OpenVINOModel + openvino_available = True +except Exception: + openvino_available = False + + +@pytest.mark.skipif("not o3d._build_config['BUILD_TENSORFLOW_OPS']") +def test_randlanet_tf(): + import open3d.ml.tf as ml3d + + net = ml3d.models.RandLANet(num_points=5000, + num_classes=10, + dim_input=6, + num_layers=4) + + data = { + 'point': + np.array(np.random.random((1000, 3)), dtype=np.float32), + 'feat': + np.array(np.random.random((1000, 3)), dtype=np.float32), + 'label': + np.array([np.random.randint(10) for i in range(1000)], + dtype=np.int32) + } + attr = {'split': 'train'} + + data = net.preprocess(data, attr) + pc, feat, label, _ = ml3d.datasets.utils.trans_crop_pc( + data['point'], data['feat'], data['label'], data['search_tree'], 0, + 5000) + + inputs = net.transform(tf.convert_to_tensor(pc), tf.convert_to_tensor(feat), + tf.convert_to_tensor(label)) + for i in range(18): # num_layers * 4 + 2 + inputs[i] = tf.expand_dims(inputs[i], 0) + + out = net(inputs, training=False).numpy() + + assert out.shape == (1, 5000, 10) + + if openvino_available: + ov_net = ml3d.models.OpenVINOModel(net) + ov_out = ov_net(inputs) + assert ov_out.shape == out.shape + assert np.max(np.abs(ov_out - out)) < 1e-6 + + +@pytest.mark.skipif("not o3d._build_config['BUILD_TENSORFLOW_OPS']") +def test_kpconv_tf(): + import open3d.ml.tf as ml3d + + np.random.seed(32) + + net = ml3d.models.KPFCNN(lbl_values=[0, 1, 2, 3, 4, 5], + num_classes=4, + ignored_label_inds=[0], + in_features_dim=5) + + data = { + 'point': + np.array(np.random.random((10000, 3)), dtype=np.float32), + 'feat': + np.array(np.random.random((10000, 3)), dtype=np.float32), + 'label': + np.array([np.random.randint(5) for i in range(10000)], + dtype=np.int32) + } + attr = {'split': 'train'} + + data = net.preprocess(data, attr) + p_list = tf.convert_to_tensor(data['point'][:1000]) + c_list = tf.convert_to_tensor( + np.concatenate([data['point'][:1000], data['feat'][:1000]], axis=1)) + pl_list = tf.convert_to_tensor(data['label'][:1000]) + + pi_list = tf.convert_to_tensor( + np.array([i for i in range(1000)], dtype=np.int32)) + ci_list = tf.convert_to_tensor(np.array([0], dtype=np.int32)) + + inputs = net.transform( + p_list, c_list, pl_list, + tf.convert_to_tensor(np.array([500, 500], dtype=np.int32)), pi_list, + ci_list) + + out = net(inputs) + + assert out.shape == (1000, 5) + + if openvino_available: + ov_net = ml3d.models.OpenVINOModel(net) + ov_out = ov_net(inputs) + assert ov_out.shape == out.shape + assert np.max(np.abs(ov_out - out)) < 1e-5 + + +@pytest.mark.skipif("not o3d._build_config['BUILD_TENSORFLOW_OPS']") +def test_pointpillars_tf(): + import open3d.ml.tf as ml3d + from open3d.ml.utils import Config + + cfg_path = os.path.join(base, 'ml3d', 'configs', 'pointpillars_kitti.yml') + cfg = Config.load_from_file(cfg_path) + + net = ml3d.models.PointPillars(**cfg.model, device='cpu') + + data = [ + tf.constant(np.random.random((10000, 4)), dtype=tf.float32), None, None, + [tf.constant(np.stack([np.eye(4), np.eye(4)], axis=0))] + ] + + results = net(data, training=False) + boxes = net.inference_end(results, data) + + assert type(boxes) == list diff --git a/tests/test_models_torch.py b/tests/test_models_torch.py new file mode 100644 index 000000000..6055973aa --- /dev/null +++ b/tests/test_models_torch.py @@ -0,0 +1,514 @@ +"""PyTorch model tests. + +Each CPU+accelerator model test builds the same model and batch on each device, +runs one forward and one backward pass per device, and compares outputs and +gradients. Models whose ops have no CPU kernel run on the accelerator only. +""" + +import copy +import os +import sys +from types import SimpleNamespace + +import numpy as np +import open3d as o3d +import pytest +import torch + +from torch_backend_parity import (assert_cpu_accelerator_parity, + move_to_device) + +if 'PATH_TO_OPEN3D_ML' in os.environ.keys(): + base = os.environ['PATH_TO_OPEN3D_ML'] +elif 'OPEN3D_ML_ROOT' in os.environ.keys(): + base = os.environ['OPEN3D_ML_ROOT'] +else: + # tests/ lives at repo root; works regardless of pytest cwd. + base = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) + +try: + from open3d.ml.torch.models import OpenVINOModel + openvino_available = True +except Exception: + openvino_available = False + +_ACCEL_ONLY_REASON = ( + "Requires a CUDA or XPU device; no CPU kernel for one or more ops used by " + "this model (see test comment).") + +_accel = None +if o3d.core.cuda.is_available(): + _accel = torch.device('cuda') +elif o3d.core.sycl.is_available(): + _accel = torch.device('xpu') + +skip_no_pytorch_ops = pytest.mark.skipif( + "not o3d._build_config['BUILD_PYTORCH_OPS']") +skip_no_accelerator = pytest.mark.skipif(_accel is None, + reason=_ACCEL_ONLY_REASON) + +# Model.get_loss() only reads Loss.weighted_CrossEntropyLoss. The real SemSegLoss +# derives class weights from a Dataset, which these synthetic samples do not have. +semseg_loss = SimpleNamespace( + weighted_CrossEntropyLoss=torch.nn.CrossEntropyLoss()) + + +def _bev_box3d(): + """BEVBox3D lives in Open3D-ML (ml3d), not in open3d.ml.datasets.""" + ml_root = (os.environ.get('OPEN3D_ML_ROOT') + or os.environ.get('PATH_TO_OPEN3D_ML') or base) + if ml_root not in sys.path: + sys.path.insert(0, ml_root) + from ml3d.datasets.utils import BEVBox3D + return BEVBox3D + + +def _to_tensor(x): + if torch.is_tensor(x): + return x + return torch.from_numpy(x) + + +def _pointrcnn_ctor_kwargs(mode): + """Small synthetic PointRCNN config for fast accelerator-only tests.""" + npoints = 1024 + rpn_backbone = dict( + in_channels=0, + SA_config=dict( + npoints=[256, 64, 16, 4], + radius=[[0.1, 0.5], [0.5, 1.0], [1.0, 2.0], [2.0, 4.0]], + nsample=[[4, 8], [4, 8], [4, 8], [4, 8]], + mlps=[[[8, 8, 16], [16, 16, 32]], + [[32, 32, 64], [32, 48, 64]], + [[64, 98, 128], [64, 98, 128]], + [[128, 128, 256], [128, 192, 256]]], + ), + fp_mlps=[[64, 64], [128, 128], [256, 256], [256, 256]], + ) + rpn_cfg = dict(backbone=rpn_backbone, cls_in_ch=64, reg_in_ch=64) + rcnn_cfg = dict( + SA_config=dict(npoints=[16, 4, -1], + radius=[0.2, 0.4, 100], + nsample=[8, 8, 8], + mlps=[[64, 64, 64], [64, 64, 128], [128, 128, 256]]), + target_head=dict(num_points=32), + in_channels=64, + xyz_up_layer=[64, 64], + ) + return dict(classes=['Car'], + npoints=npoints, + mode=mode, + augment={}, + rpn=rpn_cfg, + rcnn=rcnn_cfg) + + +def _pointrcnn_synthetic_sample(seed=44): + BEVBox3D = _bev_box3d() + rng = np.random.RandomState(seed) + n = 1200 + points = rng.uniform(-5, 5, size=(n, 4)).astype(np.float32) + points[:, 3] = 1.0 + calib = {'world_cam': np.eye(4, dtype=np.float32)} + box = BEVBox3D(center=[0, 0, 3], + size=[1.6, 1.5, 3.9], + yaw=0.0, + label_class='Car', + confidence=-1.0, + world_cam=calib['world_cam']) + data = { + 'point': points, + 'calib': calib, + 'bounding_boxes': [box], + } + attr = {'split': 'train'} + return data, attr + + +@skip_no_pytorch_ops +def test_randlanet_torch(): + import open3d.ml.torch as ml3d + + np.random.seed(11) + torch.manual_seed(11) + + def make_net(device=torch.device('cpu')): + net = ml3d.models.RandLANet(num_points=5000, + num_classes=10, + in_channels=6, + ignored_label_inds=[]) + net.device = str(device) + net.eval() + return net.to(device) + + net = make_net() + state = copy.deepcopy(net.state_dict()) + + data = { + 'point': np.random.random((1000, 3)).astype(np.float32), + 'feat': np.random.random((1000, 3)).astype(np.float32), + 'label': np.random.randint(10, size=(1000,)).astype(np.int32), + } + attr = {'split': 'train'} + transformed = net.transform(net.preprocess(data, attr), attr) + inputs = { + 'coords': [ + torch.from_numpy(np.array([item])) for item in transformed['coords'] + ], + 'neighbor_indices': [ + torch.from_numpy(np.array([item])) + for item in transformed['neighbor_indices'] + ], + 'sub_idx': [ + torch.from_numpy(np.array([item])) + for item in transformed['sub_idx'] + ], + 'interp_idx': [ + torch.from_numpy(np.array([item])) + for item in transformed['interp_idx'] + ], + 'features': torch.from_numpy(np.array([transformed['features']])), + 'labels': torch.from_numpy(np.array([transformed['labels']])), + } + + def run(device): + model = make_net(device) + model.load_state_dict(state) + dev_inputs = move_to_device(inputs, device) + out = model(dev_inputs) + loss, _, _ = model.get_loss(semseg_loss, out, {'data': dev_inputs}, + device) + loss.backward() + return out, model + + out_cpu, _ = assert_cpu_accelerator_parity(run) + assert out_cpu.detach().numpy().shape == (1, 5000, 10) + + +@skip_no_pytorch_ops +def test_kpconv_torch(): + import open3d.ml.torch as ml3d + + np.random.seed(22) + torch.manual_seed(22) + + def make_net(device=torch.device('cpu')): + net = ml3d.models.KPFCNN(lbl_values=[0, 1, 2, 3, 4, 5], + num_classes=5, + ignored_label_inds=[0], + in_features_dim=5) + net.device = str(device) + net.eval() + return net.to(device) + + net = make_net() + state = copy.deepcopy(net.state_dict()) + + data = { + 'point': np.random.random((1000, 3)).astype(np.float32), + 'feat': np.random.random((1000, 3)).astype(np.float32), + 'label': np.random.randint(5, size=(1000,)).astype(np.int32), + } + attr = {'split': 'train'} + sample = { + 'data': net.transform(net.preprocess(data, attr), attr), + 'attr': attr + } + + def run(device): + model = make_net(device) + model.load_state_dict(state) + batcher = ml3d.dataloaders.ConcatBatcher(str(device)) + batch = batcher.collate_fn([sample]) + out = model(batch['data']) + loss, _, _ = model.get_loss(semseg_loss, out, batch, device) + loss.backward() + return out, model + + # Deformable kernel point offsets amplify per-parameter gradient differences. + out_cpu, _ = assert_cpu_accelerator_parity(run, grad_atol=2e-3) + assert out_cpu.detach().numpy().shape[1] == 5 + + if openvino_available: + batcher = ml3d.dataloaders.ConcatBatcher('cpu') + inputs = batcher.collate_fn([sample]) + ov_net = ml3d.models.OpenVINOModel(net) + ov_net.to("cpu") + ov_out = ov_net(inputs['data']).detach().numpy() + assert ov_out.shape == out_cpu.detach().numpy().shape + assert np.max(np.abs(ov_out - out_cpu.detach().numpy())) < 1e-7 + + +@skip_no_pytorch_ops +def test_pointpillars_torch(): + import open3d.ml.torch as ml3d + from open3d.ml.utils import Config + + BEVBox3D = _bev_box3d() + + np.random.seed(33) + torch.manual_seed(33) + + cfg_path = os.path.join(base, 'ml3d', 'configs', 'pointpillars_kitti.yml') + model_cfg = dict(Config.load_from_file(cfg_path).model) + model_cfg['augment'] = {} + + def make_net(device=torch.device('cpu')): + net = ml3d.models.PointPillars(**model_cfg, device=str(device)) + net.eval() + return net.to(device) + + net = make_net() + state = copy.deepcopy(net.state_dict()) + + box = BEVBox3D(center=[10, 0, -1], + size=[1.6, 3.9, 1.5], + yaw=0.0, + label_class='Car', + confidence=-1.0) + data = { + 'point': np.random.uniform(0, 20, size=(2000, 4)).astype(np.float32), + 'calib': None, + 'bounding_boxes': [box], + } + attr = {'split': 'train'} + sample = { + 'data': net.transform(net.preprocess(data, attr), attr), + 'attr': attr + } + batches = {} + + def run(device): + model = make_net(device) + model.load_state_dict(state) + batcher = ml3d.dataloaders.ConcatBatcher(str(device), + model='PointPillars') + batch = batcher.collate_fn([sample]) + batch.to(device) + batches[device.type] = batch + out = model(batch) + loss = sum(model.get_loss(out, batch).values()) + loss.backward() + return out, model + + out_cpu, net_cpu = assert_cpu_accelerator_parity(run) + assert isinstance(net_cpu.inference_end(out_cpu, batches['cpu']), list) + + if openvino_available: + batcher = ml3d.dataloaders.ConcatBatcher('cpu', model='PointPillars') + batch = batcher.collate_fn([sample]) + ov_net = ml3d.models.OpenVINOModel(net) + ov_results = ov_net(batch) + for out, ref in zip(ov_results, out_cpu): + assert out.shape == ref.shape + assert torch.max(torch.abs(out - ref)) < 1e-5 + + +@skip_no_pytorch_ops +def test_sparseconvunet_torch(): + import open3d.ml.torch as ml3d + + np.random.seed(88) + torch.manual_seed(88) + + def make_net(device=torch.device('cpu')): + net = ml3d.models.SparseConvUnet(device=str(device), + num_classes=20, + in_channels=3, + augment={}, + ignored_label_inds=[]) + net.eval() + return net.to(device) + + net = make_net() + state = copy.deepcopy(net.state_dict()) + + data = { + 'point': np.random.random((2000, 3)).astype(np.float32), + 'feat': np.random.random((2000, 3)).astype(np.float32), + 'label': np.random.randint(20, size=(2000,)).astype(np.int32), + } + attr = {'split': 'train'} + sample = { + 'data': net.transform(net.preprocess(data, attr), attr), + 'attr': attr + } + + def run(device): + model = make_net(device) + model.load_state_dict(state) + batcher = ml3d.dataloaders.ConcatBatcher(str(device), + model='SparseConvUnet') + batch = batcher.collate_fn([sample]) + batch['data'].to(device) + out = model(batch['data']) + loss, _, _ = model.get_loss(semseg_loss, out, batch, device) + loss.backward() + return out, model + + # Voxel hashing orders sparse conv accumulations differently per backend. + assert_cpu_accelerator_parity(run, atol=1e-2) + + +@skip_no_pytorch_ops +@skip_no_accelerator +def test_pointrcnn_rpn_torch(): + # NOTE: furthest_point_sampling (PointRCNN RPN Pointnet++ backbone) has no CPU + # kernel -- see cpp/open3d/ml/pytorch/pointnet/SamplingOps.cpp. Forward+backward + # runs on accelerator only; no CPU/XPU parity baseline exists. + import open3d.ml.torch as ml3d + + np.random.seed(44) + torch.manual_seed(44) + + net = ml3d.models.PointRCNN(device=str(_accel), + **_pointrcnn_ctor_kwargs('RPN')) + data, attr = _pointrcnn_synthetic_sample() + net.train() + data = net.preprocess(data, attr) + t_data = net.transform(data, attr) + sample = {'data': t_data, 'attr': attr} + batcher = ml3d.dataloaders.ConcatBatcher(str(_accel), model='PointRCNN') + batch = batcher.collate_fn([sample]) + batch.to(_accel) + + out = net(batch) + loss_dict = net.get_loss(out, batch) + total = sum(loss_dict.values()) + total.backward() + assert any(p.grad is not None for p in net.rpn.parameters()) + + +@skip_no_pytorch_ops +@skip_no_accelerator +def test_pointrcnn_rcnn_torch(): + # NOTE: same furthest_point_sampling / roipool3d CPU limitation as RPN test. + # RCNN.loss may assert on SYCL if cls_label contains -1 (ambiguous ROI); try two + # GT boxes to reduce ambiguous labels. + import open3d.ml.torch as ml3d + + BEVBox3D = _bev_box3d() + np.random.seed(45) + torch.manual_seed(45) + + net = ml3d.models.PointRCNN(device=str(_accel), + **_pointrcnn_ctor_kwargs('RCNN')) + data, attr = _pointrcnn_synthetic_sample(seed=45) + calib = data['calib'] + data['bounding_boxes'] = [ + BEVBox3D(center=[0, 0, 3], + size=[1.6, 1.5, 3.9], + yaw=0.0, + label_class='Car', + confidence=-1.0, + world_cam=calib['world_cam']), + BEVBox3D(center=[2, 1, 4], + size=[1.6, 1.5, 3.9], + yaw=0.5, + label_class='Car', + confidence=-1.0, + world_cam=calib['world_cam']), + ] + net.train() + data = net.preprocess(data, attr) + t_data = net.transform(data, attr) + sample = {'data': t_data, 'attr': attr} + batcher = ml3d.dataloaders.ConcatBatcher(str(_accel), model='PointRCNN') + batch = batcher.collate_fn([sample]) + batch.to(_accel) + + out = net(batch) + required = { + 'cls_label', 'reg_valid_mask', 'roi_boxes3d', 'gt_of_rois', 'pts_input' + } + assert required.issubset(out.keys()) + + loss_dict = net.get_loss(out, batch) + total = sum(loss_dict.values()) + total.backward() + assert any(p.grad is not None for p in net.parameters()) + + +@skip_no_pytorch_ops +@skip_no_accelerator +def test_pointtransformer_torch(): + # NOTE: furthest_point_sampling (encoder downsampling) has no CPU kernel, same as + # PointRCNN -- forward+backward on accelerator only; no CPU/XPU parity baseline. + import open3d.ml.torch as ml3d + + np.random.seed(66) + torch.manual_seed(66) + + net = ml3d.models.PointTransformer(device=str(_accel), + num_classes=13, + in_channels=6, + augment={}, + ignored_label_inds=[]) + net.to(_accel) + net.eval() + + n = 4096 + data = { + 'point': np.random.random((n, 3)).astype(np.float32), + 'feat': np.random.random((n, 3)).astype(np.float32), + 'label': np.random.randint(13, size=(n,)).astype(np.int32), + } + attr = {'split': 'train'} + data = net.preprocess(data, attr) + data = net.transform(data, attr) + sample = {'data': data, 'attr': attr} + batcher = ml3d.dataloaders.ConcatBatcher(str(_accel), + model='PointTransformer') + batch = batcher.collate_fn([sample]) + batch['data'].to(_accel) + out = net(batch['data']) + assert out.shape[1] == 13 + + loss, _, _ = net.get_loss(semseg_loss, out, batch, _accel) + loss.backward() + assert any(p.grad is not None for p in net.parameters()) + + +@skip_no_pytorch_ops +@skip_no_accelerator +def test_pvcnn_torch(): + # NOTE: trilinear_devoxelize has no CPU kernel (TrilinearDevoxelizeOps.cpp). + # Forward+backward on accelerator only; no CPU parity baseline. + import open3d.ml.torch as ml3d + + np.random.seed(77) + torch.manual_seed(77) + + net = ml3d.models.PVCNN(device=str(_accel), + num_classes=13, + num_points=256, + extra_feature_channels=6, + augment={}, + ignored_label_inds=[]) + net.to(_accel) + net.train() + + samples = [] + for seed in (771, 772): + np.random.seed(seed) + data = { + 'point': np.random.random((400, 3)).astype(np.float32), + 'feat': np.random.random((400, 3)).astype(np.float32) * 255.0, + 'label': np.random.randint(13, size=(400,)).astype(np.int32), + } + attr = {'split': 'train'} + data = net.preprocess(data, attr) + data = net.transform(data, attr) + samples.append(data) + + points = torch.stack([_to_tensor(s['point']) for s in samples]).to(_accel) + feats = torch.stack([_to_tensor(s['feat']) for s in samples]).to(_accel) + labels = torch.stack([_to_tensor(s['label']) for s in samples]).to(_accel) + inputs = {'point': points, 'feat': feats} + + out = net(inputs) + loss, _, _ = net.get_loss(semseg_loss, out, {'data': { + 'label': labels + }}, _accel) + loss.backward() + assert any(p.grad is not None for p in net.parameters()) diff --git a/tests/torch_backend_parity.py b/tests/torch_backend_parity.py index e27c6a55c..9c1da0e25 100644 --- a/tests/torch_backend_parity.py +++ b/tests/torch_backend_parity.py @@ -1,25 +1,11 @@ """CPU vs CUDA / XPU parity helpers for Open3D-ML PyTorch model tests.""" -import copy - -import numpy as np import open3d as o3d -import pytest import torch - -def parity_accelerator(): - """Torch device for accelerator parity, or None if only CPU applies.""" - cfg = o3d._build_config - if cfg.get("BUILD_CUDA_MODULE") and torch.cuda.is_available(): - cuda_version = cfg.get("CUDA_VERSION") - if cuda_version and torch.version.cuda == cuda_version: - return torch.device("cuda") - if (cfg.get("BUILD_SYCL_MODULE") and hasattr(torch, "xpu") and - torch.xpu.is_available()): - return torch.device("xpu") - return None - +# Tolerances for CPU vs accelerator comparisons, keyed by accelerator type. +RTOL = {"cuda": 1e-4, "xpu": 1e-3} +ATOL = {"cuda": 1e-5, "xpu": 1e-4} def move_to_device(obj, device): """Recursively move tensors in nested batch structures to ``device``.""" @@ -34,64 +20,50 @@ def move_to_device(obj, device): return obj -def _compare_tensors(ref, actual, rtol, atol, path): - ref_np = ref.detach().cpu().numpy() if torch.is_tensor(ref) else ref - act_np = actual.detach().cpu().numpy() if torch.is_tensor(actual) else actual - if ref_np.shape != act_np.shape: - pytest.fail(f"Shape mismatch at {path}: {ref_np.shape} vs {act_np.shape}") - if not np.all(np.isfinite(ref_np)) or not np.all(np.isfinite(act_np)): - pytest.fail(f"Non-finite values at {path}") - np.testing.assert_allclose(ref_np, act_np, rtol=rtol, atol=atol, - err_msg=f"CPU vs accelerator mismatch at {path}") - +def collect_grads(module): + """Return {param_name: grad} for the parameters that received a gradient.""" + return { + name: param.grad + for name, param in module.named_parameters() + if param.grad is not None + } -def assert_outputs_allclose(ref, actual, rtol=1e-4, atol=1e-5, path="root"): - """Compare nested model outputs (tensors, lists, tuples, dicts).""" - if torch.is_tensor(ref) or isinstance(ref, np.ndarray): - _compare_tensors(ref, actual, rtol, atol, path) - return - if isinstance(ref, dict): - if ref.keys() != actual.keys(): - pytest.fail(f"Dict keys differ at {path}: {ref.keys()} vs {actual.keys()}") - for key in ref: - assert_outputs_allclose(ref[key], actual[key], rtol, atol, - f"{path}.{key}") - return - if isinstance(ref, (list, tuple)): - if len(ref) != len(actual): - pytest.fail( - f"Length mismatch at {path}: {len(ref)} vs {len(actual)}") - for idx, (r, a) in enumerate(zip(ref, actual)): - assert_outputs_allclose(r, a, rtol, atol, f"{path}[{idx}]") - return - if ref == actual: - return - pytest.fail(f"Unsupported or unequal values at {path}: {type(ref)}") +def assert_cpu_accelerator_parity(run_on_device, atol=None, grad_atol=None): + """Run one forward + backward pass per device and compare outputs and grads. -def assert_cpu_accelerator_parity(cpu_output, - forward_on_device, - rtol=1e-4, - atol=1e-5): - """Compare in-process CPU forward with ``forward_on_device(accel_device)``. - - Uses the same loaded ``open3d_torch_ops.so``; CPU and accelerator paths - dispatch inside the op library. + ``run_on_device(device)`` builds the model and batch on ``device``, runs + forward and ``loss.backward()``, and returns ``(output, model)``. Returns the + CPU ``(output, model)``; the accelerator half is skipped if none is present. """ - accel = parity_accelerator() - if accel is None: - return - - accel_output = forward_on_device(accel) - assert_outputs_allclose(cpu_output, accel_output, rtol=rtol, atol=atol) - - -def clone_module_to_device(module, device): - """Copy ``module`` weights onto ``device`` for a second forward pass.""" - clone = copy.deepcopy(module) - dev = device if isinstance(device, torch.device) else torch.device(device) - clone.to(dev) - if hasattr(clone, "device"): - clone.device = str(dev) - clone.eval() - return clone + cpu_output, cpu_model = run_on_device(torch.device("cpu")) + + if o3d.core.cuda.is_available(): + accel = torch.device('cuda') + elif o3d.core.sycl.is_available(): + accel = torch.device('xpu') + else: + return cpu_output, cpu_model + + accel_output, accel_model = run_on_device(accel) + torch.accelerator.synchronize() + + rtol = RTOL[accel.type] + atol = ATOL[accel.type] if atol is None else atol + # assert_close walks tensors, dicts and sequences alike. The tensors being + # compared live on different devices, so only their values must match. + torch.testing.assert_close( + accel_output, + cpu_output, + rtol=rtol, + atol=atol, + check_device=False, + msg=lambda m: f"{accel.type} vs CPU output mismatch\n{m}") + torch.testing.assert_close( + collect_grads(accel_model), + collect_grads(cpu_model), + rtol=rtol, + atol=atol if grad_atol is None else grad_atol, + check_device=False, + msg=lambda m: f"{accel.type} vs CPU gradient mismatch\n{m}") + return cpu_output, cpu_model From 7b9999f61d824b1ed8555a51158fc5b275042b5f Mon Sep 17 00:00:00 2001 From: Sameer Sheorey Date: Sun, 2 Aug 2026 23:54:21 -0700 Subject: [PATCH 04/14] Bump torch to 2.13 --- requirements-torch-cuda.txt | 4 ++-- requirements-torch-xpu.txt | 4 ++++ requirements-torch.txt | 8 ++++---- 3 files changed, 10 insertions(+), 6 deletions(-) create mode 100644 requirements-torch-xpu.txt diff --git a/requirements-torch-cuda.txt b/requirements-torch-cuda.txt index 7f614707f..8026dff7a 100644 --- a/requirements-torch-cuda.txt +++ b/requirements-torch-cuda.txt @@ -1,5 +1,5 @@ -f https://download.pytorch.org/whl/torch/ -torch==2.10.0+cu126 +torch==2.13.0+cu126 -f https://download.pytorch.org/whl/torchvision/ -torchvision==0.25.0+cu126 +torchvision==0.28.0+cu126 tensorboard diff --git a/requirements-torch-xpu.txt b/requirements-torch-xpu.txt new file mode 100644 index 000000000..fed627879 --- /dev/null +++ b/requirements-torch-xpu.txt @@ -0,0 +1,4 @@ +--extra-index-url https://download.pytorch.org/whl/xpu/ +torch==2.13.0+xpu +torchvision==0.28.0+xpu +tensorboard diff --git a/requirements-torch.txt b/requirements-torch.txt index 97f036e52..8c5df5a1b 100644 --- a/requirements-torch.txt +++ b/requirements-torch.txt @@ -1,6 +1,6 @@ --extra-index-url https://download.pytorch.org/whl/cpu/ -torch==2.10.0+cpu ; sys_platform != 'darwin' -torchvision==0.25.0+cpu ; sys_platform != 'darwin' -torch==2.10.0 ; sys_platform == 'darwin' -torchvision==0.25.0 ; sys_platform == 'darwin' +torch==2.13.0+cpu ; sys_platform != 'darwin' +torchvision==0.28.0+cpu ; sys_platform != 'darwin' +torch==2.13.0 ; sys_platform == 'darwin' +torchvision==0.28.0 ; sys_platform == 'darwin' tensorboard From 7e962a1aef1c0c8b12082e3fdcc8d0d4635ceb2e Mon Sep 17 00:00:00 2001 From: Sameer Sheorey Date: Wed, 5 Aug 2026 13:39:28 -0700 Subject: [PATCH 05/14] Generalize PyTorch training for XPU and split CI by backend. Use accelerator-aware device defaults and .to() paths, configurable run_ci.sh (cpu/cuda/xpu), and GitHub Actions on cpu-only without parity tests. Document torch model test coverage and CPU/CUDA/XPU parity in howtos and tests. Co-authored-by: Cursor --- .github/workflows/ubuntu.yml | 4 +- README.md | 3 + ci/run_ci.sh | 126 ++++++++++++++++-- docs/howtos.md | 39 +++++- ml3d/metrics/__init__.py | 4 + ml3d/torch/dataloaders/concat_batcher.py | 2 +- ml3d/torch/models/base_model.py | 2 +- ml3d/torch/models/point_pillars.py | 6 +- ml3d/torch/models/point_rcnn.py | 11 +- ml3d/torch/models/point_transformer.py | 5 +- ml3d/torch/models/pvcnn.py | 7 +- ml3d/torch/models/randlanet.py | 2 +- ml3d/torch/models/sparseconvnet.py | 9 +- ml3d/torch/pipelines/base_pipeline.py | 16 ++- ml3d/torch/pipelines/object_detection.py | 8 +- ml3d/torch/pipelines/semantic_segmentation.py | 4 +- ml3d/torch/utils/objdet_helper.py | 7 +- ml3d/torch/utils/torch_utils.py | 10 ++ scripts/run_pipeline.py | 17 ++- tests/test_models_torch.py | 41 +++++- tests/torch_backend_parity.py | 7 +- torch-acc-plan.md | 99 ++++++++++++++ 22 files changed, 381 insertions(+), 48 deletions(-) create mode 100644 torch-acc-plan.md diff --git a/.github/workflows/ubuntu.yml b/.github/workflows/ubuntu.yml index 7e823cf89..335552cd1 100644 --- a/.github/workflows/ubuntu.yml +++ b/.github/workflows/ubuntu.yml @@ -26,7 +26,7 @@ jobs: uses: actions/setup-python@v5 with: python-version: "3.12" - - name: Run Open3D-ML tests against the prebuilt open3d_xpu wheel + - name: Run Open3D-ML tests (CPU wheel, no torch parity) env: GH_TOKEN: ${{ github.token }} - run: ./ci/run_ci.sh + run: ./ci/run_ci.sh cpu diff --git a/README.md b/README.md index f51811880..5f2401845 100644 --- a/README.md +++ b/README.md @@ -50,6 +50,8 @@ pip install -r requirements-tensorflow.txt pip install -r requirements-torch.txt # To install a compatible version of PyTorch with CUDA on Linux pip install -r requirements-torch-cuda.txt +# To install a compatible version of PyTorch with XPU (Intel GPU) on Linux +pip install -r requirements-torch-xpu.txt ``` To test the installation use @@ -420,6 +422,7 @@ For downloading these datasets visit the respective webpages and have a look at - [Adding a new model](docs/howtos.md#adding-a-new-model) - [Adding a new dataset](docs/howtos.md#adding-a-new-dataset) - [Distributed training](docs/howtos.md#distributed-training) +- [Testing CPU / CUDA / XPU parity](docs/howtos.md#testing-cpu--cuda--xpu-parity) - [Visualize and compare input data, ground truth and results in TensorBoard](docs/tensorboard.md) - [Inference with Intel OpenVINO](docs/openvino.md) diff --git a/ci/run_ci.sh b/ci/run_ci.sh index b499b7ca0..83a4bda3e 100755 --- a/ci/run_ci.sh +++ b/ci/run_ci.sh @@ -1,20 +1,84 @@ #!/usr/bin/env bash +# +# Install a prebuilt Open3D wheel + Open3D-ML deps, then run tests. +# +# Usage: ./ci/run_ci.sh [cpu|cuda|xpu] +# +# cpu — open3d_cpu wheel, PyTorch CPU; integration + TF tests only (no torch +# CPU/accelerator parity). Used on GitHub Actions. +# cuda — open3d (CUDA) wheel, PyTorch+cu126; full suite including +# tests/test_models_torch.py parity (requires NVIDIA GPU). +# xpu — open3d_xpu wheel, PyTorch+XPU; full suite including parity +# (requires Intel GPU; torch.xpu.is_available()). +# +# Parity tests (tests/test_models_torch.py) are intentionally omitted for the +# cpu variant: GitHub-hosted runners have no GPU, and parity needs a real +# accelerator. See docs/howtos.md. set -euo pipefail +usage() { + sed -n '2,16p' "$0" | sed 's/^# \?//' + echo + echo "Example: ./ci/run_ci.sh cpu" + exit "${1:-0}" +} + +BACKEND="${1:-cpu}" +case "${BACKEND}" in + cpu | cuda | xpu) ;; + -h | --help) usage 0 ;; + *) + echo "Unknown backend: ${BACKEND}" >&2 + usage 1 + ;; +esac + PIP_VER="24.3.1" OPEN3D_REPO="isl-org/Open3D" RELEASE_TAG="main-devel" PY_TAG="cp312" -echo "1. Download the latest open3d_cpu devel wheel from ${OPEN3D_REPO}@${RELEASE_TAG}" +case "${BACKEND}" in + cpu) + WHEEL_GLOB="open3d_cpu-*-${PY_TAG}-${PY_TAG}-manylinux*_x86_64.whl" + TORCH_REQUIREMENTS="requirements-torch.txt" + INCLUDE_PARITY_TESTS=false + ;; + cuda) + # Default manylinux wheel (not open3d_cpu / open3d_xpu). + WHEEL_GLOB="open3d-[0-9]*-${PY_TAG}-${PY_TAG}-manylinux*_x86_64.whl" + TORCH_REQUIREMENTS="requirements-torch-cuda.txt" + INCLUDE_PARITY_TESTS=true + ;; + xpu) + WHEEL_GLOB="open3d_xpu-*-${PY_TAG}-${PY_TAG}-manylinux*_x86_64.whl" + TORCH_REQUIREMENTS="requirements-torch-xpu.txt" + INCLUDE_PARITY_TESTS=true + ;; +esac + +echo "Open3D-ML CI backend: ${BACKEND}" +echo " wheel pattern: ${WHEEL_GLOB}" +echo " torch requirements: ${TORCH_REQUIREMENTS}" +echo " torch parity tests (test_models_torch.py): ${INCLUDE_PARITY_TESTS}" +echo + +echo "1. Download the latest Open3D devel wheel from ${OPEN3D_REPO}@${RELEASE_TAG}" echo gh release download "${RELEASE_TAG}" \ --repo "${OPEN3D_REPO}" \ - --pattern "open3d_cpu-*-${PY_TAG}-${PY_TAG}-manylinux*_x86_64.whl" \ + --pattern "${WHEEL_GLOB}" \ --dir . \ --clobber -WHEEL_PATH="$(ls open3d_cpu-*-"${PY_TAG}"-*.whl)" +shopt -s nullglob +wheel_matches=( ${WHEEL_GLOB} ) +shopt -u nullglob +if [ "${#wheel_matches[@]}" -ne 1 ]; then + echo "Expected exactly one wheel matching ${WHEEL_GLOB}, found ${#wheel_matches[@]}" >&2 + exit 1 +fi +WHEEL_PATH="${wheel_matches[0]}" echo "Downloaded: ${WHEEL_PATH}" echo "2. Install the wheel in a fresh virtual environment" @@ -31,25 +95,65 @@ python -W default -c " import open3d print('Installed:', open3d) print('BUILD_PYTORCH_OPS:', open3d._build_config['BUILD_PYTORCH_OPS']) -print('BUILD_SYCL_MODULE:', open3d._build_config['BUILD_SYCL_MODULE']) +print('BUILD_SYCL_MODULE:', open3d._build_config.get('BUILD_SYCL_MODULE')) +print('CUDA available:', open3d.core.cuda.is_available()) +print('SYCL available:', open3d.core.sycl.is_available()) " -echo "4. Install Open3D-ML's own dependencies (torch flavor + base requirements)" +echo "4. Install Open3D-ML dependencies" echo export PATH_TO_OPEN3D_ML="$PWD" -python -m pip install -r requirements.txt -r requirements-torch.txt \ +python -m pip install -r requirements.txt -r "${TORCH_REQUIREMENTS}" \ -r requirements-tensorflow.txt +echo "4b. PyTorch accelerator visibility" +echo +python -c " +import torch +print('torch:', torch.__version__) +print('torch.cuda.is_available():', torch.cuda.is_available()) +if hasattr(torch, 'xpu'): + print('torch.xpu.is_available():', torch.xpu.is_available()) +" + +if [[ "${INCLUDE_PARITY_TESTS}" == true ]]; then + python -c " +import open3d as o3d +import torch +import sys +backend = '${BACKEND}' +if backend == 'cuda' and not torch.cuda.is_available(): + sys.exit('cuda CI variant requires torch.cuda.is_available()') +if backend == 'xpu' and not (hasattr(torch, 'xpu') and torch.xpu.is_available()): + sys.exit('xpu CI variant requires torch.xpu.is_available()') +print('Accelerator check passed for', backend) +" +fi + +if [[ "${INCLUDE_PARITY_TESTS}" == true ]]; then + TEST_TARGETS=(tests) +else + TEST_TARGETS=( + tests/test_integration.py + tests/test_models_tf.py + ) +fi + +run_test_suite() { + echo "Running: ./tests/run_tests.sh ${TEST_TARGETS[*]}" + echo "Add --randomly-seed=SEED via pytest env if reproducing order." + ./tests/run_tests.sh "${TEST_TARGETS[@]}" +} + echo "5. Run the Open3D-ML pytest suite against the installed wheel" echo -echo "Add --randomly-seed=SEED to the test command to reproduce test order." -./tests/run_tests.sh +run_test_suite -echo "6. Also verify the OPEN3D_ML_ROOT dev-mode path (bundled models loaded from the" -echo " Open3D-ML checkout instead of whatever the wheel itself bundled)" +echo "6. Also verify the OPEN3D_ML_ROOT dev-mode path (models loaded from this" +echo " checkout instead of the wheel bundle)" echo export OPEN3D_ML_ROOT="${PATH_TO_OPEN3D_ML}" -./tests/run_tests.sh +run_test_suite unset OPEN3D_ML_ROOT deactivate diff --git a/docs/howtos.md b/docs/howtos.md index ed5e60eab..cd1eb57e0 100644 --- a/docs/howtos.md +++ b/docs/howtos.md @@ -257,4 +257,41 @@ Distributed training uses the PyTorch Distributed Data Parallel (DDP) module and ![PointPillars training on Waymo per epoch training time with number of GPUs](https://user-images.githubusercontent.com/41028320/220750523-57075575-8cc7-4e40-99b0-a4e79995f1ec.png) -See [`scripts/train_scripts/pointpillars_waymo.sh`](../scripts/train_scripts/pointpillars_waymo.sh) for an example SLURM training script for distributed training on two nodes, using four GPUs on each node. The remaining configuration is read from the config file [`pointpillars_waymo.yml`](../ml3d/configs/pointpillars_waymo.yml). \ No newline at end of file +See [`scripts/train_scripts/pointpillars_waymo.sh`](../scripts/train_scripts/pointpillars_waymo.sh) for an example SLURM training script for distributed training on two nodes, using four GPUs on each node. The remaining configuration is read from the config file [`pointpillars_waymo.yml`](../ml3d/configs/pointpillars_waymo.yml). + +## Testing CPU / CUDA / XPU parity + +The PyTorch model tests in [`tests/test_models_torch.py`](../tests/test_models_torch.py) build the same model and batch on CPU and on an accelerator (CUDA or XPU), then assert that outputs and gradients match within a tolerance (see [`tests/torch_backend_parity.py`](../tests/torch_backend_parity.py)). Correctness is verified as follows: + +- **CUDA**: new CUDA results are compared against the existing CPU results. +- **XPU (Intel GPU)**: new XPU results are compared against the same CPU results, using separate tolerances tuned for SYCL's op ordering. + +Both accelerator paths reuse the same CPU baseline, so CPU correctness is the +common foundation both backends are checked against. + +Run the full suite locally with: + +```bash +./tests/run_tests.sh +# or select specific tests, e.g. +./tests/run_tests.sh tests/test_models_torch.py -k "not sparse" +``` + +### Note on GitHub Actions CI + +GitHub-hosted runners have no NVIDIA or Intel GPU. CI runs `./ci/run_ci.sh cpu`, +which installs the `open3d_cpu` wheel and PyTorch CPU, then runs integration and +TensorFlow model tests only. **Torch CPU/accelerator parity** (`tests/test_models_torch.py`) +is not part of CPU CI. + +Run parity locally (or on GPU machines) with: + +```bash +./ci/run_ci.sh cuda # NVIDIA GPU + open3d CUDA wheel +./ci/run_ci.sh xpu # Intel GPU + open3d_xpu wheel +``` + +Both `cuda` and `xpu` variants install the matching PyTorch build and run the +full test tree, including `test_models_torch.py`. The `cpu` variant skips those +parity tests because they require a real accelerator and are not meaningful on +CPU-only hosts. \ No newline at end of file diff --git a/ml3d/metrics/__init__.py b/ml3d/metrics/__init__.py index d4e8e4d48..8eb80189e 100644 --- a/ml3d/metrics/__init__.py +++ b/ml3d/metrics/__init__.py @@ -4,6 +4,10 @@ # Open3D is built with CUDA and the machine has a CUDA device. from open3d.ml.contrib import iou_bev_cuda as iou_bev from open3d.ml.contrib import iou_3d_cuda as iou_3d +elif open3d.core.sycl.device_count() > 0: + # Open3D is built with SYCL and the machine has a SYCL (XPU) device. + from open3d.ml.contrib import iou_bev_sycl as iou_bev + from open3d.ml.contrib import iou_3d_sycl as iou_3d else: from open3d.ml.contrib import iou_bev_cpu as iou_bev from open3d.ml.contrib import iou_3d_cpu as iou_3d diff --git a/ml3d/torch/dataloaders/concat_batcher.py b/ml3d/torch/dataloaders/concat_batcher.py index a10684663..6389f59de 100644 --- a/ml3d/torch/dataloaders/concat_batcher.py +++ b/ml3d/torch/dataloaders/concat_batcher.py @@ -560,7 +560,7 @@ def __init__(self, device, model='KPConv'): """Initialize. Args: - device: torch device 'gpu' or 'cpu' + device: Torch device (cpu, cuda, or xpu). Returns: class: The corresponding class. diff --git a/ml3d/torch/models/base_model.py b/ml3d/torch/models/base_model.py index ad0c2af4c..2853ba8f4 100644 --- a/ml3d/torch/models/base_model.py +++ b/ml3d/torch/models/base_model.py @@ -32,7 +32,7 @@ def get_loss(self, Loss, results, inputs, device): Loss: A loss object. results: This is the output of the model. inputs: This is the input to the model. - device: The torch device to be used. + device: Torch device (cpu, cuda, or xpu). Returns: Returns the loss value. diff --git a/ml3d/torch/models/point_pillars.py b/ml3d/torch/models/point_pillars.py index 5254167ba..6f9a109b2 100644 --- a/ml3d/torch/models/point_pillars.py +++ b/ml3d/torch/models/point_pillars.py @@ -32,6 +32,7 @@ from .base_model_objdet import BaseModel from ...utils import MODEL +from ..utils.torch_utils import default_training_device from ..utils.objdet_helper import Anchor3DRangeGenerator, BBoxCoder, multiclass_nms, limit_period, get_paddings_indicator, bbox_overlaps, box3d_to_bev2d from ..modules.losses.focal_loss import FocalLoss from ..modules.losses.smooth_L1 import SmoothL1Loss @@ -60,7 +61,7 @@ class PointPillars(BaseModel): def __init__(self, name="PointPillars", - device="cuda", + device=None, point_cloud_range=[0, -40.0, -3, 70.0, 40.0, 1], classes=['car'], voxelize={}, @@ -72,6 +73,9 @@ def __init__(self, loss={}, **kwargs): + if device is None: + device = default_training_device() + super().__init__(name=name, point_cloud_range=point_cloud_range, device=device, diff --git a/ml3d/torch/models/point_rcnn.py b/ml3d/torch/models/point_rcnn.py index 61e5bcc06..8708c50f1 100644 --- a/ml3d/torch/models/point_rcnn.py +++ b/ml3d/torch/models/point_rcnn.py @@ -39,7 +39,7 @@ from ..modules.pointnet import Pointnet2MSG, PointnetSAModule from ..utils.objdet_helper import xywhr_to_xyxyr from open3d.ml.torch.ops import nms -from ..utils.torch_utils import gen_CNN +from ..utils.torch_utils import gen_CNN, default_training_device from ...datasets.utils import BEVBox3D, DataProcessing from ...datasets.utils.operations import points_in_box from ...datasets.augment import ObjdetAugmentation @@ -68,8 +68,8 @@ class PointRCNN(BaseModel): Args: name (string): Name of model. Default to "PointRCNN". - device (string): 'cuda' or 'cpu'. - Default to 'cuda'. + device (string): 'cuda', 'xpu', or 'cpu'. Default: first available + accelerator (cuda, then xpu), else cpu. classes (string[]): List of classes used for object detection: Default to ['Car']. score_thres (float): Min confindence score for prediction. @@ -86,7 +86,7 @@ class PointRCNN(BaseModel): def __init__(self, name="PointRCNN", - device="cuda", + device=None, classes=['Car'], score_thres=0.3, npoints=16384, @@ -95,6 +95,9 @@ def __init__(self, mode="RCNN", **kwargs): + if device is None: + device = default_training_device() + super().__init__(name=name, device=device, **kwargs) assert mode == "RPN" or mode == "RCNN" self.mode = mode diff --git a/ml3d/torch/models/point_transformer.py b/ml3d/torch/models/point_transformer.py index 328b359f7..73b633d14 100644 --- a/ml3d/torch/models/point_transformer.py +++ b/ml3d/torch/models/point_transformer.py @@ -343,7 +343,7 @@ def get_loss(self, sem_seg_loss, results, inputs, device): sem_seg_loss: Object of type `SemSegLoss`. results: Output of the model. inputs: Input of the model. - device: device(cpu or cuda). + device: Torch device (cpu, cuda, or xpu). Returns: Returns loss, labels and scores. @@ -730,7 +730,8 @@ def knn_batch(points, return_distances=True) if return_distances: return ans.neighbors_index.reshape( - -1, k).long().cuda(), ans.neighbors_distance.reshape(-1, k).to(device) + -1, k).long().to(device), ans.neighbors_distance.reshape(-1, k).to( + device) else: return ans.neighbors_index.reshape(-1, k).long().to(device) diff --git a/ml3d/torch/models/pvcnn.py b/ml3d/torch/models/pvcnn.py index ea47d4787..1374c88b5 100644 --- a/ml3d/torch/models/pvcnn.py +++ b/ml3d/torch/models/pvcnn.py @@ -11,6 +11,7 @@ from ...datasets.augment import SemsegAugmentation from ...utils.open3d_ops import pytorch_ops_built +from ..utils.torch_utils import default_training_device if pytorch_ops_built(): from open3d.ml.torch.ops import trilinear_devoxelize_forward, trilinear_devoxelize_backward @@ -86,7 +87,7 @@ class PVCNN(BaseModel): def __init__(self, name='PVCNN', - device="cuda", + device=None, num_classes=13, num_points=40960, extra_feature_channels=6, @@ -95,6 +96,8 @@ def __init__(self, batcher='DefaultBatcher', augment=None, **kwargs): + if device is None: + device = default_training_device() super(PVCNN, self).__init__( name=name, device=device, @@ -290,7 +293,7 @@ def get_loss(self, sem_seg_loss, results, inputs, device): sem_seg_loss: Object of type `SemSegLoss`. results: Output of the model. inputs: Input of the model. - device: device(cpu or cuda). + device: Torch device (cpu, cuda, or xpu). Returns: Returns loss, labels and scores. diff --git a/ml3d/torch/models/randlanet.py b/ml3d/torch/models/randlanet.py index 390c53cbe..904e1223d 100644 --- a/ml3d/torch/models/randlanet.py +++ b/ml3d/torch/models/randlanet.py @@ -363,7 +363,7 @@ def get_loss(self, Loss, results, inputs, device): Loss: Object of type `SemSegLoss`. results: Output of the model (B, N, C). inputs: Input of the model. - device: device(cpu or cuda). + device: Torch device (cpu, cuda, or xpu). Returns: Returns loss, labels and scores. diff --git a/ml3d/torch/models/sparseconvnet.py b/ml3d/torch/models/sparseconvnet.py index 86c555f33..37e50620b 100644 --- a/ml3d/torch/models/sparseconvnet.py +++ b/ml3d/torch/models/sparseconvnet.py @@ -8,6 +8,7 @@ from ...datasets.augment import SemsegAugmentation from open3d.ml.torch.layers import SparseConv, SparseConvTranspose from open3d.ml.torch.ops import voxelize, reduce_subarrays_sum +from ..utils.torch_utils import default_training_device class SparseConvUnet(BaseModel): @@ -18,7 +19,7 @@ class SparseConvUnet(BaseModel): Attributes: name: Name of model. Default to "SparseConvUnet". - device: Which device to use (cpu or cuda). + device: Which device to use (cpu, cuda, or xpu). voxel_size: Voxel length for subsampling. multiplier: min length of feature length in each layer. conv_block_reps: repetition of Unet Blocks. @@ -30,7 +31,7 @@ class SparseConvUnet(BaseModel): def __init__( self, name="SparseConvUnet", - device="cuda", + device=None, multiplier=16, # Proportional to number of neurons in each layer. voxel_size=0.05, conv_block_reps=1, # Conv block repetitions. @@ -41,6 +42,8 @@ def __init__( batcher='ConcatBatcher', augment=None, **kwargs): + if device is None: + device = default_training_device() super(SparseConvUnet, self).__init__(name=name, device=device, multiplier=multiplier, @@ -197,7 +200,7 @@ def get_loss(self, Loss, results, inputs, device): Loss: Object of type `SemSegLoss`. results: Output of the model. inputs: Input of the model. - device: device(cpu or cuda). + device: Torch device (cpu, cuda, or xpu). Returns: Returns loss, labels and scores. diff --git a/ml3d/torch/pipelines/base_pipeline.py b/ml3d/torch/pipelines/base_pipeline.py index 7aa52b9f2..c05856987 100644 --- a/ml3d/torch/pipelines/base_pipeline.py +++ b/ml3d/torch/pipelines/base_pipeline.py @@ -7,6 +7,7 @@ # use relative import for being compatible with Open3d main repo from ...utils import Config, make_dir +from ..utils.torch_utils import default_training_device class BasePipeline(ABC): @@ -15,7 +16,7 @@ class BasePipeline(ABC): def __init__(self, model, dataset=None, - device='cuda', + device=None, distributed=False, **kwargs): """Initialize. @@ -23,13 +24,17 @@ def __init__(self, Args: model: A network model. dataset: A dataset, or None for inference model. - device: 'cuda' or 'cpu'. + device: ``cuda``, ``xpu``, or ``cpu``. Default: first available + accelerator (cuda, then xpu), else cpu. distributed: Whether to use multiple gpus. kwargs: Returns: class: The corresponding class. """ + if device is None: + device = default_training_device() + self.cfg = Config(kwargs) if kwargs['name'] is None: @@ -78,7 +83,12 @@ def __init__(self, if distributed: self.device = torch.device(device) print(f"Rank : {self.rank} using device : {self.device}") - torch.cuda.set_device(self.device) + device_index = (self.device.index if self.device.index is not None + else 0) + if hasattr(torch, 'accelerator'): + torch.accelerator.set_device_index(device_index) + elif self.device.type == 'cuda': + torch.cuda.set_device(self.device) else: self.device = torch.device('cuda') diff --git a/ml3d/torch/pipelines/object_detection.py b/ml3d/torch/pipelines/object_detection.py index 0e6f739d6..a493d1e47 100644 --- a/ml3d/torch/pipelines/object_detection.py +++ b/ml3d/torch/pipelines/object_detection.py @@ -31,7 +31,7 @@ def __init__(self, dataset=None, name='ObjectDetection', main_log_dir='./logs/', - device='cuda', + device=None, split='train', **kwargs): super().__init__(model=model, @@ -335,9 +335,11 @@ def run_train(self): # wrap model for multiple GPU if self.distributed: - model.cuda(self.device) + model.to(self.device) + device_index = (self.device.index if self.device.index is not None + else 0) model = torch.nn.parallel.DistributedDataParallel( - model, device_ids=[self.device]) + model, device_ids=[device_index]) model.get_loss = model.module.get_loss model.cfg = model.module.cfg model.inference_end = model.module.inference_end diff --git a/ml3d/torch/pipelines/semantic_segmentation.py b/ml3d/torch/pipelines/semantic_segmentation.py index f44990e16..807b73707 100644 --- a/ml3d/torch/pipelines/semantic_segmentation.py +++ b/ml3d/torch/pipelines/semantic_segmentation.py @@ -70,7 +70,7 @@ class SemanticSegmentation(BasePipeline): scheduler_gamma: The decaying factor associated with the scheduler. momentum: The momentum that accelerates the training rate schedule. main_log_dir: The directory where logs are stored. - device: The device to be used for training. + device: Device for training (cpu, cuda, or xpu). split: The dataset split to be used. In this example, we have used "train". train_sum_dir: The directory where the trainig summary is stored. @@ -94,7 +94,7 @@ def __init__( scheduler_gamma=0.95, momentum=0.98, main_log_dir='./logs/', - device='cuda', + device=None, split='train', train_sum_dir='train_log', **kwargs): diff --git a/ml3d/torch/utils/objdet_helper.py b/ml3d/torch/utils/objdet_helper.py index 522a7c0c8..f1afe07b1 100644 --- a/ml3d/torch/utils/objdet_helper.py +++ b/ml3d/torch/utils/objdet_helper.py @@ -168,8 +168,9 @@ def grid_anchors(self, featmap_size, device='cuda'): Args: featmap_size (tuple[int]): Size of the feature map. - device (str, optional): Device the tensor will be put on. - Defaults to 'cuda'. + device (str, optional): Device the tensor will be put on (cpu, cuda, + or xpu). Callers should pass the model device; default ``cuda`` + is for CUDA-only legacy paths. Returns: torch.Tensor: Anchors in the overall feature map. @@ -203,7 +204,7 @@ def anchors_single_range(self, shape [N, 3], in order of x, y, z. rotations (list[float] | np.ndarray | torch.Tensor): Rotations of anchors in a single feature grid. - device (str): Devices that the anchors will be put on. + device (str): Device for anchors (cpu, cuda, or xpu). Returns: torch.Tensor: Anchors with shape \ diff --git a/ml3d/torch/utils/torch_utils.py b/ml3d/torch/utils/torch_utils.py index 4d8699763..be85ceb78 100644 --- a/ml3d/torch/utils/torch_utils.py +++ b/ml3d/torch/utils/torch_utils.py @@ -1,9 +1,19 @@ import os import re +import torch from torch import nn import torch.nn.functional as F +def default_training_device(): + """Pick cuda, xpu, or cpu for model defaults (matches pipeline/test logic).""" + if torch.cuda.is_available(): + return "cuda" + if hasattr(torch, "xpu") and torch.xpu.is_available(): + return "xpu" + return "cpu" + + def atoi(text): return int(text) if text.isdigit() else text diff --git a/scripts/run_pipeline.py b/scripts/run_pipeline.py index 895f470f7..bea54bfcd 100644 --- a/scripts/run_pipeline.py +++ b/scripts/run_pipeline.py @@ -31,11 +31,11 @@ def parse_args(): parser.add_argument('--dataset_path', help='path to the dataset') parser.add_argument('--ckpt_path', help='path to the checkpoint') parser.add_argument('--device', - help='devices to run the pipeline', + help='device: cpu, cuda, xpu, gpu, or sycl', default='cuda') parser.add_argument('--device_ids', nargs='+', - help='cuda device list', + help='accelerator device indices (e.g. 0 1)', default=['0']) parser.add_argument('--split', help='train or test', default='train') parser.add_argument('--mode', help='additional mode', default=None) @@ -61,7 +61,8 @@ def parse_args(): parser.add_argument( '--backend', help= - 'backend for distributed training. One of (nccl, gloo)}, default: gloo', + 'backend for distributed training. One of (nccl, gloo, xccl for XPU), ' + 'default: gloo', default='gloo') args, unknown = parser.parse_known_args() @@ -117,9 +118,15 @@ def main(): "Multi-GPU training with TensorFlow is not yet implemented." ) tf.config.set_visible_devices(gpus[0], 'GPU') - else: + elif device == 'xpu': + tf.config.set_visible_devices([], 'GPU') + elif ':' in device: idx = device.split(':')[1] tf.config.set_visible_devices(gpus[int(idx)], 'GPU') + else: + raise ValueError( + f"Unsupported TensorFlow device {device!r}; " + "use cpu, cuda, or cuda:N.") except RuntimeError as e: print(e) @@ -225,7 +232,7 @@ def main_worker(local_rank, Dataset, Model, Pipeline, cfg_dict_dataset, cfg_dict_model['seed'] = rng cfg_dict_pipeline['seed'] = rng - device = f"cuda:{args.device_ids[local_rank]}" + device = f"{args.device}:{args.device_ids[local_rank]}" print( f"local_rank = {local_rank}, rank = {rank}, world_size = {world_size}," f" gpu = {device}") diff --git a/tests/test_models_torch.py b/tests/test_models_torch.py index 6055973aa..9e5f261d8 100644 --- a/tests/test_models_torch.py +++ b/tests/test_models_torch.py @@ -2,7 +2,39 @@ Each CPU+accelerator model test builds the same model and batch on each device, runs one forward and one backward pass per device, and compares outputs and -gradients. Models whose ops have no CPU kernel run on the accelerator only. +gradients (see ``torch_backend_parity.assert_cpu_accelerator_parity``). Models +whose ops have no CPU kernel run on the accelerator only (``@skip_no_accelerator``). + +Registered PyTorch models in ``ml3d/torch/models`` and how they are covered here: + ++------------------+----------+--------------------------------+--------+-----------------------------+ +| Model | Task | Dedicated test | Parity | Basic | ++==================+==========+================================+========+=============================+ +| RandLANet | Semseg | test_randlanet_torch | Yes | Yes (CPU path if no GPU) | +| KPFCNN | Semseg | test_kpconv_torch | Yes | Yes; OpenVINO optional | +| PointPillars | Obj det | test_pointpillars_torch | Yes | Yes; OpenVINO optional | +| SparseConvUnet | Semseg | test_sparseconvunet_torch | Yes | Yes (relaxed atol) | +| PointRCNN (RPN) | Obj det | test_pointrcnn_rpn_torch | No | Yes (@skip_no_accelerator) | +| PointRCNN (RCNN) | Obj det | test_pointrcnn_rcnn_torch | No | Yes (@skip_no_accelerator) | +| PointTransformer | Semseg | test_pointtransformer_torch | No | Yes (@skip_no_accelerator) | +| PVCNN | Semseg | test_pvcnn_torch | No | Yes (@skip_no_accelerator) | ++------------------+----------+--------------------------------+--------+-----------------------------+ + +**Parity** — ``assert_cpu_accelerator_parity``: same weights, forward + backward on +CPU and CUDA/XPU, compare outputs and gradients. + +**Basic** — forward + backward smoke; accelerator-only rows require CUDA or XPU. + +OpenVINOModel (wrapper, not in table): no dedicated test; exercised in +``test_kpconv_torch`` / ``test_pointpillars_torch`` when OpenVINO is available +(CPU torch vs OpenVINO, not CPU vs GPU parity). + +Other PyTorch tests outside this file: ``test_integration_torch`` only constructs +RandLANet from a config (no forward pass). + +Parity tests need ``BUILD_PYTORCH_OPS`` and a CUDA or XPU device for the +accelerator half. CPU CI (``./ci/run_ci.sh cpu``) does not run this file; use +``./ci/run_ci.sh cuda`` or ``xpu`` locally for the full matrix. """ import copy @@ -39,7 +71,12 @@ _accel = None if o3d.core.cuda.is_available(): _accel = torch.device('cuda') -elif o3d.core.sycl.is_available(): +elif o3d.core.sycl.is_available() and torch.xpu.is_available(): + # o3d.core.sycl.is_available() is True whenever Open3D's SYCL module was + # built, even on hosts with no Intel GPU (it falls back to a SYCL CPU + # device). torch.xpu.is_available() additionally confirms a real XPU + # device is visible to PyTorch, so this only picks 'xpu' on actual GPU + # hardware. _accel = torch.device('xpu') skip_no_pytorch_ops = pytest.mark.skipif( diff --git a/tests/torch_backend_parity.py b/tests/torch_backend_parity.py index 9c1da0e25..4bf9daf32 100644 --- a/tests/torch_backend_parity.py +++ b/tests/torch_backend_parity.py @@ -40,7 +40,12 @@ def assert_cpu_accelerator_parity(run_on_device, atol=None, grad_atol=None): if o3d.core.cuda.is_available(): accel = torch.device('cuda') - elif o3d.core.sycl.is_available(): + elif o3d.core.sycl.is_available() and torch.xpu.is_available(): + # o3d.core.sycl.is_available() is True whenever Open3D's SYCL module was + # built, even on hosts with no Intel GPU (it falls back to a SYCL CPU + # device). torch.xpu.is_available() additionally confirms a real XPU + # device is visible to PyTorch, so this only picks 'xpu' on actual GPU + # hardware. accel = torch.device('xpu') else: return cpu_output, cpu_model diff --git a/torch-acc-plan.md b/torch-acc-plan.md new file mode 100644 index 000000000..561e838cc --- /dev/null +++ b/torch-acc-plan.md @@ -0,0 +1,99 @@ +# Open3D-ML torch.accelerator (CUDA/XPU) generalization plan + +Status as of 2026-08-04. Use `torch.accelerator` API where possible to +generalize CUDA-only code paths to also work with XPU (Intel Arc, SYCL). +Parity testing strategy (critical, must not regress): +- old CUDA impl results == old CPU impl results +- new SYCL/XPU impl results == old==new CPU impl results + +## Already DONE in this repo (verified in this session) +- `tests/test_models_torch.py` and `tests/torch_backend_parity.py`: `_accel`/`accel` + detection now requires BOTH `o3d.core.sycl.is_available()` AND + `torch.xpu.is_available()` before selecting XPU (o3d.core.sycl.is_available() + is True even on SYCL-CPU-fallback-only hosts with no real GPU — unsafe alone). +- `ml3d/metrics/__init__.py`: added SYCL branch selecting `iou_bev_sycl`/`iou_3d_sycl` + when `open3d.core.sycl.device_count() > 0` (verified numerically matches CPU, + atol=1e-4). +- `ci/run_ci.sh`: configurable `./ci/run_ci.sh cpu|cuda|xpu` — wheel + torch + deps per backend; parity suite only for cuda/xpu. GitHub Actions runs `cpu` only. +- `docs/howtos.md`: new "Testing CPU / CUDA / XPU parity" section + CI note. +- `README.md`: added `requirements-torch-xpu.txt` install line + howtos link. +- `ml3d/torch/pipelines/base_pipeline.py`: ALREADY generalized (contrary to + earlier assumption) — `__init__` already has an `elif (device == 'xpu' or + str(device).startswith('xpu')) and hasattr(torch, 'xpu') and + torch.xpu.is_available():` branch alongside the cuda/cpu branches. No changes + needed here unless we want to also generalize the `torch.cuda.set_device()` + call in the `distributed` branch to use `torch.accelerator.set_device_index()`. +- `ml3d/utils/builder.py::convert_device_name()`: ALREADY generalized (contrary + to earlier assumption) — maps `gpu_names = ["gpu", "cuda"] -> "cuda"`, + `xpu_names = ["xpu", "sycl"] -> "xpu"`, `cpu_names = ["cpu"] -> "cpu"`. No + changes needed. +- **2026-08-04 (items 1–4):** `point_transformer.py` KNN indices use `.to(device)` + instead of `.cuda()`; `object_detection.py` distributed wrap uses `model.to()`. + Model ctors (`PointPillars`, `PointRCNN`, `PVCNN`, `SparseConvUnet`) default + `device=None` → `ml3d.torch.utils.torch_utils.default_training_device()` + (cuda if available, else xpu if `torch.xpu.is_available()`, else cpu). + `scripts/run_pipeline.py`: TF branch handles bare `xpu`, distributed device + string uses `{args.device}:{id}`, `--backend` help mentions `xccl`. +- **2026-08-04 (follow-up):** `BasePipeline` / torch pipelines default + `device=None` → `default_training_device()`; distributed rank setup uses + `torch.accelerator.set_device_index()` when available. Object-detection DDP + uses integer `device_ids` (was passing `torch.device`). + +## Remaining TODO + +1. ~~Optional: `base_pipeline.py` distributed branch — `torch.cuda.set_device()` → + `torch.accelerator.set_device_index()`~~ DONE (2026-08-04). +2. ~~`ci/run_ci.sh`~~ backend argument + GH Actions `cpu` only. +3. Pipeline/model parity tests on local Arc: all 8 `test_models_torch.py` cases + hit exit 124 at TIMEOUT=300s (XPU oneDNN init then stall — see KNOWN RISK). + Re-run with longer timeout or after PyTorch/XPU stack fix; not a code regression + from items 1–4. +4. ~~Cosmetic: docstrings mention xpu~~ DONE (torch models, pipelines, batcher, + objdet_helper, run_pipeline --device help). TF left cuda/cpu only (no XPU). + +## Remaining TODO (historical — items 1–4 completed 2026-08-04) + +~~1. point_transformer `.cuda()`~~ DONE +~~2. object_detection `model.cuda`~~ DONE +~~3. ctor device="cuda" defaults~~ DONE +~~4. run_pipeline.py TF/distributed/backend help~~ DONE + +5. TensorFlow: **DO NOT TOUCH** — user confirmed TF has no SYCL support. + Leave `ml3d/tf/utils/pointnet/pointnet2_utils.py`, + `ml3d/tf/utils/roipool3d/roipool3d_utils.py`, `ml3d/tf/models/pvcnn.py` + CUDA-only guards (`open3d.core.cuda.device_count()`) exactly as-is. This + reverses an earlier (pre-clarification) plan item — do not re-add SYCL + handling to TF code. + +6. Cosmetic (duplicate note): docstring xpu mentions — see Remaining TODO #3 above. + +## Verification + +- Re-run parity tests locally after changes: + `OPEN3D_ML_ROOT=$PWD PATH_TO_OPEN3D_ML=$PWD ./tests/run_tests.sh tests/test_models_torch.py` + (per-test subprocess isolation is required — XPU/SYCL state left behind by + one model test can deadlock the next in a shared interpreter). +- Environment: venv at `/home/ssheorey/Documents/o3d.venv`, open3d-xpu wheel + with `BUNDLE_OPEN3D_ML=True`, `BUILD_SYCL_MODULE=True`, + `BUILD_PYTORCH_OPS=True` (confirmed installed 2026-08-04). +- Local hardware: 2x Intel Arc A770 (i915 driver, renderD128/129). +- KNOWN RISK: a bare `torch.randn(4,4).to('xpu'); x @ x` was previously + observed to hang indefinitely (300s+) on this machine — likely a GEMM/oneDNN + JIT compile or Level-Zero stall, unrelated to Open3D-ML code. If model tests + hang, this is the suspected cause — not a regression from these changes. + Always run tests with a wrapper timeout (e.g. via `tests/run_tests.sh`'s + built-in per-test `TIMEOUT`, default 120s, bumped to 300s in recent runs). +- IMPORTANT process hygiene: background test runs via `nohup ... &` can become + orphaned if the parent shell/terminal is killed without killing the child + process tree first. Always check `ps aux | grep pytest` for stray leftover + runs before starting a new test run, to avoid two runs contending for the + same 2 GPUs and corrupting results/timing. + +## Test run (2026-08-04) + +- Full suite: `PATH=/home/ssheorey/Documents/o3d.venv/bin:$PATH OPEN3D_ML_ROOT=$PWD + PATH_TO_OPEN3D_ML=$PWD TIMEOUT=300 ./tests/run_tests.sh tests/test_models_torch.py` + → **8/8 exit 124** (timeout). Single `test_randlanet_torch` stalls after + oneDNN SYCL GPU init on 2× Arc A770 (`xpu True`, `sycl device_count 2`). +- Log: `/tmp/test_models_torch_after_fix.log`, `/tmp/randlanet_single.log`. From 217236c3bae8c034b910c4187a24a32495141480 Mon Sep 17 00:00:00 2001 From: Sameer Sheorey Date: Wed, 19 Aug 2026 15:35:39 -0700 Subject: [PATCH 06/14] enable parity test for point_transformer --- tests/test_models_torch.py | 53 +++++++++++++++++++++----------------- 1 file changed, 30 insertions(+), 23 deletions(-) diff --git a/tests/test_models_torch.py b/tests/test_models_torch.py index 9e5f261d8..1bf1b696e 100644 --- a/tests/test_models_torch.py +++ b/tests/test_models_torch.py @@ -16,7 +16,7 @@ | SparseConvUnet | Semseg | test_sparseconvunet_torch | Yes | Yes (relaxed atol) | | PointRCNN (RPN) | Obj det | test_pointrcnn_rpn_torch | No | Yes (@skip_no_accelerator) | | PointRCNN (RCNN) | Obj det | test_pointrcnn_rcnn_torch | No | Yes (@skip_no_accelerator) | -| PointTransformer | Semseg | test_pointtransformer_torch | No | Yes (@skip_no_accelerator) | +| PointTransformer | Semseg | test_pointtransformer_torch | Yes | Yes | | PVCNN | Semseg | test_pvcnn_torch | No | Yes (@skip_no_accelerator) | +------------------+----------+--------------------------------+--------+-----------------------------+ @@ -467,22 +467,23 @@ def test_pointrcnn_rcnn_torch(): @skip_no_pytorch_ops -@skip_no_accelerator def test_pointtransformer_torch(): - # NOTE: furthest_point_sampling (encoder downsampling) has no CPU kernel, same as - # PointRCNN -- forward+backward on accelerator only; no CPU/XPU parity baseline. import open3d.ml.torch as ml3d np.random.seed(66) torch.manual_seed(66) - net = ml3d.models.PointTransformer(device=str(_accel), - num_classes=13, - in_channels=6, - augment={}, - ignored_label_inds=[]) - net.to(_accel) - net.eval() + def make_net(device=torch.device('cpu')): + net = ml3d.models.PointTransformer(device=str(device), + num_classes=13, + in_channels=6, + augment={}, + ignored_label_inds=[]) + net.eval() + return net.to(device) + + net = make_net() + state = copy.deepcopy(net.state_dict()) n = 4096 data = { @@ -491,19 +492,25 @@ def test_pointtransformer_torch(): 'label': np.random.randint(13, size=(n,)).astype(np.int32), } attr = {'split': 'train'} - data = net.preprocess(data, attr) - data = net.transform(data, attr) - sample = {'data': data, 'attr': attr} - batcher = ml3d.dataloaders.ConcatBatcher(str(_accel), - model='PointTransformer') - batch = batcher.collate_fn([sample]) - batch['data'].to(_accel) - out = net(batch['data']) - assert out.shape[1] == 13 + sample = { + 'data': net.transform(net.preprocess(data, attr), attr), + 'attr': attr, + } - loss, _, _ = net.get_loss(semseg_loss, out, batch, _accel) - loss.backward() - assert any(p.grad is not None for p in net.parameters()) + def run(device): + model = make_net(device) + model.load_state_dict(state) + batcher = ml3d.dataloaders.ConcatBatcher( + str(device), model='PointTransformer') + batch = batcher.collate_fn([sample]) + batch['data'].to(device) + out = model(batch['data']) + loss, _, _ = model.get_loss(semseg_loss, out, batch, device) + loss.backward() + return out, model + + out_cpu, _ = assert_cpu_accelerator_parity(run) + assert out_cpu.shape[1] == 13 @skip_no_pytorch_ops From 51f8f860747ba59b9fc69f4693fd2507e0cc9a24 Mon Sep 17 00:00:00 2001 From: Sameer Sheorey Date: Thu, 20 Aug 2026 22:04:03 +0200 Subject: [PATCH 07/14] fix point transformer test --- tests/test_models_torch.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_models_torch.py b/tests/test_models_torch.py index 1bf1b696e..0631ca44e 100644 --- a/tests/test_models_torch.py +++ b/tests/test_models_torch.py @@ -485,7 +485,7 @@ def make_net(device=torch.device('cpu')): net = make_net() state = copy.deepcopy(net.state_dict()) - n = 4096 + n = 8192 data = { 'point': np.random.random((n, 3)).astype(np.float32), 'feat': np.random.random((n, 3)).astype(np.float32), From edd358215b3cb83daf144c5e63c8fed517fb7ee1 Mon Sep 17 00:00:00 2001 From: Sameer Sheorey <41028320+ssheorey@users.noreply.github.com> Date: Thu, 20 Aug 2026 13:11:20 -0700 Subject: [PATCH 08/14] Delete torch-acc-plan.md --- torch-acc-plan.md | 99 ----------------------------------------------- 1 file changed, 99 deletions(-) delete mode 100644 torch-acc-plan.md diff --git a/torch-acc-plan.md b/torch-acc-plan.md deleted file mode 100644 index 561e838cc..000000000 --- a/torch-acc-plan.md +++ /dev/null @@ -1,99 +0,0 @@ -# Open3D-ML torch.accelerator (CUDA/XPU) generalization plan - -Status as of 2026-08-04. Use `torch.accelerator` API where possible to -generalize CUDA-only code paths to also work with XPU (Intel Arc, SYCL). -Parity testing strategy (critical, must not regress): -- old CUDA impl results == old CPU impl results -- new SYCL/XPU impl results == old==new CPU impl results - -## Already DONE in this repo (verified in this session) -- `tests/test_models_torch.py` and `tests/torch_backend_parity.py`: `_accel`/`accel` - detection now requires BOTH `o3d.core.sycl.is_available()` AND - `torch.xpu.is_available()` before selecting XPU (o3d.core.sycl.is_available() - is True even on SYCL-CPU-fallback-only hosts with no real GPU — unsafe alone). -- `ml3d/metrics/__init__.py`: added SYCL branch selecting `iou_bev_sycl`/`iou_3d_sycl` - when `open3d.core.sycl.device_count() > 0` (verified numerically matches CPU, - atol=1e-4). -- `ci/run_ci.sh`: configurable `./ci/run_ci.sh cpu|cuda|xpu` — wheel + torch - deps per backend; parity suite only for cuda/xpu. GitHub Actions runs `cpu` only. -- `docs/howtos.md`: new "Testing CPU / CUDA / XPU parity" section + CI note. -- `README.md`: added `requirements-torch-xpu.txt` install line + howtos link. -- `ml3d/torch/pipelines/base_pipeline.py`: ALREADY generalized (contrary to - earlier assumption) — `__init__` already has an `elif (device == 'xpu' or - str(device).startswith('xpu')) and hasattr(torch, 'xpu') and - torch.xpu.is_available():` branch alongside the cuda/cpu branches. No changes - needed here unless we want to also generalize the `torch.cuda.set_device()` - call in the `distributed` branch to use `torch.accelerator.set_device_index()`. -- `ml3d/utils/builder.py::convert_device_name()`: ALREADY generalized (contrary - to earlier assumption) — maps `gpu_names = ["gpu", "cuda"] -> "cuda"`, - `xpu_names = ["xpu", "sycl"] -> "xpu"`, `cpu_names = ["cpu"] -> "cpu"`. No - changes needed. -- **2026-08-04 (items 1–4):** `point_transformer.py` KNN indices use `.to(device)` - instead of `.cuda()`; `object_detection.py` distributed wrap uses `model.to()`. - Model ctors (`PointPillars`, `PointRCNN`, `PVCNN`, `SparseConvUnet`) default - `device=None` → `ml3d.torch.utils.torch_utils.default_training_device()` - (cuda if available, else xpu if `torch.xpu.is_available()`, else cpu). - `scripts/run_pipeline.py`: TF branch handles bare `xpu`, distributed device - string uses `{args.device}:{id}`, `--backend` help mentions `xccl`. -- **2026-08-04 (follow-up):** `BasePipeline` / torch pipelines default - `device=None` → `default_training_device()`; distributed rank setup uses - `torch.accelerator.set_device_index()` when available. Object-detection DDP - uses integer `device_ids` (was passing `torch.device`). - -## Remaining TODO - -1. ~~Optional: `base_pipeline.py` distributed branch — `torch.cuda.set_device()` → - `torch.accelerator.set_device_index()`~~ DONE (2026-08-04). -2. ~~`ci/run_ci.sh`~~ backend argument + GH Actions `cpu` only. -3. Pipeline/model parity tests on local Arc: all 8 `test_models_torch.py` cases - hit exit 124 at TIMEOUT=300s (XPU oneDNN init then stall — see KNOWN RISK). - Re-run with longer timeout or after PyTorch/XPU stack fix; not a code regression - from items 1–4. -4. ~~Cosmetic: docstrings mention xpu~~ DONE (torch models, pipelines, batcher, - objdet_helper, run_pipeline --device help). TF left cuda/cpu only (no XPU). - -## Remaining TODO (historical — items 1–4 completed 2026-08-04) - -~~1. point_transformer `.cuda()`~~ DONE -~~2. object_detection `model.cuda`~~ DONE -~~3. ctor device="cuda" defaults~~ DONE -~~4. run_pipeline.py TF/distributed/backend help~~ DONE - -5. TensorFlow: **DO NOT TOUCH** — user confirmed TF has no SYCL support. - Leave `ml3d/tf/utils/pointnet/pointnet2_utils.py`, - `ml3d/tf/utils/roipool3d/roipool3d_utils.py`, `ml3d/tf/models/pvcnn.py` - CUDA-only guards (`open3d.core.cuda.device_count()`) exactly as-is. This - reverses an earlier (pre-clarification) plan item — do not re-add SYCL - handling to TF code. - -6. Cosmetic (duplicate note): docstring xpu mentions — see Remaining TODO #3 above. - -## Verification - -- Re-run parity tests locally after changes: - `OPEN3D_ML_ROOT=$PWD PATH_TO_OPEN3D_ML=$PWD ./tests/run_tests.sh tests/test_models_torch.py` - (per-test subprocess isolation is required — XPU/SYCL state left behind by - one model test can deadlock the next in a shared interpreter). -- Environment: venv at `/home/ssheorey/Documents/o3d.venv`, open3d-xpu wheel - with `BUNDLE_OPEN3D_ML=True`, `BUILD_SYCL_MODULE=True`, - `BUILD_PYTORCH_OPS=True` (confirmed installed 2026-08-04). -- Local hardware: 2x Intel Arc A770 (i915 driver, renderD128/129). -- KNOWN RISK: a bare `torch.randn(4,4).to('xpu'); x @ x` was previously - observed to hang indefinitely (300s+) on this machine — likely a GEMM/oneDNN - JIT compile or Level-Zero stall, unrelated to Open3D-ML code. If model tests - hang, this is the suspected cause — not a regression from these changes. - Always run tests with a wrapper timeout (e.g. via `tests/run_tests.sh`'s - built-in per-test `TIMEOUT`, default 120s, bumped to 300s in recent runs). -- IMPORTANT process hygiene: background test runs via `nohup ... &` can become - orphaned if the parent shell/terminal is killed without killing the child - process tree first. Always check `ps aux | grep pytest` for stray leftover - runs before starting a new test run, to avoid two runs contending for the - same 2 GPUs and corrupting results/timing. - -## Test run (2026-08-04) - -- Full suite: `PATH=/home/ssheorey/Documents/o3d.venv/bin:$PATH OPEN3D_ML_ROOT=$PWD - PATH_TO_OPEN3D_ML=$PWD TIMEOUT=300 ./tests/run_tests.sh tests/test_models_torch.py` - → **8/8 exit 124** (timeout). Single `test_randlanet_torch` stalls after - oneDNN SYCL GPU init on 2× Arc A770 (`xpu True`, `sycl device_count 2`). -- Log: `/tmp/test_models_torch_after_fix.log`, `/tmp/randlanet_single.log`. From 86528d57bbc0182da123b8936de7f4b7bb9ced44 Mon Sep 17 00:00:00 2001 From: Sameer Sheorey Date: Thu, 20 Aug 2026 22:18:21 +0200 Subject: [PATCH 09/14] style --- ml3d/torch/models/point_transformer.py | 5 +++-- ml3d/torch/pipelines/base_pipeline.py | 7 +++---- ml3d/torch/pipelines/object_detection.py | 4 ++-- tests/test_models_torch.py | 14 ++++++-------- tests/torch_backend_parity.py | 1 + 5 files changed, 15 insertions(+), 16 deletions(-) diff --git a/ml3d/torch/models/point_transformer.py b/ml3d/torch/models/point_transformer.py index 73b633d14..130d877b8 100644 --- a/ml3d/torch/models/point_transformer.py +++ b/ml3d/torch/models/point_transformer.py @@ -730,8 +730,9 @@ def knn_batch(points, return_distances=True) if return_distances: return ans.neighbors_index.reshape( - -1, k).long().to(device), ans.neighbors_distance.reshape(-1, k).to( - device) + -1, + k).long().to(device), ans.neighbors_distance.reshape(-1, + k).to(device) else: return ans.neighbors_index.reshape(-1, k).long().to(device) diff --git a/ml3d/torch/pipelines/base_pipeline.py b/ml3d/torch/pipelines/base_pipeline.py index c05856987..36a904af8 100644 --- a/ml3d/torch/pipelines/base_pipeline.py +++ b/ml3d/torch/pipelines/base_pipeline.py @@ -72,8 +72,7 @@ def __init__(self, if distributed: raise NotImplementedError( "Distributed training for XPU is not supported yet.") - self.device = torch.device( - device if ':' in str(device) else 'xpu') + self.device = torch.device(device if ':' in str(device) else 'xpu') elif not torch.cuda.is_available(): if distributed: raise NotImplementedError( @@ -83,8 +82,8 @@ def __init__(self, if distributed: self.device = torch.device(device) print(f"Rank : {self.rank} using device : {self.device}") - device_index = (self.device.index if self.device.index is not None - else 0) + device_index = (self.device.index + if self.device.index is not None else 0) if hasattr(torch, 'accelerator'): torch.accelerator.set_device_index(device_index) elif self.device.type == 'cuda': diff --git a/ml3d/torch/pipelines/object_detection.py b/ml3d/torch/pipelines/object_detection.py index a493d1e47..e79311ae2 100644 --- a/ml3d/torch/pipelines/object_detection.py +++ b/ml3d/torch/pipelines/object_detection.py @@ -336,8 +336,8 @@ def run_train(self): # wrap model for multiple GPU if self.distributed: model.to(self.device) - device_index = (self.device.index if self.device.index is not None - else 0) + device_index = (self.device.index + if self.device.index is not None else 0) model = torch.nn.parallel.DistributedDataParallel( model, device_ids=[device_index]) model.get_loss = model.module.get_loss diff --git a/tests/test_models_torch.py b/tests/test_models_torch.py index 0631ca44e..b8651a051 100644 --- a/tests/test_models_torch.py +++ b/tests/test_models_torch.py @@ -47,8 +47,7 @@ import pytest import torch -from torch_backend_parity import (assert_cpu_accelerator_parity, - move_to_device) +from torch_backend_parity import (assert_cpu_accelerator_parity, move_to_device) if 'PATH_TO_OPEN3D_ML' in os.environ.keys(): base = os.environ['PATH_TO_OPEN3D_ML'] @@ -92,8 +91,8 @@ def _bev_box3d(): """BEVBox3D lives in Open3D-ML (ml3d), not in open3d.ml.datasets.""" - ml_root = (os.environ.get('OPEN3D_ML_ROOT') - or os.environ.get('PATH_TO_OPEN3D_ML') or base) + ml_root = (os.environ.get('OPEN3D_ML_ROOT') or + os.environ.get('PATH_TO_OPEN3D_ML') or base) if ml_root not in sys.path: sys.path.insert(0, ml_root) from ml3d.datasets.utils import BEVBox3D @@ -115,8 +114,7 @@ def _pointrcnn_ctor_kwargs(mode): npoints=[256, 64, 16, 4], radius=[[0.1, 0.5], [0.5, 1.0], [1.0, 2.0], [2.0, 4.0]], nsample=[[4, 8], [4, 8], [4, 8], [4, 8]], - mlps=[[[8, 8, 16], [16, 16, 32]], - [[32, 32, 64], [32, 48, 64]], + mlps=[[[8, 8, 16], [16, 16, 32]], [[32, 32, 64], [32, 48, 64]], [[64, 98, 128], [64, 98, 128]], [[128, 128, 256], [128, 192, 256]]], ), @@ -500,8 +498,8 @@ def make_net(device=torch.device('cpu')): def run(device): model = make_net(device) model.load_state_dict(state) - batcher = ml3d.dataloaders.ConcatBatcher( - str(device), model='PointTransformer') + batcher = ml3d.dataloaders.ConcatBatcher(str(device), + model='PointTransformer') batch = batcher.collate_fn([sample]) batch['data'].to(device) out = model(batch['data']) diff --git a/tests/torch_backend_parity.py b/tests/torch_backend_parity.py index 4bf9daf32..5281d9660 100644 --- a/tests/torch_backend_parity.py +++ b/tests/torch_backend_parity.py @@ -7,6 +7,7 @@ RTOL = {"cuda": 1e-4, "xpu": 1e-3} ATOL = {"cuda": 1e-5, "xpu": 1e-4} + def move_to_device(obj, device): """Recursively move tensors in nested batch structures to ``device``.""" if torch.is_tensor(obj): From 6c40e1f571397a3878bfe04ed2c2489ea6d55d08 Mon Sep 17 00:00:00 2001 From: Sameer Sheorey Date: Thu, 20 Aug 2026 22:35:20 +0200 Subject: [PATCH 10/14] Install libegl1 for Open3D wheel import in Ubuntu CI. --- .github/workflows/ubuntu.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/workflows/ubuntu.yml b/.github/workflows/ubuntu.yml index 335552cd1..d7542e7da 100644 --- a/.github/workflows/ubuntu.yml +++ b/.github/workflows/ubuntu.yml @@ -26,6 +26,9 @@ jobs: uses: actions/setup-python@v5 with: python-version: "3.12" + # open3d / open3d_cpu wheels link EGL for offscreen rendering (GUI=ON). + - name: Install Open3D runtime deps + run: sudo apt-get update && sudo apt-get install --yes libegl1 - name: Run Open3D-ML tests (CPU wheel, no torch parity) env: GH_TOKEN: ${{ github.token }} From 91218da1adf00b02385ef3f84334b46b332038f8 Mon Sep 17 00:00:00 2001 From: Sameer Sheorey Date: Thu, 20 Aug 2026 22:49:06 +0200 Subject: [PATCH 11/14] pytest --- ci/run_ci.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ci/run_ci.sh b/ci/run_ci.sh index 83a4bda3e..796b8fffd 100755 --- a/ci/run_ci.sh +++ b/ci/run_ci.sh @@ -86,7 +86,7 @@ echo python -m venv open3d_test.venv # shellcheck disable=SC1091 source open3d_test.venv/bin/activate -python -m pip install -U pip=="${PIP_VER}" +python -m pip install -U pip=="${PIP_VER}" pytest python -m pip install "${WHEEL_PATH}" echo "3. Sanity-check the installed package" From 942bbc903994a928e411aa4a5f44f675069607f4 Mon Sep 17 00:00:00 2001 From: Sameer Sheorey Date: Thu, 20 Aug 2026 23:20:03 +0200 Subject: [PATCH 12/14] also run torch tests on github CI. simplify CI --- .github/workflows/ubuntu.yml | 2 +- ci/run_ci.sh | 67 +++++------------------------------- docs/howtos.md | 18 +++------- tests/test_models_torch.py | 5 +-- 4 files changed, 17 insertions(+), 75 deletions(-) diff --git a/.github/workflows/ubuntu.yml b/.github/workflows/ubuntu.yml index d7542e7da..5217a8003 100644 --- a/.github/workflows/ubuntu.yml +++ b/.github/workflows/ubuntu.yml @@ -29,7 +29,7 @@ jobs: # open3d / open3d_cpu wheels link EGL for offscreen rendering (GUI=ON). - name: Install Open3D runtime deps run: sudo apt-get update && sudo apt-get install --yes libegl1 - - name: Run Open3D-ML tests (CPU wheel, no torch parity) + - name: Run Open3D-ML tests (CPU wheel) env: GH_TOKEN: ${{ github.token }} run: ./ci/run_ci.sh cpu diff --git a/ci/run_ci.sh b/ci/run_ci.sh index 796b8fffd..08af22c27 100755 --- a/ci/run_ci.sh +++ b/ci/run_ci.sh @@ -4,21 +4,17 @@ # # Usage: ./ci/run_ci.sh [cpu|cuda|xpu] # -# cpu — open3d_cpu wheel, PyTorch CPU; integration + TF tests only (no torch -# CPU/accelerator parity). Used on GitHub Actions. -# cuda — open3d (CUDA) wheel, PyTorch+cu126; full suite including -# tests/test_models_torch.py parity (requires NVIDIA GPU). -# xpu — open3d_xpu wheel, PyTorch+XPU; full suite including parity -# (requires Intel GPU; torch.xpu.is_available()). +# cpu — open3d_cpu wheel + requirements-torch.txt +# cuda — default open3d manylinux wheel + requirements-torch-cuda.txt +# xpu — open3d_xpu wheel + requirements-torch-xpu.txt # -# Parity tests (tests/test_models_torch.py) are intentionally omitted for the -# cpu variant: GitHub-hosted runners have no GPU, and parity needs a real -# accelerator. See docs/howtos.md. +# Pytest skips (parity, accelerator-only ops, missing ops) are handled in the +# test modules. See docs/howtos.md. set -euo pipefail usage() { - sed -n '2,16p' "$0" | sed 's/^# \?//' + sed -n '2,12p' "$0" | sed 's/^# \?//' echo echo "Example: ./ci/run_ci.sh cpu" exit "${1:-0}" @@ -43,25 +39,20 @@ case "${BACKEND}" in cpu) WHEEL_GLOB="open3d_cpu-*-${PY_TAG}-${PY_TAG}-manylinux*_x86_64.whl" TORCH_REQUIREMENTS="requirements-torch.txt" - INCLUDE_PARITY_TESTS=false ;; cuda) - # Default manylinux wheel (not open3d_cpu / open3d_xpu). WHEEL_GLOB="open3d-[0-9]*-${PY_TAG}-${PY_TAG}-manylinux*_x86_64.whl" TORCH_REQUIREMENTS="requirements-torch-cuda.txt" - INCLUDE_PARITY_TESTS=true ;; xpu) WHEEL_GLOB="open3d_xpu-*-${PY_TAG}-${PY_TAG}-manylinux*_x86_64.whl" TORCH_REQUIREMENTS="requirements-torch-xpu.txt" - INCLUDE_PARITY_TESTS=true ;; esac echo "Open3D-ML CI backend: ${BACKEND}" echo " wheel pattern: ${WHEEL_GLOB}" echo " torch requirements: ${TORCH_REQUIREMENTS}" -echo " torch parity tests (test_models_torch.py): ${INCLUDE_PARITY_TESTS}" echo echo "1. Download the latest Open3D devel wheel from ${OPEN3D_REPO}@${RELEASE_TAG}" @@ -91,14 +82,7 @@ python -m pip install "${WHEEL_PATH}" echo "3. Sanity-check the installed package" echo -python -W default -c " -import open3d -print('Installed:', open3d) -print('BUILD_PYTORCH_OPS:', open3d._build_config['BUILD_PYTORCH_OPS']) -print('BUILD_SYCL_MODULE:', open3d._build_config.get('BUILD_SYCL_MODULE')) -print('CUDA available:', open3d.core.cuda.is_available()) -print('SYCL available:', open3d.core.sycl.is_available()) -" +python -W default -c "import open3d; print('Installed:', open3d)" echo "4. Install Open3D-ML dependencies" echo @@ -106,43 +90,10 @@ export PATH_TO_OPEN3D_ML="$PWD" python -m pip install -r requirements.txt -r "${TORCH_REQUIREMENTS}" \ -r requirements-tensorflow.txt -echo "4b. PyTorch accelerator visibility" -echo -python -c " -import torch -print('torch:', torch.__version__) -print('torch.cuda.is_available():', torch.cuda.is_available()) -if hasattr(torch, 'xpu'): - print('torch.xpu.is_available():', torch.xpu.is_available()) -" - -if [[ "${INCLUDE_PARITY_TESTS}" == true ]]; then - python -c " -import open3d as o3d -import torch -import sys -backend = '${BACKEND}' -if backend == 'cuda' and not torch.cuda.is_available(): - sys.exit('cuda CI variant requires torch.cuda.is_available()') -if backend == 'xpu' and not (hasattr(torch, 'xpu') and torch.xpu.is_available()): - sys.exit('xpu CI variant requires torch.xpu.is_available()') -print('Accelerator check passed for', backend) -" -fi - -if [[ "${INCLUDE_PARITY_TESTS}" == true ]]; then - TEST_TARGETS=(tests) -else - TEST_TARGETS=( - tests/test_integration.py - tests/test_models_tf.py - ) -fi - run_test_suite() { - echo "Running: ./tests/run_tests.sh ${TEST_TARGETS[*]}" + echo "Running: ./tests/run_tests.sh tests" echo "Add --randomly-seed=SEED via pytest env if reproducing order." - ./tests/run_tests.sh "${TEST_TARGETS[@]}" + ./tests/run_tests.sh tests } echo "5. Run the Open3D-ML pytest suite against the installed wheel" diff --git a/docs/howtos.md b/docs/howtos.md index cd1eb57e0..13640cf39 100644 --- a/docs/howtos.md +++ b/docs/howtos.md @@ -280,18 +280,8 @@ Run the full suite locally with: ### Note on GitHub Actions CI GitHub-hosted runners have no NVIDIA or Intel GPU. CI runs `./ci/run_ci.sh cpu`, -which installs the `open3d_cpu` wheel and PyTorch CPU, then runs integration and -TensorFlow model tests only. **Torch CPU/accelerator parity** (`tests/test_models_torch.py`) -is not part of CPU CI. +which installs the `open3d_cpu` wheel and PyTorch CPU, then runs the full pytest +tree. Individual tests skip when an op backend or accelerator is unavailable. -Run parity locally (or on GPU machines) with: - -```bash -./ci/run_ci.sh cuda # NVIDIA GPU + open3d CUDA wheel -./ci/run_ci.sh xpu # Intel GPU + open3d_xpu wheel -``` - -Both `cuda` and `xpu` variants install the matching PyTorch build and run the -full test tree, including `test_models_torch.py`. The `cpu` variant skips those -parity tests because they require a real accelerator and are not meaningful on -CPU-only hosts. \ No newline at end of file +Run `./ci/run_ci.sh cuda` or `./ci/run_ci.sh xpu` locally or on GPU machines to +exercise CUDA/XPU wheels and PyTorch builds. \ No newline at end of file diff --git a/tests/test_models_torch.py b/tests/test_models_torch.py index b8651a051..000dbdff4 100644 --- a/tests/test_models_torch.py +++ b/tests/test_models_torch.py @@ -33,8 +33,9 @@ RandLANet from a config (no forward pass). Parity tests need ``BUILD_PYTORCH_OPS`` and a CUDA or XPU device for the -accelerator half. CPU CI (``./ci/run_ci.sh cpu``) does not run this file; use -``./ci/run_ci.sh cuda`` or ``xpu`` locally for the full matrix. +accelerator half; without a GPU, ``assert_cpu_accelerator_parity`` runs CPU only. +CPU CI (``./ci/run_ci.sh cpu``) runs the same torch model tests with parity +skipped on GPU-less runners; use ``./ci/run_ci.sh cuda`` or ``xpu`` for full parity. """ import copy From 237fd023e628d6ed613c78d6202cabc99ba5f31d Mon Sep 17 00:00:00 2001 From: Sameer Sheorey Date: Fri, 21 Aug 2026 01:26:24 +0200 Subject: [PATCH 13/14] Fix review threads and Ubuntu CI for ss/xpu. Use device_index for distributed CUDA set_device, device-specific sync fallbacks in parity tests, drop dead TF cuda:N parsing, and gate SYCL IoU kernels on non-CPU SYCL devices. CI sets OPEN3D_ML_ROOT so pytest uses this checkout's PointTransformer until the wheel bundle catches up. Co-authored-by: Cursor --- ci/run_ci.sh | 12 ++++-------- docs/howtos.md | 5 +++-- ml3d/metrics/__init__.py | 17 +++++++++++++++-- ml3d/torch/pipelines/base_pipeline.py | 2 +- scripts/run_pipeline.py | 5 +---- tests/test_models_torch.py | 2 +- tests/torch_backend_parity.py | 13 +++++++++++-- 7 files changed, 36 insertions(+), 20 deletions(-) diff --git a/ci/run_ci.sh b/ci/run_ci.sh index 08af22c27..968d593d4 100755 --- a/ci/run_ci.sh +++ b/ci/run_ci.sh @@ -90,21 +90,17 @@ export PATH_TO_OPEN3D_ML="$PWD" python -m pip install -r requirements.txt -r "${TORCH_REQUIREMENTS}" \ -r requirements-tensorflow.txt +# Load ml3d from this checkout (wheel _ml3d may lag main-devel until the next Open3D release). +export OPEN3D_ML_ROOT="${PATH_TO_OPEN3D_ML}" + run_test_suite() { echo "Running: ./tests/run_tests.sh tests" echo "Add --randomly-seed=SEED via pytest env if reproducing order." ./tests/run_tests.sh tests } -echo "5. Run the Open3D-ML pytest suite against the installed wheel" -echo -run_test_suite - -echo "6. Also verify the OPEN3D_ML_ROOT dev-mode path (models loaded from this" -echo " checkout instead of the wheel bundle)" +echo "5. Run the Open3D-ML pytest suite (open3d wheel + ml3d from OPEN3D_ML_ROOT)" echo -export OPEN3D_ML_ROOT="${PATH_TO_OPEN3D_ML}" run_test_suite -unset OPEN3D_ML_ROOT deactivate diff --git a/docs/howtos.md b/docs/howtos.md index 13640cf39..c8cae564a 100644 --- a/docs/howtos.md +++ b/docs/howtos.md @@ -280,8 +280,9 @@ Run the full suite locally with: ### Note on GitHub Actions CI GitHub-hosted runners have no NVIDIA or Intel GPU. CI runs `./ci/run_ci.sh cpu`, -which installs the `open3d_cpu` wheel and PyTorch CPU, then runs the full pytest -tree. Individual tests skip when an op backend or accelerator is unavailable. +which installs the `open3d_cpu` wheel and PyTorch CPU, sets `OPEN3D_ML_ROOT` to +this checkout (so model code matches the PR), then runs the full pytest tree. +Individual tests skip when an op backend or accelerator is unavailable. Run `./ci/run_ci.sh cuda` or `./ci/run_ci.sh xpu` locally or on GPU machines to exercise CUDA/XPU wheels and PyTorch builds. \ No newline at end of file diff --git a/ml3d/metrics/__init__.py b/ml3d/metrics/__init__.py index 8eb80189e..8f04c601b 100644 --- a/ml3d/metrics/__init__.py +++ b/ml3d/metrics/__init__.py @@ -1,11 +1,24 @@ import open3d + +def _sycl_accelerator_available(): + """True when Open3D sees a non-CPU SYCL device (e.g. Intel GPU), not SYCL-on-CPU.""" + o3c = open3d.core + if not o3c.sycl.is_available(): + return False + for device in o3c.sycl.get_available_devices(): + props = o3c.sycl.get_device_properties(device) + if props.device_type != "cpu": + return True + return False + + if open3d.core.cuda.device_count() > 0: # Open3D is built with CUDA and the machine has a CUDA device. from open3d.ml.contrib import iou_bev_cuda as iou_bev from open3d.ml.contrib import iou_3d_cuda as iou_3d -elif open3d.core.sycl.device_count() > 0: - # Open3D is built with SYCL and the machine has a SYCL (XPU) device. +elif _sycl_accelerator_available(): + # Open3D SYCL build with an accelerator-class SYCL device (not CPU-only SYCL). from open3d.ml.contrib import iou_bev_sycl as iou_bev from open3d.ml.contrib import iou_3d_sycl as iou_3d else: diff --git a/ml3d/torch/pipelines/base_pipeline.py b/ml3d/torch/pipelines/base_pipeline.py index 36a904af8..2f1edfd86 100644 --- a/ml3d/torch/pipelines/base_pipeline.py +++ b/ml3d/torch/pipelines/base_pipeline.py @@ -87,7 +87,7 @@ def __init__(self, if hasattr(torch, 'accelerator'): torch.accelerator.set_device_index(device_index) elif self.device.type == 'cuda': - torch.cuda.set_device(self.device) + torch.cuda.set_device(device_index) else: self.device = torch.device('cuda') diff --git a/scripts/run_pipeline.py b/scripts/run_pipeline.py index bea54bfcd..b0c477539 100644 --- a/scripts/run_pipeline.py +++ b/scripts/run_pipeline.py @@ -120,13 +120,10 @@ def main(): tf.config.set_visible_devices(gpus[0], 'GPU') elif device == 'xpu': tf.config.set_visible_devices([], 'GPU') - elif ':' in device: - idx = device.split(':')[1] - tf.config.set_visible_devices(gpus[int(idx)], 'GPU') else: raise ValueError( f"Unsupported TensorFlow device {device!r}; " - "use cpu, cuda, or cuda:N.") + "use cpu, cuda, or xpu (set --device_ids for a specific GPU).") except RuntimeError as e: print(e) diff --git a/tests/test_models_torch.py b/tests/test_models_torch.py index 000dbdff4..9c0219d7f 100644 --- a/tests/test_models_torch.py +++ b/tests/test_models_torch.py @@ -69,7 +69,7 @@ "this model (see test comment).") _accel = None -if o3d.core.cuda.is_available(): +if o3d.core.cuda.is_available() and torch.cuda.is_available(): _accel = torch.device('cuda') elif o3d.core.sycl.is_available() and torch.xpu.is_available(): # o3d.core.sycl.is_available() is True whenever Open3D's SYCL module was diff --git a/tests/torch_backend_parity.py b/tests/torch_backend_parity.py index 5281d9660..526ee5015 100644 --- a/tests/torch_backend_parity.py +++ b/tests/torch_backend_parity.py @@ -30,6 +30,15 @@ def collect_grads(module): } +def _synchronize_accel(accel_type): + if hasattr(torch, "accelerator"): + torch.accelerator.synchronize() + elif accel_type == "cuda": + torch.cuda.synchronize() + elif accel_type == "xpu" and hasattr(torch, "xpu"): + torch.xpu.synchronize() + + def assert_cpu_accelerator_parity(run_on_device, atol=None, grad_atol=None): """Run one forward + backward pass per device and compare outputs and grads. @@ -39,7 +48,7 @@ def assert_cpu_accelerator_parity(run_on_device, atol=None, grad_atol=None): """ cpu_output, cpu_model = run_on_device(torch.device("cpu")) - if o3d.core.cuda.is_available(): + if o3d.core.cuda.is_available() and torch.cuda.is_available(): accel = torch.device('cuda') elif o3d.core.sycl.is_available() and torch.xpu.is_available(): # o3d.core.sycl.is_available() is True whenever Open3D's SYCL module was @@ -52,7 +61,7 @@ def assert_cpu_accelerator_parity(run_on_device, atol=None, grad_atol=None): return cpu_output, cpu_model accel_output, accel_model = run_on_device(accel) - torch.accelerator.synchronize() + _synchronize_accel(accel.type) rtol = RTOL[accel.type] atol = ATOL[accel.type] if atol is None else atol From 631f0e88e551440d351fcae47cf885314cfd102f Mon Sep 17 00:00:00 2001 From: Sameer Sheorey Date: Fri, 21 Aug 2026 01:30:44 +0200 Subject: [PATCH 14/14] style: wrap run_pipeline ValueError message for yapf. Co-authored-by: Cursor --- scripts/run_pipeline.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/scripts/run_pipeline.py b/scripts/run_pipeline.py index b0c477539..b008d48ad 100644 --- a/scripts/run_pipeline.py +++ b/scripts/run_pipeline.py @@ -123,7 +123,8 @@ def main(): else: raise ValueError( f"Unsupported TensorFlow device {device!r}; " - "use cpu, cuda, or xpu (set --device_ids for a specific GPU).") + "use cpu, cuda, or xpu (set --device_ids for a " + "specific GPU).") except RuntimeError as e: print(e)