diff --git a/.github/workflows/ubuntu.yml b/.github/workflows/ubuntu.yml index d09e9e827..5217a8003 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,14 @@ 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 + # 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) + env: + GH_TOKEN: ${{ github.token }} + 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 efc33cc00..968d593d4 100755 --- a/ci/run_ci.sh +++ b/ci/run_ci.sh @@ -1,66 +1,106 @@ #!/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 + requirements-torch.txt +# cuda — default open3d manylinux wheel + requirements-torch-cuda.txt +# xpu — open3d_xpu wheel + requirements-torch-xpu.txt +# +# Pytest skips (parity, accelerator-only ops, missing ops) are handled in the +# test modules. See docs/howtos.md. set -euo pipefail -NPROC=${NPROC:?'env var must be set to number of available CPUs.'} +usage() { + sed -n '2,12p' "$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. Prepare the Open3D-ML repo and install dependencies -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 +case "${BACKEND}" in + cpu) + WHEEL_GLOB="open3d_cpu-*-${PY_TAG}-${PY_TAG}-manylinux*_x86_64.whl" + TORCH_REQUIREMENTS="requirements-torch.txt" + ;; + cuda) + WHEEL_GLOB="open3d-[0-9]*-${PY_TAG}-${PY_TAG}-manylinux*_x86_64.whl" + TORCH_REQUIREMENTS="requirements-torch-cuda.txt" + ;; + xpu) + WHEEL_GLOB="open3d_xpu-*-${PY_TAG}-${PY_TAG}-manylinux*_x86_64.whl" + TORCH_REQUIREMENTS="requirements-torch-xpu.txt" + ;; +esac -echo 2. clone Open3D and install dependencies +echo "Open3D-ML CI backend: ${BACKEND}" +echo " wheel pattern: ${WHEEL_GLOB}" +echo " torch requirements: ${TORCH_REQUIREMENTS}" 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 +echo "1. Download the latest Open3D devel wheel from ${OPEN3D_REPO}@${RELEASE_TAG}" +echo +gh release download "${RELEASE_TAG}" \ + --repo "${OPEN3D_REPO}" \ + --pattern "${WHEEL_GLOB}" \ + --dir . \ + --clobber +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 3. Configure for bundling the Open3D-ML part +echo "2. Install the wheel in a fresh virtual environment" 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 \ - .. +python -m venv open3d_test.venv +# shellcheck disable=SC1091 +source open3d_test.venv/bin/activate +python -m pip install -U pip=="${PIP_VER}" pytest +python -m pip install "${WHEEL_PATH}" -echo 4. Build and install wheel +echo "3. Sanity-check the installed package" echo -make -j"$NPROC" install-pip-package +python -W default -c "import open3d; print('Installed:', open3d)" -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 "4. Install Open3D-ML dependencies" 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 +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 "... now do the same but in dev mode by setting OPEN3D_ML_ROOT" +echo "5. Run the Open3D-ML pytest suite (open3d wheel + ml3d from OPEN3D_ML_ROOT)" 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 -unset OPEN3D_ML_ROOT +run_test_suite -popd +deactivate diff --git a/docs/howtos.md b/docs/howtos.md index ed5e60eab..c8cae564a 100644 --- a/docs/howtos.md +++ b/docs/howtos.md @@ -257,4 +257,32 @@ 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, 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 d4e8e4d48..8f04c601b 100644 --- a/ml3d/metrics/__init__.py +++ b/ml3d/metrics/__init__.py @@ -1,9 +1,26 @@ 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 _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: 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 a28293e19..130d877b8 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. @@ -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,11 @@ 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().to(device), 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/ml3d/torch/models/pvcnn.py b/ml3d/torch/models/pvcnn.py index 13908bddd..1374c88b5 100644 --- a/ml3d/torch/models/pvcnn.py +++ b/ml3d/torch/models/pvcnn.py @@ -10,7 +10,10 @@ 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 +from ..utils.torch_utils import default_training_device + +if pytorch_ops_built(): from open3d.ml.torch.ops import trilinear_devoxelize_forward, trilinear_devoxelize_backward @@ -84,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, @@ -93,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, @@ -288,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 f466868b9..2f1edfd86 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: @@ -57,7 +62,18 @@ 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.") @@ -66,7 +82,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(device_index) else: self.device = torch.device('cuda') diff --git a/ml3d/torch/pipelines/object_detection.py b/ml3d/torch/pipelines/object_detection.py index 892d86154..e79311ae2 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 @@ -32,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, @@ -336,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 @@ -523,6 +524,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..807b73707 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 @@ -71,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. @@ -95,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): @@ -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/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/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/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/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/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/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 diff --git a/scripts/run_pipeline.py b/scripts/run_pipeline.py index 895f470f7..b008d48ad 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,13 @@ def main(): "Multi-GPU training with TensorFlow is not yet implemented." ) tf.config.set_visible_devices(gpus[0], 'GPU') + elif device == 'xpu': + tf.config.set_visible_devices([], 'GPU') else: - idx = device.split(':')[1] - tf.config.set_visible_devices(gpus[int(idx)], 'GPU') + raise ValueError( + f"Unsupported TensorFlow device {device!r}; " + "use cpu, cuda, or xpu (set --device_ids for a " + "specific GPU).") except RuntimeError as e: print(e) @@ -225,7 +230,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/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_tf.py similarity index 51% rename from tests/test_models.py rename to tests/test_models_tf.py index 45dd8e171..4eeede463 100644 --- a/tests/test_models.py +++ b/tests/test_models_tf.py @@ -1,16 +1,15 @@ -import pytest import os + import numpy as np import open3d as o3d -try: - import torch -except ImportError: - torch = None +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 = '.' + base = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) try: import tensorflow as tf @@ -27,52 +26,10 @@ try: from open3d.ml.torch.models import OpenVINOModel openvino_available = True -except: +except Exception: openvino_available = False -@pytest.mark.skipif("not o3d._build_config['BUILD_PYTORCH_OPS']") -def test_randlanet_torch(): - import open3d.ml.torch as ml3d - - 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']])) - } - out = net(inputs).detach().numpy() - - assert out.shape == (1, 5000, 10) - - @pytest.mark.skipif("not o3d._build_config['BUILD_TENSORFLOW_OPS']") def test_randlanet_tf(): import open3d.ml.tf as ml3d @@ -114,45 +71,6 @@ def test_randlanet_tf(): 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 - - 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'} - 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 - - if openvino_available: - 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 - - @pytest.mark.skipif("not o3d._build_config['BUILD_TENSORFLOW_OPS']") def test_kpconv_tf(): import open3d.ml.tf as ml3d @@ -201,47 +119,12 @@ def test_kpconv_tf(): 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 - - 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, - 'bounding_boxes': [], - } - data = net.preprocess(data, {'split': 'test'}) - data = net.transform(data, {'split': 'test'}) - data = batcher.collate_fn([{'data': data, 'attr': {'split': 'test'}}]) - - net.eval() - with torch.no_grad(): - results = net(data) - boxes = net.inference_end(results, data) - assert type(boxes) == list - - if openvino_available: - ov_net = ml3d.models.OpenVINOModel(net) - ov_results = ov_net(data) - - for out, ref in zip(ov_results, results): - 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_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') diff --git a/tests/test_models_torch.py b/tests/test_models_torch.py new file mode 100644 index 000000000..9c0219d7f --- /dev/null +++ b/tests/test_models_torch.py @@ -0,0 +1,557 @@ +"""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 (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 | Yes | Yes | +| 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; 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 +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() 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 + # 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( + "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 +def test_pointtransformer_torch(): + import open3d.ml.torch as ml3d + + np.random.seed(66) + torch.manual_seed(66) + + 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 = 8192 + 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'} + 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='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 +@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 new file mode 100644 index 000000000..526ee5015 --- /dev/null +++ b/tests/torch_backend_parity.py @@ -0,0 +1,84 @@ +"""CPU vs CUDA / XPU parity helpers for Open3D-ML PyTorch model tests.""" + +import open3d as o3d +import torch + +# 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``.""" + 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 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 _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. + + ``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. + """ + cpu_output, cpu_model = run_on_device(torch.device("cpu")) + + 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 + # 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 + + accel_output, accel_model = run_on_device(accel) + _synchronize_accel(accel.type) + + 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