Commit ·
568c4c1
1
Parent(s): cf3870d
Upload folder using huggingface_hub (part 30)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +22 -0
- pace_revision/.venv-pace/lib/python3.11/site-packages/torch-2.9.1+cu128.dist-info/METADATA +634 -0
- pace_revision/.venv-pace/lib/python3.11/site-packages/torch-2.9.1+cu128.dist-info/RECORD +0 -0
- pace_revision/.venv-pace/lib/python3.11/site-packages/torch-2.9.1+cu128.dist-info/WHEEL +5 -0
- pace_revision/.venv-pace/lib/python3.11/site-packages/torch-2.9.1+cu128.dist-info/entry_points.txt +6 -0
- pace_revision/.venv-pace/lib/python3.11/site-packages/torch-2.9.1+cu128.dist-info/licenses/LICENSE +0 -0
- pace_revision/.venv-pace/lib/python3.11/site-packages/torch-2.9.1+cu128.dist-info/licenses/NOTICE +456 -0
- pace_revision/.venv-pace/lib/python3.11/site-packages/torch-2.9.1+cu128.dist-info/top_level.txt +3 -0
- pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/common_dtype.py +227 -0
- pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/common_fsdp.py +1580 -0
- pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/common_jit.py +323 -0
- pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/common_methods_invocations.py +0 -0
- pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/common_mkldnn.py +113 -0
- pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/common_modules.py +0 -0
- pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/common_mps.py +850 -0
- pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/common_nn.py +0 -0
- pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/common_optimizers.py +2309 -0
- pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/common_pruning.py +385 -0
- pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/common_quantization.py +0 -0
- pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/common_quantized.py +588 -0
- pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/common_subclass.py +346 -0
- pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/common_utils.py +0 -0
- pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/composite_compliance.py +608 -0
- pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/custom_op_db.py +585 -0
- pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/custom_tensor.py +158 -0
- pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/data/__init__.py +1 -0
- pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/data/network1.py +10 -0
- pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/data/network2.py +11 -0
- pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/dist_utils.py +199 -0
- pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/distributed/__init__.py +0 -0
- pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/distributed/__pycache__/__init__.cpython-311.pyc +0 -0
- pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/distributed/__pycache__/fake_pg.cpython-311.pyc +0 -0
- pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/distributed/_shard/__init__.py +1 -0
- pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/distributed/_shard/sharded_tensor/__init__.py +103 -0
- pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/distributed/_shard/sharded_tensor/_test_ops_common.py +137 -0
- pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/distributed/_shard/sharded_tensor/_test_st_common.py +56 -0
- pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/distributed/_shard/test_common.py +41 -0
- pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/distributed/_tensor/__init__.py +0 -0
- pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/distributed/_tensor/common_dtensor.py +683 -0
- pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/distributed/checkpoint_utils.py +193 -0
- pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/distributed/common_state_dict.py +170 -0
- pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/distributed/ddp_under_dist_autograd_test.py +746 -0
- pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/distributed/distributed_test.py +0 -0
- pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/distributed/distributed_utils.py +70 -0
- pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/distributed/fake_pg.py +32 -0
- pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/distributed/multi_threaded_pg.py +573 -0
- pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/distributed/nn/__init__.py +0 -0
- pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/distributed/nn/api/__init__.py +0 -0
- pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/distributed/nn/api/remote_module_test.py +752 -0
- pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/distributed/rpc/__init__.py +0 -0
.gitattributes
CHANGED
|
@@ -489,3 +489,25 @@ pace_revision/.venv-pace/lib/python3.11/site-packages/torch/nn/parallel/__pycach
|
|
| 489 |
pace_revision/.venv-pace/lib/python3.11/site-packages/torch/onnx/_internal/torchscript_exporter/__pycache__/symbolic_helper.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
|
| 490 |
pace_revision/.venv-pace/lib/python3.11/site-packages/torch/onnx/_internal/torchscript_exporter/__pycache__/symbolic_opset9.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
|
| 491 |
pace_revision/.venv-pace/lib/python3.11/site-packages/torch/optim/__pycache__/lr_scheduler.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 489 |
pace_revision/.venv-pace/lib/python3.11/site-packages/torch/onnx/_internal/torchscript_exporter/__pycache__/symbolic_helper.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
|
| 490 |
pace_revision/.venv-pace/lib/python3.11/site-packages/torch/onnx/_internal/torchscript_exporter/__pycache__/symbolic_opset9.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
|
| 491 |
pace_revision/.venv-pace/lib/python3.11/site-packages/torch/optim/__pycache__/lr_scheduler.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
|
| 492 |
+
pace_revision/.venv-pace/lib/python3.11/site-packages/torchgen/__pycache__/model.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
|
| 493 |
+
pace_revision/.venv-pace/lib/python3.11/site-packages/triton/FileCheck filter=lfs diff=lfs merge=lfs -text
|
| 494 |
+
pace_revision/.venv-pace/lib/python3.11/site-packages/triton/_C/libproton.so filter=lfs diff=lfs merge=lfs -text
|
| 495 |
+
pace_revision/.venv-pace/lib/python3.11/site-packages/triton/_C/libtriton.so filter=lfs diff=lfs merge=lfs -text
|
| 496 |
+
pace_revision/.venv-pace/lib/python3.11/site-packages/triton/backends/amd/lib/ockl.bc filter=lfs diff=lfs merge=lfs -text
|
| 497 |
+
pace_revision/.venv-pace/lib/python3.11/site-packages/triton/backends/amd/lib/ocml.bc filter=lfs diff=lfs merge=lfs -text
|
| 498 |
+
pace_revision/.venv-pace/lib/python3.11/site-packages/triton/backends/nvidia/bin/cuobjdump filter=lfs diff=lfs merge=lfs -text
|
| 499 |
+
pace_revision/.venv-pace/lib/python3.11/site-packages/triton/backends/nvidia/bin/nvdisasm filter=lfs diff=lfs merge=lfs -text
|
| 500 |
+
pace_revision/.venv-pace/lib/python3.11/site-packages/triton/backends/nvidia/bin/ptxas filter=lfs diff=lfs merge=lfs -text
|
| 501 |
+
pace_revision/.venv-pace/lib/python3.11/site-packages/triton/backends/nvidia/lib/cupti/libcheckpoint.so filter=lfs diff=lfs merge=lfs -text
|
| 502 |
+
pace_revision/.venv-pace/lib/python3.11/site-packages/triton/backends/nvidia/lib/cupti/libcupti.so filter=lfs diff=lfs merge=lfs -text
|
| 503 |
+
pace_revision/.venv-pace/lib/python3.11/site-packages/triton/backends/nvidia/lib/cupti/libcupti.so.12 filter=lfs diff=lfs merge=lfs -text
|
| 504 |
+
pace_revision/.venv-pace/lib/python3.11/site-packages/triton/backends/nvidia/lib/cupti/libcupti.so.2025.1.1 filter=lfs diff=lfs merge=lfs -text
|
| 505 |
+
pace_revision/.venv-pace/lib/python3.11/site-packages/triton/backends/nvidia/lib/cupti/libcupti_static.a filter=lfs diff=lfs merge=lfs -text
|
| 506 |
+
pace_revision/.venv-pace/lib/python3.11/site-packages/triton/backends/nvidia/lib/cupti/libnvperf_host.so filter=lfs diff=lfs merge=lfs -text
|
| 507 |
+
pace_revision/.venv-pace/lib/python3.11/site-packages/triton/backends/nvidia/lib/cupti/libnvperf_host_static.a filter=lfs diff=lfs merge=lfs -text
|
| 508 |
+
pace_revision/.venv-pace/lib/python3.11/site-packages/triton/backends/nvidia/lib/cupti/libnvperf_target.so filter=lfs diff=lfs merge=lfs -text
|
| 509 |
+
pace_revision/.venv-pace/lib/python3.11/site-packages/triton/backends/nvidia/lib/cupti/libpcsamplingutil.so filter=lfs diff=lfs merge=lfs -text
|
| 510 |
+
pace_revision/.venv-pace/lib/python3.11/site-packages/triton/backends/nvidia/lib/libdevice.10.bc filter=lfs diff=lfs merge=lfs -text
|
| 511 |
+
pace_revision/.venv-pace/lib/python3.11/site-packages/triton/instrumentation/libGPUInstrumentationTestLib.so filter=lfs diff=lfs merge=lfs -text
|
| 512 |
+
pace_revision/.venv-pace/lib/python3.11/site-packages/triton/instrumentation/libPrintLoadStoreMemSpaces.so filter=lfs diff=lfs merge=lfs -text
|
| 513 |
+
pace_revision/.venv-pace/lib/python3.11/site-packages/triton/language/__pycache__/core.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
|
pace_revision/.venv-pace/lib/python3.11/site-packages/torch-2.9.1+cu128.dist-info/METADATA
ADDED
|
@@ -0,0 +1,634 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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+
Name: torch
|
| 3 |
+
Version: 2.9.1+cu128
|
| 4 |
+
Summary: Tensors and Dynamic neural networks in Python with strong GPU acceleration
|
| 5 |
+
Author-email: PyTorch Team <packages@pytorch.org>
|
| 6 |
+
License: BSD-3-Clause
|
| 7 |
+
Project-URL: Homepage, https://pytorch.org
|
| 8 |
+
Project-URL: Repository, https://github.com/pytorch/pytorch
|
| 9 |
+
Project-URL: Documentation, https://pytorch.org/docs
|
| 10 |
+
Project-URL: Issue Tracker, https://github.com/pytorch/pytorch/issues
|
| 11 |
+
Project-URL: Forum, https://discuss.pytorch.org
|
| 12 |
+
Keywords: pytorch,machine learning
|
| 13 |
+
Classifier: Development Status :: 5 - Production/Stable
|
| 14 |
+
Classifier: Intended Audience :: Developers
|
| 15 |
+
Classifier: Intended Audience :: Education
|
| 16 |
+
Classifier: Intended Audience :: Science/Research
|
| 17 |
+
Classifier: Topic :: Scientific/Engineering
|
| 18 |
+
Classifier: Topic :: Scientific/Engineering :: Mathematics
|
| 19 |
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
| 20 |
+
Classifier: Topic :: Software Development
|
| 21 |
+
Classifier: Topic :: Software Development :: Libraries
|
| 22 |
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
| 23 |
+
Classifier: Programming Language :: C++
|
| 24 |
+
Classifier: Programming Language :: Python :: 3 :: Only
|
| 25 |
+
Classifier: Programming Language :: Python :: 3.10
|
| 26 |
+
Classifier: Programming Language :: Python :: 3.11
|
| 27 |
+
Classifier: Programming Language :: Python :: 3.12
|
| 28 |
+
Classifier: Programming Language :: Python :: 3.13
|
| 29 |
+
Classifier: Programming Language :: Python :: 3.14
|
| 30 |
+
Requires-Python: >=3.10
|
| 31 |
+
Description-Content-Type: text/markdown
|
| 32 |
+
License-File: LICENSE
|
| 33 |
+
License-File: NOTICE
|
| 34 |
+
Requires-Dist: filelock
|
| 35 |
+
Requires-Dist: typing-extensions>=4.10.0
|
| 36 |
+
Requires-Dist: setuptools; python_version >= "3.12"
|
| 37 |
+
Requires-Dist: sympy>=1.13.3
|
| 38 |
+
Requires-Dist: networkx>=2.5.1
|
| 39 |
+
Requires-Dist: jinja2
|
| 40 |
+
Requires-Dist: fsspec>=0.8.5
|
| 41 |
+
Requires-Dist: nvidia-cuda-nvrtc-cu12==12.8.93; platform_system == "Linux"
|
| 42 |
+
Requires-Dist: nvidia-cuda-runtime-cu12==12.8.90; platform_system == "Linux"
|
| 43 |
+
Requires-Dist: nvidia-cuda-cupti-cu12==12.8.90; platform_system == "Linux"
|
| 44 |
+
Requires-Dist: nvidia-cudnn-cu12==9.10.2.21; platform_system == "Linux"
|
| 45 |
+
Requires-Dist: nvidia-cublas-cu12==12.8.4.1; platform_system == "Linux"
|
| 46 |
+
Requires-Dist: nvidia-cufft-cu12==11.3.3.83; platform_system == "Linux"
|
| 47 |
+
Requires-Dist: nvidia-curand-cu12==10.3.9.90; platform_system == "Linux"
|
| 48 |
+
Requires-Dist: nvidia-cusolver-cu12==11.7.3.90; platform_system == "Linux"
|
| 49 |
+
Requires-Dist: nvidia-cusparse-cu12==12.5.8.93; platform_system == "Linux"
|
| 50 |
+
Requires-Dist: nvidia-cusparselt-cu12==0.7.1; platform_system == "Linux"
|
| 51 |
+
Requires-Dist: nvidia-nccl-cu12==2.27.5; platform_system == "Linux"
|
| 52 |
+
Requires-Dist: nvidia-nvshmem-cu12==3.3.20; platform_system == "Linux"
|
| 53 |
+
Requires-Dist: nvidia-nvtx-cu12==12.8.90; platform_system == "Linux"
|
| 54 |
+
Requires-Dist: nvidia-nvjitlink-cu12==12.8.93; platform_system == "Linux"
|
| 55 |
+
Requires-Dist: nvidia-cufile-cu12==1.13.1.3; platform_system == "Linux"
|
| 56 |
+
Requires-Dist: triton==3.5.1; platform_system == "Linux"
|
| 57 |
+
Provides-Extra: optree
|
| 58 |
+
Requires-Dist: optree>=0.13.0; extra == "optree"
|
| 59 |
+
Provides-Extra: opt-einsum
|
| 60 |
+
Requires-Dist: opt-einsum>=3.3; extra == "opt-einsum"
|
| 61 |
+
Provides-Extra: pyyaml
|
| 62 |
+
Requires-Dist: pyyaml; extra == "pyyaml"
|
| 63 |
+
Dynamic: license-file
|
| 64 |
+
Dynamic: requires-dist
|
| 65 |
+
|
| 66 |
+

|
| 67 |
+
|
| 68 |
+
--------------------------------------------------------------------------------
|
| 69 |
+
|
| 70 |
+
PyTorch is a Python package that provides two high-level features:
|
| 71 |
+
- Tensor computation (like NumPy) with strong GPU acceleration
|
| 72 |
+
- Deep neural networks built on a tape-based autograd system
|
| 73 |
+
|
| 74 |
+
You can reuse your favorite Python packages such as NumPy, SciPy, and Cython to extend PyTorch when needed.
|
| 75 |
+
|
| 76 |
+
Our trunk health (Continuous Integration signals) can be found at [hud.pytorch.org](https://hud.pytorch.org/ci/pytorch/pytorch/main).
|
| 77 |
+
|
| 78 |
+
<!-- toc -->
|
| 79 |
+
|
| 80 |
+
- [More About PyTorch](#more-about-pytorch)
|
| 81 |
+
- [A GPU-Ready Tensor Library](#a-gpu-ready-tensor-library)
|
| 82 |
+
- [Dynamic Neural Networks: Tape-Based Autograd](#dynamic-neural-networks-tape-based-autograd)
|
| 83 |
+
- [Python First](#python-first)
|
| 84 |
+
- [Imperative Experiences](#imperative-experiences)
|
| 85 |
+
- [Fast and Lean](#fast-and-lean)
|
| 86 |
+
- [Extensions Without Pain](#extensions-without-pain)
|
| 87 |
+
- [Installation](#installation)
|
| 88 |
+
- [Binaries](#binaries)
|
| 89 |
+
- [NVIDIA Jetson Platforms](#nvidia-jetson-platforms)
|
| 90 |
+
- [From Source](#from-source)
|
| 91 |
+
- [Prerequisites](#prerequisites)
|
| 92 |
+
- [NVIDIA CUDA Support](#nvidia-cuda-support)
|
| 93 |
+
- [AMD ROCm Support](#amd-rocm-support)
|
| 94 |
+
- [Intel GPU Support](#intel-gpu-support)
|
| 95 |
+
- [Get the PyTorch Source](#get-the-pytorch-source)
|
| 96 |
+
- [Install Dependencies](#install-dependencies)
|
| 97 |
+
- [Install PyTorch](#install-pytorch)
|
| 98 |
+
- [Adjust Build Options (Optional)](#adjust-build-options-optional)
|
| 99 |
+
- [Docker Image](#docker-image)
|
| 100 |
+
- [Using pre-built images](#using-pre-built-images)
|
| 101 |
+
- [Building the image yourself](#building-the-image-yourself)
|
| 102 |
+
- [Building the Documentation](#building-the-documentation)
|
| 103 |
+
- [Building a PDF](#building-a-pdf)
|
| 104 |
+
- [Previous Versions](#previous-versions)
|
| 105 |
+
- [Getting Started](#getting-started)
|
| 106 |
+
- [Resources](#resources)
|
| 107 |
+
- [Communication](#communication)
|
| 108 |
+
- [Releases and Contributing](#releases-and-contributing)
|
| 109 |
+
- [The Team](#the-team)
|
| 110 |
+
- [License](#license)
|
| 111 |
+
|
| 112 |
+
<!-- tocstop -->
|
| 113 |
+
|
| 114 |
+
## More About PyTorch
|
| 115 |
+
|
| 116 |
+
[Learn the basics of PyTorch](https://pytorch.org/tutorials/beginner/basics/intro.html)
|
| 117 |
+
|
| 118 |
+
At a granular level, PyTorch is a library that consists of the following components:
|
| 119 |
+
|
| 120 |
+
| Component | Description |
|
| 121 |
+
| ---- | --- |
|
| 122 |
+
| [**torch**](https://pytorch.org/docs/stable/torch.html) | A Tensor library like NumPy, with strong GPU support |
|
| 123 |
+
| [**torch.autograd**](https://pytorch.org/docs/stable/autograd.html) | A tape-based automatic differentiation library that supports all differentiable Tensor operations in torch |
|
| 124 |
+
| [**torch.jit**](https://pytorch.org/docs/stable/jit.html) | A compilation stack (TorchScript) to create serializable and optimizable models from PyTorch code |
|
| 125 |
+
| [**torch.nn**](https://pytorch.org/docs/stable/nn.html) | A neural networks library deeply integrated with autograd designed for maximum flexibility |
|
| 126 |
+
| [**torch.multiprocessing**](https://pytorch.org/docs/stable/multiprocessing.html) | Python multiprocessing, but with magical memory sharing of torch Tensors across processes. Useful for data loading and Hogwild training |
|
| 127 |
+
| [**torch.utils**](https://pytorch.org/docs/stable/data.html) | DataLoader and other utility functions for convenience |
|
| 128 |
+
|
| 129 |
+
Usually, PyTorch is used either as:
|
| 130 |
+
|
| 131 |
+
- A replacement for NumPy to use the power of GPUs.
|
| 132 |
+
- A deep learning research platform that provides maximum flexibility and speed.
|
| 133 |
+
|
| 134 |
+
Elaborating Further:
|
| 135 |
+
|
| 136 |
+
### A GPU-Ready Tensor Library
|
| 137 |
+
|
| 138 |
+
If you use NumPy, then you have used Tensors (a.k.a. ndarray).
|
| 139 |
+
|
| 140 |
+

|
| 141 |
+
|
| 142 |
+
PyTorch provides Tensors that can live either on the CPU or the GPU and accelerates the
|
| 143 |
+
computation by a huge amount.
|
| 144 |
+
|
| 145 |
+
We provide a wide variety of tensor routines to accelerate and fit your scientific computation needs
|
| 146 |
+
such as slicing, indexing, mathematical operations, linear algebra, reductions.
|
| 147 |
+
And they are fast!
|
| 148 |
+
|
| 149 |
+
### Dynamic Neural Networks: Tape-Based Autograd
|
| 150 |
+
|
| 151 |
+
PyTorch has a unique way of building neural networks: using and replaying a tape recorder.
|
| 152 |
+
|
| 153 |
+
Most frameworks such as TensorFlow, Theano, Caffe, and CNTK have a static view of the world.
|
| 154 |
+
One has to build a neural network and reuse the same structure again and again.
|
| 155 |
+
Changing the way the network behaves means that one has to start from scratch.
|
| 156 |
+
|
| 157 |
+
With PyTorch, we use a technique called reverse-mode auto-differentiation, which allows you to
|
| 158 |
+
change the way your network behaves arbitrarily with zero lag or overhead. Our inspiration comes
|
| 159 |
+
from several research papers on this topic, as well as current and past work such as
|
| 160 |
+
[torch-autograd](https://github.com/twitter/torch-autograd),
|
| 161 |
+
[autograd](https://github.com/HIPS/autograd),
|
| 162 |
+
[Chainer](https://chainer.org), etc.
|
| 163 |
+
|
| 164 |
+
While this technique is not unique to PyTorch, it's one of the fastest implementations of it to date.
|
| 165 |
+
You get the best of speed and flexibility for your crazy research.
|
| 166 |
+
|
| 167 |
+

|
| 168 |
+
|
| 169 |
+
### Python First
|
| 170 |
+
|
| 171 |
+
PyTorch is not a Python binding into a monolithic C++ framework.
|
| 172 |
+
It is built to be deeply integrated into Python.
|
| 173 |
+
You can use it naturally like you would use [NumPy](https://www.numpy.org/) / [SciPy](https://www.scipy.org/) / [scikit-learn](https://scikit-learn.org) etc.
|
| 174 |
+
You can write your new neural network layers in Python itself, using your favorite libraries
|
| 175 |
+
and use packages such as [Cython](https://cython.org/) and [Numba](http://numba.pydata.org/).
|
| 176 |
+
Our goal is to not reinvent the wheel where appropriate.
|
| 177 |
+
|
| 178 |
+
### Imperative Experiences
|
| 179 |
+
|
| 180 |
+
PyTorch is designed to be intuitive, linear in thought, and easy to use.
|
| 181 |
+
When you execute a line of code, it gets executed. There isn't an asynchronous view of the world.
|
| 182 |
+
When you drop into a debugger or receive error messages and stack traces, understanding them is straightforward.
|
| 183 |
+
The stack trace points to exactly where your code was defined.
|
| 184 |
+
We hope you never spend hours debugging your code because of bad stack traces or asynchronous and opaque execution engines.
|
| 185 |
+
|
| 186 |
+
### Fast and Lean
|
| 187 |
+
|
| 188 |
+
PyTorch has minimal framework overhead. We integrate acceleration libraries
|
| 189 |
+
such as [Intel MKL](https://software.intel.com/mkl) and NVIDIA ([cuDNN](https://developer.nvidia.com/cudnn), [NCCL](https://developer.nvidia.com/nccl)) to maximize speed.
|
| 190 |
+
At the core, its CPU and GPU Tensor and neural network backends
|
| 191 |
+
are mature and have been tested for years.
|
| 192 |
+
|
| 193 |
+
Hence, PyTorch is quite fast — whether you run small or large neural networks.
|
| 194 |
+
|
| 195 |
+
The memory usage in PyTorch is extremely efficient compared to Torch or some of the alternatives.
|
| 196 |
+
We've written custom memory allocators for the GPU to make sure that
|
| 197 |
+
your deep learning models are maximally memory efficient.
|
| 198 |
+
This enables you to train bigger deep learning models than before.
|
| 199 |
+
|
| 200 |
+
### Extensions Without Pain
|
| 201 |
+
|
| 202 |
+
Writing new neural network modules, or interfacing with PyTorch's Tensor API was designed to be straightforward
|
| 203 |
+
and with minimal abstractions.
|
| 204 |
+
|
| 205 |
+
You can write new neural network layers in Python using the torch API
|
| 206 |
+
[or your favorite NumPy-based libraries such as SciPy](https://pytorch.org/tutorials/advanced/numpy_extensions_tutorial.html).
|
| 207 |
+
|
| 208 |
+
If you want to write your layers in C/C++, we provide a convenient extension API that is efficient and with minimal boilerplate.
|
| 209 |
+
No wrapper code needs to be written. You can see [a tutorial here](https://pytorch.org/tutorials/advanced/cpp_extension.html) and [an example here](https://github.com/pytorch/extension-cpp).
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
## Installation
|
| 213 |
+
|
| 214 |
+
### Binaries
|
| 215 |
+
Commands to install binaries via Conda or pip wheels are on our website: [https://pytorch.org/get-started/locally/](https://pytorch.org/get-started/locally/)
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
#### NVIDIA Jetson Platforms
|
| 219 |
+
|
| 220 |
+
Python wheels for NVIDIA's Jetson Nano, Jetson TX1/TX2, Jetson Xavier NX/AGX, and Jetson AGX Orin are provided [here](https://forums.developer.nvidia.com/t/pytorch-for-jetson-version-1-10-now-available/72048) and the L4T container is published [here](https://catalog.ngc.nvidia.com/orgs/nvidia/containers/l4t-pytorch)
|
| 221 |
+
|
| 222 |
+
They require JetPack 4.2 and above, and [@dusty-nv](https://github.com/dusty-nv) and [@ptrblck](https://github.com/ptrblck) are maintaining them.
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
### From Source
|
| 226 |
+
|
| 227 |
+
#### Prerequisites
|
| 228 |
+
If you are installing from source, you will need:
|
| 229 |
+
- Python 3.9 or later
|
| 230 |
+
- A compiler that fully supports C++17, such as clang or gcc (gcc 9.4.0 or newer is required, on Linux)
|
| 231 |
+
- Visual Studio or Visual Studio Build Tool (Windows only)
|
| 232 |
+
|
| 233 |
+
\* PyTorch CI uses Visual C++ BuildTools, which come with Visual Studio Enterprise,
|
| 234 |
+
Professional, or Community Editions. You can also install the build tools from
|
| 235 |
+
https://visualstudio.microsoft.com/visual-cpp-build-tools/. The build tools *do not*
|
| 236 |
+
come with Visual Studio Code by default.
|
| 237 |
+
|
| 238 |
+
An example of environment setup is shown below:
|
| 239 |
+
|
| 240 |
+
* Linux:
|
| 241 |
+
|
| 242 |
+
```bash
|
| 243 |
+
$ source <CONDA_INSTALL_DIR>/bin/activate
|
| 244 |
+
$ conda create -y -n <CONDA_NAME>
|
| 245 |
+
$ conda activate <CONDA_NAME>
|
| 246 |
+
```
|
| 247 |
+
|
| 248 |
+
* Windows:
|
| 249 |
+
|
| 250 |
+
```bash
|
| 251 |
+
$ source <CONDA_INSTALL_DIR>\Scripts\activate.bat
|
| 252 |
+
$ conda create -y -n <CONDA_NAME>
|
| 253 |
+
$ conda activate <CONDA_NAME>
|
| 254 |
+
$ call "C:\Program Files\Microsoft Visual Studio\<VERSION>\Community\VC\Auxiliary\Build\vcvarsall.bat" x64
|
| 255 |
+
```
|
| 256 |
+
|
| 257 |
+
A conda environment is not required. You can also do a PyTorch build in a
|
| 258 |
+
standard virtual environment, e.g., created with tools like `uv`, provided
|
| 259 |
+
your system has installed all the necessary dependencies unavailable as pip
|
| 260 |
+
packages (e.g., CUDA, MKL.)
|
| 261 |
+
|
| 262 |
+
##### NVIDIA CUDA Support
|
| 263 |
+
If you want to compile with CUDA support, [select a supported version of CUDA from our support matrix](https://pytorch.org/get-started/locally/), then install the following:
|
| 264 |
+
- [NVIDIA CUDA](https://developer.nvidia.com/cuda-downloads)
|
| 265 |
+
- [NVIDIA cuDNN](https://developer.nvidia.com/cudnn) v8.5 or above
|
| 266 |
+
- [Compiler](https://gist.github.com/ax3l/9489132) compatible with CUDA
|
| 267 |
+
|
| 268 |
+
Note: You could refer to the [cuDNN Support Matrix](https://docs.nvidia.com/deeplearning/cudnn/backend/latest/reference/support-matrix.html) for cuDNN versions with the various supported CUDA, CUDA driver, and NVIDIA hardware.
|
| 269 |
+
|
| 270 |
+
If you want to disable CUDA support, export the environment variable `USE_CUDA=0`.
|
| 271 |
+
Other potentially useful environment variables may be found in `setup.py`. If
|
| 272 |
+
CUDA is installed in a non-standard location, set PATH so that the nvcc you
|
| 273 |
+
want to use can be found (e.g., `export PATH=/usr/local/cuda-12.8/bin:$PATH`).
|
| 274 |
+
|
| 275 |
+
If you are building for NVIDIA's Jetson platforms (Jetson Nano, TX1, TX2, AGX Xavier), Instructions to install PyTorch for Jetson Nano are [available here](https://devtalk.nvidia.com/default/topic/1049071/jetson-nano/pytorch-for-jetson-nano/)
|
| 276 |
+
|
| 277 |
+
##### AMD ROCm Support
|
| 278 |
+
If you want to compile with ROCm support, install
|
| 279 |
+
- [AMD ROCm](https://rocm.docs.amd.com/en/latest/deploy/linux/quick_start.html) 4.0 and above installation
|
| 280 |
+
- ROCm is currently supported only for Linux systems.
|
| 281 |
+
|
| 282 |
+
By default the build system expects ROCm to be installed in `/opt/rocm`. If ROCm is installed in a different directory, the `ROCM_PATH` environment variable must be set to the ROCm installation directory. The build system automatically detects the AMD GPU architecture. Optionally, the AMD GPU architecture can be explicitly set with the `PYTORCH_ROCM_ARCH` environment variable [AMD GPU architecture](https://rocm.docs.amd.com/projects/install-on-linux/en/latest/reference/system-requirements.html#supported-gpus)
|
| 283 |
+
|
| 284 |
+
If you want to disable ROCm support, export the environment variable `USE_ROCM=0`.
|
| 285 |
+
Other potentially useful environment variables may be found in `setup.py`.
|
| 286 |
+
|
| 287 |
+
##### Intel GPU Support
|
| 288 |
+
If you want to compile with Intel GPU support, follow these
|
| 289 |
+
- [PyTorch Prerequisites for Intel GPUs](https://www.intel.com/content/www/us/en/developer/articles/tool/pytorch-prerequisites-for-intel-gpus.html) instructions.
|
| 290 |
+
- Intel GPU is supported for Linux and Windows.
|
| 291 |
+
|
| 292 |
+
If you want to disable Intel GPU support, export the environment variable `USE_XPU=0`.
|
| 293 |
+
Other potentially useful environment variables may be found in `setup.py`.
|
| 294 |
+
|
| 295 |
+
#### Get the PyTorch Source
|
| 296 |
+
|
| 297 |
+
```bash
|
| 298 |
+
git clone https://github.com/pytorch/pytorch
|
| 299 |
+
cd pytorch
|
| 300 |
+
# if you are updating an existing checkout
|
| 301 |
+
git submodule sync
|
| 302 |
+
git submodule update --init --recursive
|
| 303 |
+
```
|
| 304 |
+
|
| 305 |
+
#### Install Dependencies
|
| 306 |
+
|
| 307 |
+
**Common**
|
| 308 |
+
|
| 309 |
+
```bash
|
| 310 |
+
# Run this command from the PyTorch directory after cloning the source code using the “Get the PyTorch Source“ section above
|
| 311 |
+
pip install --group dev
|
| 312 |
+
```
|
| 313 |
+
|
| 314 |
+
**On Linux**
|
| 315 |
+
|
| 316 |
+
```bash
|
| 317 |
+
pip install mkl-static mkl-include
|
| 318 |
+
# CUDA only: Add LAPACK support for the GPU if needed
|
| 319 |
+
# magma installation: run with active conda environment. specify CUDA version to install
|
| 320 |
+
.ci/docker/common/install_magma_conda.sh 12.4
|
| 321 |
+
|
| 322 |
+
# (optional) If using torch.compile with inductor/triton, install the matching version of triton
|
| 323 |
+
# Run from the pytorch directory after cloning
|
| 324 |
+
# For Intel GPU support, please explicitly `export USE_XPU=1` before running command.
|
| 325 |
+
make triton
|
| 326 |
+
```
|
| 327 |
+
|
| 328 |
+
**On MacOS**
|
| 329 |
+
|
| 330 |
+
```bash
|
| 331 |
+
# Add this package on intel x86 processor machines only
|
| 332 |
+
pip install mkl-static mkl-include
|
| 333 |
+
# Add these packages if torch.distributed is needed
|
| 334 |
+
conda install pkg-config libuv
|
| 335 |
+
```
|
| 336 |
+
|
| 337 |
+
**On Windows**
|
| 338 |
+
|
| 339 |
+
```bash
|
| 340 |
+
pip install mkl-static mkl-include
|
| 341 |
+
# Add these packages if torch.distributed is needed.
|
| 342 |
+
# Distributed package support on Windows is a prototype feature and is subject to changes.
|
| 343 |
+
conda install -c conda-forge libuv
|
| 344 |
+
```
|
| 345 |
+
|
| 346 |
+
#### Install PyTorch
|
| 347 |
+
|
| 348 |
+
**On Linux**
|
| 349 |
+
|
| 350 |
+
If you're compiling for AMD ROCm then first run this command:
|
| 351 |
+
|
| 352 |
+
```bash
|
| 353 |
+
# Only run this if you're compiling for ROCm
|
| 354 |
+
python tools/amd_build/build_amd.py
|
| 355 |
+
```
|
| 356 |
+
|
| 357 |
+
Install PyTorch
|
| 358 |
+
|
| 359 |
+
```bash
|
| 360 |
+
export CMAKE_PREFIX_PATH="${CONDA_PREFIX:-'$(dirname $(which conda))/../'}:${CMAKE_PREFIX_PATH}"
|
| 361 |
+
python -m pip install --no-build-isolation -v -e .
|
| 362 |
+
```
|
| 363 |
+
|
| 364 |
+
**On macOS**
|
| 365 |
+
|
| 366 |
+
```bash
|
| 367 |
+
python -m pip install --no-build-isolation -v -e .
|
| 368 |
+
```
|
| 369 |
+
|
| 370 |
+
**On Windows**
|
| 371 |
+
|
| 372 |
+
If you want to build legacy python code, please refer to [Building on legacy code and CUDA](https://github.com/pytorch/pytorch/blob/main/CONTRIBUTING.md#building-on-legacy-code-and-cuda)
|
| 373 |
+
|
| 374 |
+
**CPU-only builds**
|
| 375 |
+
|
| 376 |
+
In this mode PyTorch computations will run on your CPU, not your GPU.
|
| 377 |
+
|
| 378 |
+
```cmd
|
| 379 |
+
python -m pip install --no-build-isolation -v -e .
|
| 380 |
+
```
|
| 381 |
+
|
| 382 |
+
Note on OpenMP: The desired OpenMP implementation is Intel OpenMP (iomp). In order to link against iomp, you'll need to manually download the library and set up the building environment by tweaking `CMAKE_INCLUDE_PATH` and `LIB`. The instruction [here](https://github.com/pytorch/pytorch/blob/main/docs/source/notes/windows.rst#building-from-source) is an example for setting up both MKL and Intel OpenMP. Without these configurations for CMake, Microsoft Visual C OpenMP runtime (vcomp) will be used.
|
| 383 |
+
|
| 384 |
+
**CUDA based build**
|
| 385 |
+
|
| 386 |
+
In this mode PyTorch computations will leverage your GPU via CUDA for faster number crunching
|
| 387 |
+
|
| 388 |
+
[NVTX](https://docs.nvidia.com/gameworks/content/gameworkslibrary/nvtx/nvidia_tools_extension_library_nvtx.htm) is needed to build Pytorch with CUDA.
|
| 389 |
+
NVTX is a part of CUDA distributive, where it is called "Nsight Compute". To install it onto an already installed CUDA run CUDA installation once again and check the corresponding checkbox.
|
| 390 |
+
Make sure that CUDA with Nsight Compute is installed after Visual Studio.
|
| 391 |
+
|
| 392 |
+
Currently, VS 2017 / 2019, and Ninja are supported as the generator of CMake. If `ninja.exe` is detected in `PATH`, then Ninja will be used as the default generator, otherwise, it will use VS 2017 / 2019.
|
| 393 |
+
<br/> If Ninja is selected as the generator, the latest MSVC will get selected as the underlying toolchain.
|
| 394 |
+
|
| 395 |
+
Additional libraries such as
|
| 396 |
+
[Magma](https://developer.nvidia.com/magma), [oneDNN, a.k.a. MKLDNN or DNNL](https://github.com/oneapi-src/oneDNN), and [Sccache](https://github.com/mozilla/sccache) are often needed. Please refer to the [installation-helper](https://github.com/pytorch/pytorch/tree/main/.ci/pytorch/win-test-helpers/installation-helpers) to install them.
|
| 397 |
+
|
| 398 |
+
You can refer to the [build_pytorch.bat](https://github.com/pytorch/pytorch/blob/main/.ci/pytorch/win-test-helpers/build_pytorch.bat) script for some other environment variables configurations
|
| 399 |
+
|
| 400 |
+
```cmd
|
| 401 |
+
cmd
|
| 402 |
+
|
| 403 |
+
:: Set the environment variables after you have downloaded and unzipped the mkl package,
|
| 404 |
+
:: else CMake would throw an error as `Could NOT find OpenMP`.
|
| 405 |
+
set CMAKE_INCLUDE_PATH={Your directory}\mkl\include
|
| 406 |
+
set LIB={Your directory}\mkl\lib;%LIB%
|
| 407 |
+
|
| 408 |
+
:: Read the content in the previous section carefully before you proceed.
|
| 409 |
+
:: [Optional] If you want to override the underlying toolset used by Ninja and Visual Studio with CUDA, please run the following script block.
|
| 410 |
+
:: "Visual Studio 2019 Developer Command Prompt" will be run automatically.
|
| 411 |
+
:: Make sure you have CMake >= 3.12 before you do this when you use the Visual Studio generator.
|
| 412 |
+
set CMAKE_GENERATOR_TOOLSET_VERSION=14.27
|
| 413 |
+
set DISTUTILS_USE_SDK=1
|
| 414 |
+
for /f "usebackq tokens=*" %i in (`"%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe" -version [15^,17^) -products * -latest -property installationPath`) do call "%i\VC\Auxiliary\Build\vcvarsall.bat" x64 -vcvars_ver=%CMAKE_GENERATOR_TOOLSET_VERSION%
|
| 415 |
+
|
| 416 |
+
:: [Optional] If you want to override the CUDA host compiler
|
| 417 |
+
set CUDAHOSTCXX=C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.27.29110\bin\HostX64\x64\cl.exe
|
| 418 |
+
|
| 419 |
+
python -m pip install --no-build-isolation -v -e .
|
| 420 |
+
```
|
| 421 |
+
|
| 422 |
+
**Intel GPU builds**
|
| 423 |
+
|
| 424 |
+
In this mode PyTorch with Intel GPU support will be built.
|
| 425 |
+
|
| 426 |
+
Please make sure [the common prerequisites](#prerequisites) as well as [the prerequisites for Intel GPU](#intel-gpu-support) are properly installed and the environment variables are configured prior to starting the build. For build tool support, `Visual Studio 2022` is required.
|
| 427 |
+
|
| 428 |
+
Then PyTorch can be built with the command:
|
| 429 |
+
|
| 430 |
+
```cmd
|
| 431 |
+
:: CMD Commands:
|
| 432 |
+
:: Set the CMAKE_PREFIX_PATH to help find corresponding packages
|
| 433 |
+
:: %CONDA_PREFIX% only works after `conda activate custom_env`
|
| 434 |
+
|
| 435 |
+
if defined CMAKE_PREFIX_PATH (
|
| 436 |
+
set "CMAKE_PREFIX_PATH=%CONDA_PREFIX%\Library;%CMAKE_PREFIX_PATH%"
|
| 437 |
+
) else (
|
| 438 |
+
set "CMAKE_PREFIX_PATH=%CONDA_PREFIX%\Library"
|
| 439 |
+
)
|
| 440 |
+
|
| 441 |
+
python -m pip install --no-build-isolation -v -e .
|
| 442 |
+
```
|
| 443 |
+
|
| 444 |
+
##### Adjust Build Options (Optional)
|
| 445 |
+
|
| 446 |
+
You can adjust the configuration of cmake variables optionally (without building first), by doing
|
| 447 |
+
the following. For example, adjusting the pre-detected directories for CuDNN or BLAS can be done
|
| 448 |
+
with such a step.
|
| 449 |
+
|
| 450 |
+
On Linux
|
| 451 |
+
|
| 452 |
+
```bash
|
| 453 |
+
export CMAKE_PREFIX_PATH="${CONDA_PREFIX:-'$(dirname $(which conda))/../'}:${CMAKE_PREFIX_PATH}"
|
| 454 |
+
CMAKE_ONLY=1 python setup.py build
|
| 455 |
+
ccmake build # or cmake-gui build
|
| 456 |
+
```
|
| 457 |
+
|
| 458 |
+
On macOS
|
| 459 |
+
|
| 460 |
+
```bash
|
| 461 |
+
export CMAKE_PREFIX_PATH="${CONDA_PREFIX:-'$(dirname $(which conda))/../'}:${CMAKE_PREFIX_PATH}"
|
| 462 |
+
MACOSX_DEPLOYMENT_TARGET=11.0 CMAKE_ONLY=1 python setup.py build
|
| 463 |
+
ccmake build # or cmake-gui build
|
| 464 |
+
```
|
| 465 |
+
|
| 466 |
+
### Docker Image
|
| 467 |
+
|
| 468 |
+
#### Using pre-built images
|
| 469 |
+
|
| 470 |
+
You can also pull a pre-built docker image from Docker Hub and run with docker v19.03+
|
| 471 |
+
|
| 472 |
+
```bash
|
| 473 |
+
docker run --gpus all --rm -ti --ipc=host pytorch/pytorch:latest
|
| 474 |
+
```
|
| 475 |
+
|
| 476 |
+
Please note that PyTorch uses shared memory to share data between processes, so if torch multiprocessing is used (e.g.
|
| 477 |
+
for multithreaded data loaders) the default shared memory segment size that container runs with is not enough, and you
|
| 478 |
+
should increase shared memory size either with `--ipc=host` or `--shm-size` command line options to `nvidia-docker run`.
|
| 479 |
+
|
| 480 |
+
#### Building the image yourself
|
| 481 |
+
|
| 482 |
+
**NOTE:** Must be built with a docker version > 18.06
|
| 483 |
+
|
| 484 |
+
The `Dockerfile` is supplied to build images with CUDA 11.1 support and cuDNN v8.
|
| 485 |
+
You can pass `PYTHON_VERSION=x.y` make variable to specify which Python version is to be used by Miniconda, or leave it
|
| 486 |
+
unset to use the default.
|
| 487 |
+
|
| 488 |
+
```bash
|
| 489 |
+
make -f docker.Makefile
|
| 490 |
+
# images are tagged as docker.io/${your_docker_username}/pytorch
|
| 491 |
+
```
|
| 492 |
+
|
| 493 |
+
You can also pass the `CMAKE_VARS="..."` environment variable to specify additional CMake variables to be passed to CMake during the build.
|
| 494 |
+
See [setup.py](./setup.py) for the list of available variables.
|
| 495 |
+
|
| 496 |
+
```bash
|
| 497 |
+
make -f docker.Makefile
|
| 498 |
+
```
|
| 499 |
+
|
| 500 |
+
### Building the Documentation
|
| 501 |
+
|
| 502 |
+
To build documentation in various formats, you will need [Sphinx](http://www.sphinx-doc.org)
|
| 503 |
+
and the pytorch_sphinx_theme2.
|
| 504 |
+
|
| 505 |
+
Before you build the documentation locally, ensure `torch` is
|
| 506 |
+
installed in your environment. For small fixes, you can install the
|
| 507 |
+
nightly version as described in [Getting Started](https://pytorch.org/get-started/locally/).
|
| 508 |
+
|
| 509 |
+
For more complex fixes, such as adding a new module and docstrings for
|
| 510 |
+
the new module, you might need to install torch [from source](#from-source).
|
| 511 |
+
See [Docstring Guidelines](https://github.com/pytorch/pytorch/wiki/Docstring-Guidelines)
|
| 512 |
+
for docstring conventions.
|
| 513 |
+
|
| 514 |
+
```bash
|
| 515 |
+
cd docs/
|
| 516 |
+
pip install -r requirements.txt
|
| 517 |
+
make html
|
| 518 |
+
make serve
|
| 519 |
+
```
|
| 520 |
+
|
| 521 |
+
Run `make` to get a list of all available output formats.
|
| 522 |
+
|
| 523 |
+
If you get a katex error run `npm install katex`. If it persists, try
|
| 524 |
+
`npm install -g katex`
|
| 525 |
+
|
| 526 |
+
> [!NOTE]
|
| 527 |
+
> If you installed `nodejs` with a different package manager (e.g.,
|
| 528 |
+
> `conda`) then `npm` will probably install a version of `katex` that is not
|
| 529 |
+
> compatible with your version of `nodejs` and doc builds will fail.
|
| 530 |
+
> A combination of versions that is known to work is `node@6.13.1` and
|
| 531 |
+
> `katex@0.13.18`. To install the latter with `npm` you can run
|
| 532 |
+
> ```npm install -g katex@0.13.18```
|
| 533 |
+
|
| 534 |
+
> [!NOTE]
|
| 535 |
+
> If you see a numpy incompatibility error, run:
|
| 536 |
+
> ```
|
| 537 |
+
> pip install 'numpy<2'
|
| 538 |
+
> ```
|
| 539 |
+
|
| 540 |
+
When you make changes to the dependencies run by CI, edit the
|
| 541 |
+
`.ci/docker/requirements-docs.txt` file.
|
| 542 |
+
|
| 543 |
+
#### Building a PDF
|
| 544 |
+
|
| 545 |
+
To compile a PDF of all PyTorch documentation, ensure you have
|
| 546 |
+
`texlive` and LaTeX installed. On macOS, you can install them using:
|
| 547 |
+
|
| 548 |
+
```
|
| 549 |
+
brew install --cask mactex
|
| 550 |
+
```
|
| 551 |
+
|
| 552 |
+
To create the PDF:
|
| 553 |
+
|
| 554 |
+
1. Run:
|
| 555 |
+
|
| 556 |
+
```
|
| 557 |
+
make latexpdf
|
| 558 |
+
```
|
| 559 |
+
|
| 560 |
+
This will generate the necessary files in the `build/latex` directory.
|
| 561 |
+
|
| 562 |
+
2. Navigate to this directory and execute:
|
| 563 |
+
|
| 564 |
+
```
|
| 565 |
+
make LATEXOPTS="-interaction=nonstopmode"
|
| 566 |
+
```
|
| 567 |
+
|
| 568 |
+
This will produce a `pytorch.pdf` with the desired content. Run this
|
| 569 |
+
command one more time so that it generates the correct table
|
| 570 |
+
of contents and index.
|
| 571 |
+
|
| 572 |
+
> [!NOTE]
|
| 573 |
+
> To view the Table of Contents, switch to the **Table of Contents**
|
| 574 |
+
> view in your PDF viewer.
|
| 575 |
+
|
| 576 |
+
|
| 577 |
+
### Previous Versions
|
| 578 |
+
|
| 579 |
+
Installation instructions and binaries for previous PyTorch versions may be found
|
| 580 |
+
on [our website](https://pytorch.org/get-started/previous-versions).
|
| 581 |
+
|
| 582 |
+
|
| 583 |
+
## Getting Started
|
| 584 |
+
|
| 585 |
+
Three pointers to get you started:
|
| 586 |
+
- [Tutorials: get you started with understanding and using PyTorch](https://pytorch.org/tutorials/)
|
| 587 |
+
- [Examples: easy to understand PyTorch code across all domains](https://github.com/pytorch/examples)
|
| 588 |
+
- [The API Reference](https://pytorch.org/docs/)
|
| 589 |
+
- [Glossary](https://github.com/pytorch/pytorch/blob/main/GLOSSARY.md)
|
| 590 |
+
|
| 591 |
+
## Resources
|
| 592 |
+
|
| 593 |
+
* [PyTorch.org](https://pytorch.org/)
|
| 594 |
+
* [PyTorch Tutorials](https://pytorch.org/tutorials/)
|
| 595 |
+
* [PyTorch Examples](https://github.com/pytorch/examples)
|
| 596 |
+
* [PyTorch Models](https://pytorch.org/hub/)
|
| 597 |
+
* [Intro to Deep Learning with PyTorch from Udacity](https://www.udacity.com/course/deep-learning-pytorch--ud188)
|
| 598 |
+
* [Intro to Machine Learning with PyTorch from Udacity](https://www.udacity.com/course/intro-to-machine-learning-nanodegree--nd229)
|
| 599 |
+
* [Deep Neural Networks with PyTorch from Coursera](https://www.coursera.org/learn/deep-neural-networks-with-pytorch)
|
| 600 |
+
* [PyTorch Twitter](https://twitter.com/PyTorch)
|
| 601 |
+
* [PyTorch Blog](https://pytorch.org/blog/)
|
| 602 |
+
* [PyTorch YouTube](https://www.youtube.com/channel/UCWXI5YeOsh03QvJ59PMaXFw)
|
| 603 |
+
|
| 604 |
+
## Communication
|
| 605 |
+
* Forums: Discuss implementations, research, etc. https://discuss.pytorch.org
|
| 606 |
+
* GitHub Issues: Bug reports, feature requests, install issues, RFCs, thoughts, etc.
|
| 607 |
+
* Slack: The [PyTorch Slack](https://pytorch.slack.com/) hosts a primary audience of moderate to experienced PyTorch users and developers for general chat, online discussions, collaboration, etc. If you are a beginner looking for help, the primary medium is [PyTorch Forums](https://discuss.pytorch.org). If you need a slack invite, please fill this form: https://goo.gl/forms/PP1AGvNHpSaJP8to1
|
| 608 |
+
* Newsletter: No-noise, a one-way email newsletter with important announcements about PyTorch. You can sign-up here: https://eepurl.com/cbG0rv
|
| 609 |
+
* Facebook Page: Important announcements about PyTorch. https://www.facebook.com/pytorch
|
| 610 |
+
* For brand guidelines, please visit our website at [pytorch.org](https://pytorch.org/)
|
| 611 |
+
|
| 612 |
+
## Releases and Contributing
|
| 613 |
+
|
| 614 |
+
Typically, PyTorch has three minor releases a year. Please let us know if you encounter a bug by [filing an issue](https://github.com/pytorch/pytorch/issues).
|
| 615 |
+
|
| 616 |
+
We appreciate all contributions. If you are planning to contribute back bug-fixes, please do so without any further discussion.
|
| 617 |
+
|
| 618 |
+
If you plan to contribute new features, utility functions, or extensions to the core, please first open an issue and discuss the feature with us.
|
| 619 |
+
Sending a PR without discussion might end up resulting in a rejected PR because we might be taking the core in a different direction than you might be aware of.
|
| 620 |
+
|
| 621 |
+
To learn more about making a contribution to Pytorch, please see our [Contribution page](CONTRIBUTING.md). For more information about PyTorch releases, see [Release page](RELEASE.md).
|
| 622 |
+
|
| 623 |
+
## The Team
|
| 624 |
+
|
| 625 |
+
PyTorch is a community-driven project with several skillful engineers and researchers contributing to it.
|
| 626 |
+
|
| 627 |
+
PyTorch is currently maintained by [Soumith Chintala](http://soumith.ch), [Gregory Chanan](https://github.com/gchanan), [Dmytro Dzhulgakov](https://github.com/dzhulgakov), [Edward Yang](https://github.com/ezyang), [Alban Desmaison](https://github.com/albanD), [Piotr Bialecki](https://github.com/ptrblck) and [Nikita Shulga](https://github.com/malfet) with major contributions coming from hundreds of talented individuals in various forms and means.
|
| 628 |
+
A non-exhaustive but growing list needs to mention: [Trevor Killeen](https://github.com/killeent), [Sasank Chilamkurthy](https://github.com/chsasank), [Sergey Zagoruyko](https://github.com/szagoruyko), [Adam Lerer](https://github.com/adamlerer), [Francisco Massa](https://github.com/fmassa), [Alykhan Tejani](https://github.com/alykhantejani), [Luca Antiga](https://github.com/lantiga), [Alban Desmaison](https://github.com/albanD), [Andreas Koepf](https://github.com/andreaskoepf), [James Bradbury](https://github.com/jekbradbury), [Zeming Lin](https://github.com/ebetica), [Yuandong Tian](https://github.com/yuandong-tian), [Guillaume Lample](https://github.com/glample), [Marat Dukhan](https://github.com/Maratyszcza), [Natalia Gimelshein](https://github.com/ngimel), [Christian Sarofeen](https://github.com/csarofeen), [Martin Raison](https://github.com/martinraison), [Edward Yang](https://github.com/ezyang), [Zachary Devito](https://github.com/zdevito). <!-- codespell:ignore -->
|
| 629 |
+
|
| 630 |
+
Note: This project is unrelated to [hughperkins/pytorch](https://github.com/hughperkins/pytorch) with the same name. Hugh is a valuable contributor to the Torch community and has helped with many things Torch and PyTorch.
|
| 631 |
+
|
| 632 |
+
## License
|
| 633 |
+
|
| 634 |
+
PyTorch has a BSD-style license, as found in the [LICENSE](LICENSE) file.
|
pace_revision/.venv-pace/lib/python3.11/site-packages/torch-2.9.1+cu128.dist-info/RECORD
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
pace_revision/.venv-pace/lib/python3.11/site-packages/torch-2.9.1+cu128.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: setuptools (79.0.1)
|
| 3 |
+
Root-Is-Purelib: false
|
| 4 |
+
Tag: cp311-cp311-manylinux_2_28_x86_64
|
| 5 |
+
|
pace_revision/.venv-pace/lib/python3.11/site-packages/torch-2.9.1+cu128.dist-info/entry_points.txt
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[console_scripts]
|
| 2 |
+
torchfrtrace = tools.flight_recorder.fr_trace:main
|
| 3 |
+
torchrun = torch.distributed.run:main
|
| 4 |
+
|
| 5 |
+
[torchrun.logs_specs]
|
| 6 |
+
default = torch.distributed.elastic.multiprocessing:DefaultLogsSpecs
|
pace_revision/.venv-pace/lib/python3.11/site-packages/torch-2.9.1+cu128.dist-info/licenses/LICENSE
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
pace_revision/.venv-pace/lib/python3.11/site-packages/torch-2.9.1+cu128.dist-info/licenses/NOTICE
ADDED
|
@@ -0,0 +1,456 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
=======================================================================
|
| 2 |
+
Software under third_party
|
| 3 |
+
=======================================================================
|
| 4 |
+
Software libraries under third_party are provided as github submodule
|
| 5 |
+
links, and their content is not part of the Caffe2 codebase. Their
|
| 6 |
+
licences can be found under the respective software repositories.
|
| 7 |
+
|
| 8 |
+
=======================================================================
|
| 9 |
+
Earlier BSD License
|
| 10 |
+
=======================================================================
|
| 11 |
+
Early development of Caffe2 in 2015 and early 2016 is licensed under the
|
| 12 |
+
BSD license. The license is attached below:
|
| 13 |
+
|
| 14 |
+
All contributions by Facebook:
|
| 15 |
+
Copyright (c) 2016 Facebook Inc.
|
| 16 |
+
|
| 17 |
+
All contributions by Google:
|
| 18 |
+
Copyright (c) 2015 Google Inc.
|
| 19 |
+
All rights reserved.
|
| 20 |
+
|
| 21 |
+
All contributions by Yangqing Jia:
|
| 22 |
+
Copyright (c) 2015 Yangqing Jia
|
| 23 |
+
All rights reserved.
|
| 24 |
+
|
| 25 |
+
All contributions by Kakao Brain:
|
| 26 |
+
Copyright 2019-2020 Kakao Brain
|
| 27 |
+
|
| 28 |
+
All other contributions:
|
| 29 |
+
Copyright(c) 2015, 2016 the respective contributors
|
| 30 |
+
All rights reserved.
|
| 31 |
+
|
| 32 |
+
Redistribution and use in source and binary forms, with or without
|
| 33 |
+
modification, are permitted provided that the following conditions are met:
|
| 34 |
+
|
| 35 |
+
1. Redistributions of source code must retain the above copyright notice, this
|
| 36 |
+
list of conditions and the following disclaimer.
|
| 37 |
+
2. Redistributions in binary form must reproduce the above copyright notice,
|
| 38 |
+
this list of conditions and the following disclaimer in the documentation
|
| 39 |
+
and/or other materials provided with the distribution.
|
| 40 |
+
|
| 41 |
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
| 42 |
+
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
| 43 |
+
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
| 44 |
+
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
|
| 45 |
+
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
| 46 |
+
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
| 47 |
+
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
|
| 48 |
+
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
| 49 |
+
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
| 50 |
+
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
=======================================================================
|
| 54 |
+
Caffe's BSD License
|
| 55 |
+
=======================================================================
|
| 56 |
+
Some parts of the caffe2 code is derived from the original Caffe code, which is
|
| 57 |
+
created by Yangqing Jia and is now a BSD-licensed open-source project. The Caffe
|
| 58 |
+
license is as follows:
|
| 59 |
+
|
| 60 |
+
COPYRIGHT
|
| 61 |
+
|
| 62 |
+
All contributions by the University of California:
|
| 63 |
+
Copyright (c) 2014, The Regents of the University of California (Regents)
|
| 64 |
+
All rights reserved.
|
| 65 |
+
|
| 66 |
+
All other contributions:
|
| 67 |
+
Copyright (c) 2014, the respective contributors
|
| 68 |
+
All rights reserved.
|
| 69 |
+
|
| 70 |
+
Caffe uses a shared copyright model: each contributor holds copyright over
|
| 71 |
+
their contributions to Caffe. The project versioning records all such
|
| 72 |
+
contribution and copyright details. If a contributor wants to further mark
|
| 73 |
+
their specific copyright on a particular contribution, they should indicate
|
| 74 |
+
their copyright solely in the commit message of the change when it is
|
| 75 |
+
committed.
|
| 76 |
+
|
| 77 |
+
LICENSE
|
| 78 |
+
|
| 79 |
+
Redistribution and use in source and binary forms, with or without
|
| 80 |
+
modification, are permitted provided that the following conditions are met:
|
| 81 |
+
|
| 82 |
+
1. Redistributions of source code must retain the above copyright notice, this
|
| 83 |
+
list of conditions and the following disclaimer.
|
| 84 |
+
2. Redistributions in binary form must reproduce the above copyright notice,
|
| 85 |
+
this list of conditions and the following disclaimer in the documentation
|
| 86 |
+
and/or other materials provided with the distribution.
|
| 87 |
+
|
| 88 |
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
| 89 |
+
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
| 90 |
+
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
| 91 |
+
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
|
| 92 |
+
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
| 93 |
+
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
| 94 |
+
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
|
| 95 |
+
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
| 96 |
+
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
| 97 |
+
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
| 98 |
+
|
| 99 |
+
CONTRIBUTION AGREEMENT
|
| 100 |
+
|
| 101 |
+
By contributing to the BVLC/caffe repository through pull-request, comment,
|
| 102 |
+
or otherwise, the contributor releases their content to the
|
| 103 |
+
license and copyright terms herein.
|
| 104 |
+
|
| 105 |
+
=======================================================================
|
| 106 |
+
Caffe2's Apache License
|
| 107 |
+
=======================================================================
|
| 108 |
+
|
| 109 |
+
This repo contains Caffe2 code, which was previously licensed under
|
| 110 |
+
Apache License Version 2.0:
|
| 111 |
+
|
| 112 |
+
Apache License
|
| 113 |
+
Version 2.0, January 2004
|
| 114 |
+
http://www.apache.org/licenses/
|
| 115 |
+
|
| 116 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 117 |
+
|
| 118 |
+
1. Definitions.
|
| 119 |
+
|
| 120 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 121 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 122 |
+
|
| 123 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 124 |
+
the copyright owner that is granting the License.
|
| 125 |
+
|
| 126 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 127 |
+
other entities that control, are controlled by, or are under common
|
| 128 |
+
control with that entity. For the purposes of this definition,
|
| 129 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 130 |
+
direction or management of such entity, whether by contract or
|
| 131 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 132 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 133 |
+
|
| 134 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 135 |
+
exercising permissions granted by this License.
|
| 136 |
+
|
| 137 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 138 |
+
including but not limited to software source code, documentation
|
| 139 |
+
source, and configuration files.
|
| 140 |
+
|
| 141 |
+
"Object" form shall mean any form resulting from mechanical
|
| 142 |
+
transformation or translation of a Source form, including but
|
| 143 |
+
not limited to compiled object code, generated documentation,
|
| 144 |
+
and conversions to other media types.
|
| 145 |
+
|
| 146 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 147 |
+
Object form, made available under the License, as indicated by a
|
| 148 |
+
copyright notice that is included in or attached to the work
|
| 149 |
+
(an example is provided in the Appendix below).
|
| 150 |
+
|
| 151 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 152 |
+
form, that is based on (or derived from) the Work and for which the
|
| 153 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 154 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 155 |
+
of this License, Derivative Works shall not include works that remain
|
| 156 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 157 |
+
the Work and Derivative Works thereof.
|
| 158 |
+
|
| 159 |
+
"Contribution" shall mean any work of authorship, including
|
| 160 |
+
the original version of the Work and any modifications or additions
|
| 161 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 162 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 163 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 164 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 165 |
+
means any form of electronic, verbal, or written communication sent
|
| 166 |
+
to the Licensor or its representatives, including but not limited to
|
| 167 |
+
communication on electronic mailing lists, source code control systems,
|
| 168 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 169 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 170 |
+
excluding communication that is conspicuously marked or otherwise
|
| 171 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 172 |
+
|
| 173 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 174 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 175 |
+
subsequently incorporated within the Work.
|
| 176 |
+
|
| 177 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 178 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 179 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 180 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 181 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 182 |
+
Work and such Derivative Works in Source or Object form.
|
| 183 |
+
|
| 184 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 185 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 186 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 187 |
+
(except as stated in this section) patent license to make, have made,
|
| 188 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 189 |
+
where such license applies only to those patent claims licensable
|
| 190 |
+
by such Contributor that are necessarily infringed by their
|
| 191 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 192 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 193 |
+
institute patent litigation against any entity (including a
|
| 194 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 195 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 196 |
+
or contributory patent infringement, then any patent licenses
|
| 197 |
+
granted to You under this License for that Work shall terminate
|
| 198 |
+
as of the date such litigation is filed.
|
| 199 |
+
|
| 200 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 201 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 202 |
+
modifications, and in Source or Object form, provided that You
|
| 203 |
+
meet the following conditions:
|
| 204 |
+
|
| 205 |
+
(a) You must give any other recipients of the Work or
|
| 206 |
+
Derivative Works a copy of this License; and
|
| 207 |
+
|
| 208 |
+
(b) You must cause any modified files to carry prominent notices
|
| 209 |
+
stating that You changed the files; and
|
| 210 |
+
|
| 211 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 212 |
+
that You distribute, all copyright, patent, trademark, and
|
| 213 |
+
attribution notices from the Source form of the Work,
|
| 214 |
+
excluding those notices that do not pertain to any part of
|
| 215 |
+
the Derivative Works; and
|
| 216 |
+
|
| 217 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 218 |
+
distribution, then any Derivative Works that You distribute must
|
| 219 |
+
include a readable copy of the attribution notices contained
|
| 220 |
+
within such NOTICE file, excluding those notices that do not
|
| 221 |
+
pertain to any part of the Derivative Works, in at least one
|
| 222 |
+
of the following places: within a NOTICE text file distributed
|
| 223 |
+
as part of the Derivative Works; within the Source form or
|
| 224 |
+
documentation, if provided along with the Derivative Works; or,
|
| 225 |
+
within a display generated by the Derivative Works, if and
|
| 226 |
+
wherever such third-party notices normally appear. The contents
|
| 227 |
+
of the NOTICE file are for informational purposes only and
|
| 228 |
+
do not modify the License. You may add Your own attribution
|
| 229 |
+
notices within Derivative Works that You distribute, alongside
|
| 230 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 231 |
+
that such additional attribution notices cannot be construed
|
| 232 |
+
as modifying the License.
|
| 233 |
+
|
| 234 |
+
You may add Your own copyright statement to Your modifications and
|
| 235 |
+
may provide additional or different license terms and conditions
|
| 236 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 237 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 238 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 239 |
+
the conditions stated in this License.
|
| 240 |
+
|
| 241 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 242 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 243 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 244 |
+
this License, without any additional terms or conditions.
|
| 245 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 246 |
+
the terms of any separate license agreement you may have executed
|
| 247 |
+
with Licensor regarding such Contributions.
|
| 248 |
+
|
| 249 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 250 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 251 |
+
except as required for reasonable and customary use in describing the
|
| 252 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 253 |
+
|
| 254 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 255 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 256 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 257 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 258 |
+
implied, including, without limitation, any warranties or conditions
|
| 259 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 260 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 261 |
+
appropriateness of using or redistributing the Work and assume any
|
| 262 |
+
risks associated with Your exercise of permissions under this License.
|
| 263 |
+
|
| 264 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 265 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 266 |
+
unless required by applicable law (such as deliberate and grossly
|
| 267 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 268 |
+
liable to You for damages, including any direct, indirect, special,
|
| 269 |
+
incidental, or consequential damages of any character arising as a
|
| 270 |
+
result of this License or out of the use or inability to use the
|
| 271 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 272 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 273 |
+
other commercial damages or losses), even if such Contributor
|
| 274 |
+
has been advised of the possibility of such damages.
|
| 275 |
+
|
| 276 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 277 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 278 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 279 |
+
or other liability obligations and/or rights consistent with this
|
| 280 |
+
License. However, in accepting such obligations, You may act only
|
| 281 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 282 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 283 |
+
defend, and hold each Contributor harmless for any liability
|
| 284 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 285 |
+
of your accepting any such warranty or additional liability.
|
| 286 |
+
|
| 287 |
+
=======================================================================
|
| 288 |
+
Cephes's 3-Clause BSD License
|
| 289 |
+
=======================================================================
|
| 290 |
+
|
| 291 |
+
Code derived from implementations in the Cephes Math Library should mention
|
| 292 |
+
its derivation and reference the following license:
|
| 293 |
+
|
| 294 |
+
3-Clause BSD License for the Cephes Math Library
|
| 295 |
+
Copyright (c) 2018, Steven Moshier
|
| 296 |
+
All rights reserved.
|
| 297 |
+
|
| 298 |
+
Redistribution and use in source and binary forms, with or without
|
| 299 |
+
modification, are permitted provided that the following conditions are met:
|
| 300 |
+
|
| 301 |
+
* Redistributions of source code must retain the above copyright
|
| 302 |
+
notice, this list of conditions and the following disclaimer.
|
| 303 |
+
|
| 304 |
+
* Redistributions in binary form must reproduce the above copyright
|
| 305 |
+
notice, this list of conditions and the following disclaimer in the
|
| 306 |
+
documentation and/or other materials provided with the distribution.
|
| 307 |
+
|
| 308 |
+
* Neither the name of the nor the
|
| 309 |
+
names of its contributors may be used to endorse or promote products
|
| 310 |
+
derived from this software without specific prior written permission.
|
| 311 |
+
|
| 312 |
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
| 313 |
+
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
| 314 |
+
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
| 315 |
+
DISCLAIMED. IN NO EVENT SHALL Steven Moshier BE LIABLE FOR ANY
|
| 316 |
+
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
| 317 |
+
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
| 318 |
+
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
|
| 319 |
+
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
| 320 |
+
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
| 321 |
+
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
=======================================================================
|
| 325 |
+
SciPy's 3-Clause BSD License
|
| 326 |
+
=======================================================================
|
| 327 |
+
|
| 328 |
+
Code derived from implementations in SciPy should mention its derivation
|
| 329 |
+
and reference the following license:
|
| 330 |
+
|
| 331 |
+
Copyright (c) 2001-2002 Enthought, Inc. 2003-2019, SciPy Developers.
|
| 332 |
+
All rights reserved.
|
| 333 |
+
|
| 334 |
+
Redistribution and use in source and binary forms, with or without
|
| 335 |
+
modification, are permitted provided that the following conditions
|
| 336 |
+
are met:
|
| 337 |
+
|
| 338 |
+
1. Redistributions of source code must retain the above copyright
|
| 339 |
+
notice, this list of conditions and the following disclaimer.
|
| 340 |
+
|
| 341 |
+
2. Redistributions in binary form must reproduce the above
|
| 342 |
+
copyright notice, this list of conditions and the following
|
| 343 |
+
disclaimer in the documentation and/or other materials provided
|
| 344 |
+
with the distribution.
|
| 345 |
+
|
| 346 |
+
3. Neither the name of the copyright holder nor the names of its
|
| 347 |
+
contributors may be used to endorse or promote products derived
|
| 348 |
+
from this software without specific prior written permission.
|
| 349 |
+
|
| 350 |
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
| 351 |
+
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
| 352 |
+
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
| 353 |
+
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
| 354 |
+
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
| 355 |
+
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
| 356 |
+
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
| 357 |
+
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
| 358 |
+
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
| 359 |
+
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
| 360 |
+
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
| 361 |
+
|
| 362 |
+
=======================================================================
|
| 363 |
+
Boost's 1.0 Software License
|
| 364 |
+
=======================================================================
|
| 365 |
+
|
| 366 |
+
Code derived from implementations in Boost 1.0 should mention its
|
| 367 |
+
derivation and reference the following license:
|
| 368 |
+
|
| 369 |
+
Boost Software License - Version 1.0 - August 17th, 2003
|
| 370 |
+
|
| 371 |
+
Permission is hereby granted, free of charge, to any person or organization
|
| 372 |
+
obtaining a copy of the software and accompanying documentation covered by
|
| 373 |
+
this license (the "Software") to use, reproduce, display, distribute,
|
| 374 |
+
execute, and transmit the Software, and to prepare derivative works of the
|
| 375 |
+
Software, and to permit third-parties to whom the Software is furnished to
|
| 376 |
+
do so, all subject to the following:
|
| 377 |
+
|
| 378 |
+
The copyright notices in the Software and this entire statement, including
|
| 379 |
+
the above license grant, this restriction and the following disclaimer,
|
| 380 |
+
must be included in all copies of the Software, in whole or in part, and
|
| 381 |
+
all derivative works of the Software, unless such copies or derivative
|
| 382 |
+
works are solely in the form of machine-executable object code generated by
|
| 383 |
+
a source language processor.
|
| 384 |
+
|
| 385 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 386 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 387 |
+
FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
|
| 388 |
+
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
|
| 389 |
+
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
|
| 390 |
+
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
| 391 |
+
DEALINGS IN THE SOFTWARE.
|
| 392 |
+
|
| 393 |
+
END OF TERMS AND CONDITIONS
|
| 394 |
+
|
| 395 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 396 |
+
|
| 397 |
+
To apply the Apache License to your work, attach the following
|
| 398 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
| 399 |
+
replaced with your own identifying information. (Don't include
|
| 400 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 401 |
+
comment syntax for the file format. We also recommend that a
|
| 402 |
+
file or class name and description of purpose be included on the
|
| 403 |
+
same "printed page" as the copyright notice for easier
|
| 404 |
+
identification within third-party archives.
|
| 405 |
+
|
| 406 |
+
Copyright [yyyy] [name of copyright owner]
|
| 407 |
+
|
| 408 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 409 |
+
you may not use this file except in compliance with the License.
|
| 410 |
+
You may obtain a copy of the License at
|
| 411 |
+
|
| 412 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 413 |
+
|
| 414 |
+
Unless required by applicable law or agreed to in writing, software
|
| 415 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 416 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 417 |
+
See the License for the specific language governing permissions and
|
| 418 |
+
limitations under the License.
|
| 419 |
+
|
| 420 |
+
=======================================================================
|
| 421 |
+
PILLOW-SIMD Software License
|
| 422 |
+
=======================================================================
|
| 423 |
+
|
| 424 |
+
Code derived from implementations in PILLOW-SIMD should mention its derivation
|
| 425 |
+
and reference the following license:
|
| 426 |
+
|
| 427 |
+
The Python Imaging Library (PIL) is
|
| 428 |
+
|
| 429 |
+
Copyright © 1997-2011 by Secret Labs AB
|
| 430 |
+
Copyright © 1995-2011 by Fredrik Lundh
|
| 431 |
+
|
| 432 |
+
Pillow is the friendly PIL fork. It is
|
| 433 |
+
|
| 434 |
+
Copyright © 2010-2022 by Alex Clark and contributors
|
| 435 |
+
|
| 436 |
+
Like PIL, Pillow is licensed under the open source HPND License:
|
| 437 |
+
|
| 438 |
+
By obtaining, using, and/or copying this software and/or its associated
|
| 439 |
+
documentation, you agree that you have read, understood, and will comply
|
| 440 |
+
with the following terms and conditions:
|
| 441 |
+
|
| 442 |
+
Permission to use, copy, modify, and distribute this software and its
|
| 443 |
+
associated documentation for any purpose and without fee is hereby granted,
|
| 444 |
+
provided that the above copyright notice appears in all copies, and that
|
| 445 |
+
both that copyright notice and this permission notice appear in supporting
|
| 446 |
+
documentation, and that the name of Secret Labs AB or the author not be
|
| 447 |
+
used in advertising or publicity pertaining to distribution of the software
|
| 448 |
+
without specific, written prior permission.
|
| 449 |
+
|
| 450 |
+
SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
|
| 451 |
+
SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
|
| 452 |
+
IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR ANY SPECIAL,
|
| 453 |
+
INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
| 454 |
+
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
|
| 455 |
+
OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
| 456 |
+
PERFORMANCE OF THIS SOFTWARE.
|
pace_revision/.venv-pace/lib/python3.11/site-packages/torch-2.9.1+cu128.dist-info/top_level.txt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
functorch
|
| 2 |
+
torch
|
| 3 |
+
torchgen
|
pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/common_dtype.py
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: ignore-errors
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
# Functions and classes for describing the dtypes a function supports
|
| 8 |
+
# NOTE: these helpers should correspond to PyTorch's C++ dispatch macros
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
# Verifies each given dtype is a torch.dtype
|
| 12 |
+
def _validate_dtypes(*dtypes):
|
| 13 |
+
for dtype in dtypes:
|
| 14 |
+
assert isinstance(dtype, torch.dtype)
|
| 15 |
+
return dtypes
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
# class for tuples corresponding to a PyTorch dispatch macro
|
| 19 |
+
class _dispatch_dtypes(tuple):
|
| 20 |
+
__slots__ = ()
|
| 21 |
+
|
| 22 |
+
def __add__(self, other):
|
| 23 |
+
assert isinstance(other, tuple)
|
| 24 |
+
return _dispatch_dtypes(tuple.__add__(self, other))
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
_empty_types = _dispatch_dtypes(())
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def empty_types():
|
| 31 |
+
return _empty_types
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
_floating_types = _dispatch_dtypes((torch.float32, torch.float64))
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def floating_types():
|
| 38 |
+
return _floating_types
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
_floating_types_and_half = _floating_types + (torch.half,)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def floating_types_and_half():
|
| 45 |
+
return _floating_types_and_half
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def floating_types_and(*dtypes):
|
| 49 |
+
return _floating_types + _validate_dtypes(*dtypes)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
_floating_and_complex_types = _floating_types + (torch.cfloat, torch.cdouble)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def floating_and_complex_types():
|
| 56 |
+
return _floating_and_complex_types
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def floating_and_complex_types_and(*dtypes):
|
| 60 |
+
return _floating_and_complex_types + _validate_dtypes(*dtypes)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
_double_types = _dispatch_dtypes((torch.float64, torch.complex128))
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def double_types():
|
| 67 |
+
return _double_types
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
# NB: Does not contain uint16/uint32/uint64 for BC reasons
|
| 71 |
+
_integral_types = _dispatch_dtypes(
|
| 72 |
+
(torch.uint8, torch.int8, torch.int16, torch.int32, torch.int64)
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def integral_types():
|
| 77 |
+
return _integral_types
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def integral_types_and(*dtypes):
|
| 81 |
+
return _integral_types + _validate_dtypes(*dtypes)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
_all_types = _floating_types + _integral_types
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def all_types():
|
| 88 |
+
return _all_types
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def all_types_and(*dtypes):
|
| 92 |
+
return _all_types + _validate_dtypes(*dtypes)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
_complex_types = _dispatch_dtypes((torch.cfloat, torch.cdouble))
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def complex_types():
|
| 99 |
+
return _complex_types
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def complex_types_and(*dtypes):
|
| 103 |
+
return _complex_types + _validate_dtypes(*dtypes)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
_all_types_and_complex = _all_types + _complex_types
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def all_types_and_complex():
|
| 110 |
+
return _all_types_and_complex
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def all_types_and_complex_and(*dtypes):
|
| 114 |
+
return _all_types_and_complex + _validate_dtypes(*dtypes)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
_all_types_and_half = _all_types + (torch.half,)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def all_types_and_half():
|
| 121 |
+
return _all_types_and_half
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
_all_mps_types = (
|
| 125 |
+
_dispatch_dtypes({torch.float, torch.half, torch.bfloat16}) + _integral_types
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def all_mps_types():
|
| 130 |
+
return _all_mps_types
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def all_mps_types_and(*dtypes):
|
| 134 |
+
return _all_mps_types + _validate_dtypes(*dtypes)
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
_float8_types = _dispatch_dtypes(
|
| 138 |
+
(
|
| 139 |
+
torch.float8_e4m3fn,
|
| 140 |
+
torch.float8_e4m3fnuz,
|
| 141 |
+
torch.float8_e5m2,
|
| 142 |
+
torch.float8_e5m2fnuz,
|
| 143 |
+
)
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def float8_types():
|
| 148 |
+
return _float8_types
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def float8_types_and(*dtypes):
|
| 152 |
+
return _float8_types + _validate_dtypes(*dtypes)
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def all_types_complex_float8_and(*dtypes):
|
| 156 |
+
return _all_types + _complex_types + _float8_types + _validate_dtypes(*dtypes)
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def custom_types(*dtypes):
|
| 160 |
+
"""Create a list of arbitrary dtypes"""
|
| 161 |
+
return _empty_types + _validate_dtypes(*dtypes)
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
# The functions below are used for convenience in our test suite and thus have no corresponding C++ dispatch macro
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
# See AT_FORALL_SCALAR_TYPES_WITH_COMPLEX_AND_QINTS.
|
| 168 |
+
def get_all_dtypes(
|
| 169 |
+
include_half=True,
|
| 170 |
+
include_bfloat16=True,
|
| 171 |
+
include_bool=True,
|
| 172 |
+
include_complex=True,
|
| 173 |
+
include_complex32=False,
|
| 174 |
+
include_qint=False,
|
| 175 |
+
) -> list[torch.dtype]:
|
| 176 |
+
dtypes = get_all_int_dtypes() + get_all_fp_dtypes(
|
| 177 |
+
include_half=include_half, include_bfloat16=include_bfloat16
|
| 178 |
+
)
|
| 179 |
+
if include_bool:
|
| 180 |
+
dtypes.append(torch.bool)
|
| 181 |
+
if include_complex:
|
| 182 |
+
dtypes += get_all_complex_dtypes(include_complex32)
|
| 183 |
+
if include_qint:
|
| 184 |
+
dtypes += get_all_qint_dtypes()
|
| 185 |
+
return dtypes
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def get_all_math_dtypes(device) -> list[torch.dtype]:
|
| 189 |
+
return (
|
| 190 |
+
get_all_int_dtypes()
|
| 191 |
+
+ get_all_fp_dtypes(
|
| 192 |
+
include_half=device.startswith("cuda"), include_bfloat16=False
|
| 193 |
+
)
|
| 194 |
+
+ get_all_complex_dtypes()
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def get_all_complex_dtypes(include_complex32=False) -> list[torch.dtype]:
|
| 199 |
+
return (
|
| 200 |
+
[torch.complex32, torch.complex64, torch.complex128]
|
| 201 |
+
if include_complex32
|
| 202 |
+
else [torch.complex64, torch.complex128]
|
| 203 |
+
)
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def get_all_int_dtypes() -> list[torch.dtype]:
|
| 207 |
+
return [torch.uint8, torch.int8, torch.int16, torch.int32, torch.int64]
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def get_all_fp_dtypes(include_half=True, include_bfloat16=True) -> list[torch.dtype]:
|
| 211 |
+
dtypes = [torch.float32, torch.float64]
|
| 212 |
+
if include_half:
|
| 213 |
+
dtypes.append(torch.float16)
|
| 214 |
+
if include_bfloat16:
|
| 215 |
+
dtypes.append(torch.bfloat16)
|
| 216 |
+
return dtypes
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def get_all_qint_dtypes() -> list[torch.dtype]:
|
| 220 |
+
return [torch.qint8, torch.quint8, torch.qint32, torch.quint4x2, torch.quint2x4]
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
float_to_corresponding_complex_type_map = {
|
| 224 |
+
torch.float16: torch.complex32,
|
| 225 |
+
torch.float32: torch.complex64,
|
| 226 |
+
torch.float64: torch.complex128,
|
| 227 |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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
# Owner(s): ["oncall: distributed"]
|
| 3 |
+
|
| 4 |
+
import contextlib
|
| 5 |
+
import os
|
| 6 |
+
import re
|
| 7 |
+
import sys
|
| 8 |
+
import time
|
| 9 |
+
import unittest
|
| 10 |
+
import warnings
|
| 11 |
+
from abc import ABC, abstractmethod
|
| 12 |
+
from contextlib import nullcontext
|
| 13 |
+
from copy import deepcopy
|
| 14 |
+
from enum import auto, Enum
|
| 15 |
+
from functools import wraps
|
| 16 |
+
from typing import Any, Callable, cast, no_type_check, Optional, Union
|
| 17 |
+
from unittest import mock
|
| 18 |
+
|
| 19 |
+
import torch
|
| 20 |
+
import torch.distributed as dist
|
| 21 |
+
import torch.nn as nn
|
| 22 |
+
import torch.nn.functional as F
|
| 23 |
+
from torch.distributed._composable import checkpoint
|
| 24 |
+
from torch.distributed.device_mesh import DeviceMesh
|
| 25 |
+
from torch.distributed.fsdp import (
|
| 26 |
+
CPUOffload,
|
| 27 |
+
fully_shard,
|
| 28 |
+
FullyShardedDataParallel as FSDP,
|
| 29 |
+
)
|
| 30 |
+
from torch.distributed.fsdp._common_utils import TrainingState
|
| 31 |
+
from torch.distributed.fsdp._fully_shard._fsdp_param_group import (
|
| 32 |
+
FSDPParamGroup,
|
| 33 |
+
RegisterPostBackwardFunction,
|
| 34 |
+
)
|
| 35 |
+
from torch.distributed.fsdp._init_utils import NO_RESHARD_AFTER_FORWARD_STRATEGIES
|
| 36 |
+
from torch.distributed.fsdp.fully_sharded_data_parallel import (
|
| 37 |
+
BackwardPrefetch,
|
| 38 |
+
MixedPrecision,
|
| 39 |
+
ShardingStrategy,
|
| 40 |
+
)
|
| 41 |
+
from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler
|
| 42 |
+
from torch.distributed.fsdp.wrap import always_wrap_policy, ModuleWrapPolicy, wrap
|
| 43 |
+
from torch.distributed.tensor import distribute_tensor, DTensor, Shard
|
| 44 |
+
from torch.distributed.tensor.parallel import (
|
| 45 |
+
ColwiseParallel,
|
| 46 |
+
parallelize_module,
|
| 47 |
+
RowwiseParallel,
|
| 48 |
+
SequenceParallel,
|
| 49 |
+
)
|
| 50 |
+
from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer
|
| 51 |
+
from torch.nn.parallel.distributed import DistributedDataParallel as DDP
|
| 52 |
+
from torch.testing._internal.common_distributed import (
|
| 53 |
+
MultiProcessTestCase,
|
| 54 |
+
MultiThreadedTestCase,
|
| 55 |
+
run_subtests,
|
| 56 |
+
TEST_SKIPS,
|
| 57 |
+
)
|
| 58 |
+
from torch.testing._internal.common_utils import (
|
| 59 |
+
FILE_SCHEMA,
|
| 60 |
+
get_cycles_per_ms,
|
| 61 |
+
TEST_CUDA,
|
| 62 |
+
TEST_HPU,
|
| 63 |
+
TEST_XPU,
|
| 64 |
+
)
|
| 65 |
+
from torch.utils._triton import has_triton
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
DEVICE_COUNT = 4 # default
|
| 69 |
+
|
| 70 |
+
if TEST_CUDA:
|
| 71 |
+
DEVICE_TYPE = "cuda"
|
| 72 |
+
DISTRIBUTED_BACKEND = "nccl"
|
| 73 |
+
DEVICE_COUNT = torch.cuda.device_count()
|
| 74 |
+
elif TEST_HPU:
|
| 75 |
+
DEVICE_TYPE = "hpu:0"
|
| 76 |
+
DISTRIBUTED_BACKEND = "hccl"
|
| 77 |
+
elif TEST_XPU:
|
| 78 |
+
DEVICE_TYPE = "xpu"
|
| 79 |
+
DISTRIBUTED_BACKEND = "xccl"
|
| 80 |
+
DEVICE_COUNT = torch.xpu.device_count()
|
| 81 |
+
else:
|
| 82 |
+
DEVICE_TYPE = "cpu"
|
| 83 |
+
DISTRIBUTED_BACKEND = "gloo"
|
| 84 |
+
DEVICE_COUNT = 1
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
class FSDPInitMode(Enum):
|
| 88 |
+
# No FSDP wrapping
|
| 89 |
+
NO_FSDP = auto()
|
| 90 |
+
# FSDP recursive wrapping
|
| 91 |
+
RECURSIVE = auto()
|
| 92 |
+
# TODO: FSDP non-recursive wrapping
|
| 93 |
+
# NONRECURSIVE = auto()
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
class DEVICEInitMode(Enum):
|
| 97 |
+
# Move model to DEVICE before passing to the FSDP constructor
|
| 98 |
+
DEVICE_BEFORE = auto()
|
| 99 |
+
# Move model to DEVICE after passing to the FSDP constructor
|
| 100 |
+
DEVICE_AFTER = auto()
|
| 101 |
+
# Keep on CPU
|
| 102 |
+
DEVICE_NEVER = auto()
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
class FSDPTestModel(nn.Module, ABC):
|
| 106 |
+
"""This defines the interface expected from all models used commonly for
|
| 107 |
+
FSDP unit tests."""
|
| 108 |
+
|
| 109 |
+
@abstractmethod
|
| 110 |
+
def get_input(self, device) -> tuple[torch.Tensor, ...]:
|
| 111 |
+
"""Returns an input for the model as as tuple."""
|
| 112 |
+
...
|
| 113 |
+
|
| 114 |
+
@abstractmethod
|
| 115 |
+
def get_loss(self, input, output) -> torch.Tensor:
|
| 116 |
+
"""Returns the loss given the input and output."""
|
| 117 |
+
...
|
| 118 |
+
|
| 119 |
+
@abstractmethod
|
| 120 |
+
def run_backward(self, loss) -> None:
|
| 121 |
+
"""Runs the backward pass (e.g. including ``loss.backward()``)."""
|
| 122 |
+
...
|
| 123 |
+
|
| 124 |
+
@staticmethod
|
| 125 |
+
@abstractmethod
|
| 126 |
+
def init(*args: Any, **kwargs: Any) -> nn.Module:
|
| 127 |
+
"""Initializes an instance of this model."""
|
| 128 |
+
...
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def _assert_module_states(
|
| 132 |
+
model: nn.Module,
|
| 133 |
+
process_group: dist.ProcessGroup,
|
| 134 |
+
assert_fn: Callable,
|
| 135 |
+
):
|
| 136 |
+
"""
|
| 137 |
+
All-gathers module states across ranks and calls ``assert_fn`` on each pair
|
| 138 |
+
of corresponding states from rank 0 and a nonzero rank. For example, if
|
| 139 |
+
``assert_fn`` is ``self.assertEqual()``, then this checks that all module
|
| 140 |
+
states are equal across ranks.
|
| 141 |
+
"""
|
| 142 |
+
# Include names for debugging convenience
|
| 143 |
+
named_module_states = [
|
| 144 |
+
(param_name, param.detach().cpu())
|
| 145 |
+
for param_name, param in model.named_parameters()
|
| 146 |
+
]
|
| 147 |
+
named_module_states += [
|
| 148 |
+
(buffer_name, buffer.detach().cpu())
|
| 149 |
+
for buffer_name, buffer in model.named_buffers()
|
| 150 |
+
]
|
| 151 |
+
world_size = dist.get_world_size(process_group)
|
| 152 |
+
olist = [None for _ in range(world_size)]
|
| 153 |
+
dist.all_gather_object(olist, named_module_states, group=process_group)
|
| 154 |
+
rank0_states = olist[0]
|
| 155 |
+
assert rank0_states is not None # mypy
|
| 156 |
+
for state in olist[1:]:
|
| 157 |
+
assert state is not None # mypy
|
| 158 |
+
for (_, p1), (_, p2) in zip(rank0_states, state):
|
| 159 |
+
assert_fn(p1, p2)
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def get_devtype():
|
| 163 |
+
return torch.device(DEVICE_TYPE)
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def _zero_model(
|
| 167 |
+
model: nn.Module,
|
| 168 |
+
zero_buffers: bool = False,
|
| 169 |
+
summon_full=True,
|
| 170 |
+
):
|
| 171 |
+
"""Zeros the parameters and optionally buffers of ``model`` in place."""
|
| 172 |
+
ctx = FSDP.summon_full_params(model) if summon_full else nullcontext()
|
| 173 |
+
with ctx:
|
| 174 |
+
for param in model.parameters():
|
| 175 |
+
with torch.no_grad():
|
| 176 |
+
param.zero_()
|
| 177 |
+
if zero_buffers:
|
| 178 |
+
for buffer in model.buffers():
|
| 179 |
+
with torch.no_grad():
|
| 180 |
+
buffer.zero_()
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def _get_state_dict(model, cpu_offload=False, half=False):
|
| 184 |
+
if not cpu_offload:
|
| 185 |
+
model = model.to(DEVICE_TYPE)
|
| 186 |
+
if half:
|
| 187 |
+
model.half()
|
| 188 |
+
|
| 189 |
+
return model.state_dict()
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def subtest_name(test_name_mapping, *args):
|
| 193 |
+
return "_".join(
|
| 194 |
+
[test_name_mapping[str(s)] if s is not None else "none" for s in args]
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def _broadcast_state_dict(rank, state_dict):
|
| 199 |
+
# For non-FSDP roots, some parts of the model state on rank 0 may
|
| 200 |
+
# not be on CPU, so we move everything to CPU to avoid issues like:
|
| 201 |
+
# https://github.com/pytorch/pytorch/issues/77113.
|
| 202 |
+
for param_name, param in state_dict.items():
|
| 203 |
+
if param.device != torch.device("cpu"):
|
| 204 |
+
state_dict[param_name] = param.cpu()
|
| 205 |
+
|
| 206 |
+
olist = [state_dict if rank == 0 else None]
|
| 207 |
+
dist.broadcast_object_list(olist)
|
| 208 |
+
state_dict = cast(dict[str, torch.Tensor], olist[0])
|
| 209 |
+
# Ensure that the state is on DEVICE
|
| 210 |
+
for param_name in state_dict.keys():
|
| 211 |
+
state_dict[param_name] = state_dict[param_name].to(DEVICE_TYPE)
|
| 212 |
+
return state_dict
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def get_full_params(model: nn.Module, recurse: bool = True):
|
| 216 |
+
"""
|
| 217 |
+
Returns the full unsharded parameters of ``model``. Any FSDP-managed
|
| 218 |
+
parameters offloaded to CPU are moved to GPU in the returned list.
|
| 219 |
+
|
| 220 |
+
Args:
|
| 221 |
+
recurse (bool): If ``False``, only unshards the parameters immediate to
|
| 222 |
+
``model``; if ``True``, recurses through the module hierarchy
|
| 223 |
+
rooted at ``model``.
|
| 224 |
+
"""
|
| 225 |
+
with FSDP.summon_full_params(model, recurse=recurse):
|
| 226 |
+
return deepcopy(list(model.parameters()))
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
def _move_to_device(model: nn.Module, move_to_device: bool):
|
| 230 |
+
return model.to(DEVICE_TYPE) if move_to_device else model
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def _maybe_wrap_fsdp(model: nn.Module, wrap_fsdp: bool, *args, **kwargs):
|
| 234 |
+
return model if not wrap_fsdp else FSDP(model, *args, **kwargs)
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
class DummyProcessGroup:
|
| 238 |
+
def __init__(self, rank: int, size: int):
|
| 239 |
+
self._rank = rank
|
| 240 |
+
self._size = size
|
| 241 |
+
|
| 242 |
+
def rank(self) -> int:
|
| 243 |
+
return self._rank
|
| 244 |
+
|
| 245 |
+
def size(self) -> int:
|
| 246 |
+
return self._size
|
| 247 |
+
|
| 248 |
+
def allreduce(self, *args, **kwargs):
|
| 249 |
+
dist_wait = mock.Mock()
|
| 250 |
+
|
| 251 |
+
def get_future():
|
| 252 |
+
future: torch.futures.Future = torch.futures.Future()
|
| 253 |
+
future.set_result(1)
|
| 254 |
+
return future
|
| 255 |
+
|
| 256 |
+
dist_wait.get_future = get_future
|
| 257 |
+
return dist_wait
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
class TransformerWithSharedParams(FSDPTestModel):
|
| 261 |
+
def __init__(
|
| 262 |
+
self,
|
| 263 |
+
group: dist.ProcessGroup,
|
| 264 |
+
device_init_mode: DEVICEInitMode,
|
| 265 |
+
add_bn: bool,
|
| 266 |
+
deterministic: bool,
|
| 267 |
+
):
|
| 268 |
+
super().__init__()
|
| 269 |
+
self.rank = group.rank()
|
| 270 |
+
self.world_size = group.size()
|
| 271 |
+
if deterministic:
|
| 272 |
+
torch.manual_seed(0)
|
| 273 |
+
d_vocab = 23
|
| 274 |
+
d_model = 16
|
| 275 |
+
|
| 276 |
+
self.embed_tokens = nn.Embedding(d_vocab, d_model)
|
| 277 |
+
self.transformer = nn.Transformer(
|
| 278 |
+
d_model=d_model,
|
| 279 |
+
num_encoder_layers=2,
|
| 280 |
+
num_decoder_layers=2,
|
| 281 |
+
dim_feedforward=8,
|
| 282 |
+
dropout=0.1,
|
| 283 |
+
)
|
| 284 |
+
self.output_proj = nn.Linear(d_model, d_vocab)
|
| 285 |
+
|
| 286 |
+
# share the embedding and output projection weights
|
| 287 |
+
self.output_proj.weight = self.embed_tokens.weight
|
| 288 |
+
self.register_buffer(
|
| 289 |
+
"vocab_bias", self.embed_tokens.weight.new_ones((d_model,))
|
| 290 |
+
)
|
| 291 |
+
self.register_buffer(
|
| 292 |
+
"long_buffer",
|
| 293 |
+
torch.zeros_like(self.vocab_bias, dtype=torch.long), # type: ignore[arg-type]
|
| 294 |
+
) # type: ignore[arg-type]
|
| 295 |
+
|
| 296 |
+
self.bs = 2
|
| 297 |
+
self.bn = torch.nn.BatchNorm1d(self.bs) if add_bn else torch.nn.Identity()
|
| 298 |
+
if device_init_mode == DEVICEInitMode.DEVICE_BEFORE:
|
| 299 |
+
self = self.to(DEVICE_TYPE)
|
| 300 |
+
if deterministic:
|
| 301 |
+
self.eval()
|
| 302 |
+
|
| 303 |
+
def get_input(self, device):
|
| 304 |
+
torch.manual_seed(1 + self.rank) # keep everything deterministic
|
| 305 |
+
src = torch.arange(12, device=device).view(6, self.bs) # T x B
|
| 306 |
+
tgt = torch.arange(self.bs * 4, device=device).view(4, self.bs) # T x B
|
| 307 |
+
return (src, tgt)
|
| 308 |
+
|
| 309 |
+
def forward(self, src_ids, tgt_ids):
|
| 310 |
+
src = self.embed_tokens(src_ids)
|
| 311 |
+
src = src + self.vocab_bias + self.long_buffer.type_as(src) # type: ignore[operator]
|
| 312 |
+
tgt = self.embed_tokens(tgt_ids)
|
| 313 |
+
tgt = self.bn(tgt)
|
| 314 |
+
x = self.transformer(src, tgt)
|
| 315 |
+
return self.output_proj(x)
|
| 316 |
+
|
| 317 |
+
def get_loss(self, input, output):
|
| 318 |
+
_, tgt = input
|
| 319 |
+
return nn.functional.cross_entropy(
|
| 320 |
+
output.view(-1, output.size(-1)), tgt.view(-1), reduction="sum"
|
| 321 |
+
)
|
| 322 |
+
|
| 323 |
+
def run_backward(self, loss):
|
| 324 |
+
loss.backward()
|
| 325 |
+
|
| 326 |
+
@staticmethod
|
| 327 |
+
def init(
|
| 328 |
+
group: dist.ProcessGroup,
|
| 329 |
+
fsdp_init_mode: FSDPInitMode,
|
| 330 |
+
device_init_mode: DEVICEInitMode,
|
| 331 |
+
fsdp_kwargs: Optional[dict[str, Any]] = None,
|
| 332 |
+
deterministic: bool = False,
|
| 333 |
+
add_bn: bool = True,
|
| 334 |
+
) -> Union[nn.Module, FSDP]:
|
| 335 |
+
"""
|
| 336 |
+
Initializes a :class:`TransformerWithSharedParams` instance.
|
| 337 |
+
|
| 338 |
+
Args:
|
| 339 |
+
fsdp_init_mode (FSDPInitMode): If ``NO_FSDP``, then does not wrap
|
| 340 |
+
any modules with FSDP. If ``RECURSIVE``, then wraps with
|
| 341 |
+
top-level FSDP. By default, the top-level FSDP uses the
|
| 342 |
+
``ModuleWrapPolicy`` for encoder and decoder layers, but a
|
| 343 |
+
different auto wrap policy may be specified via
|
| 344 |
+
``fsdp_kwargs``.
|
| 345 |
+
device_init_mode (DEVICEInitMode): Determines model movement to DEVICE.
|
| 346 |
+
fsdp_kwargs (Optional[Dict[str, Any]]): Optional keyword arguments
|
| 347 |
+
forwarded to the FSDP constructor.
|
| 348 |
+
deterministic (bool): Whether to make the model deterministic
|
| 349 |
+
across constructions.
|
| 350 |
+
add_bn (bool): Whether to include batch norm in the model.
|
| 351 |
+
"""
|
| 352 |
+
|
| 353 |
+
if fsdp_kwargs is None:
|
| 354 |
+
fsdp_kwargs = {}
|
| 355 |
+
if fsdp_init_mode == FSDPInitMode.NO_FSDP:
|
| 356 |
+
if isinstance(group, tuple):
|
| 357 |
+
pg = group[0]
|
| 358 |
+
else:
|
| 359 |
+
pg = group
|
| 360 |
+
return TransformerWithSharedParams(
|
| 361 |
+
pg, device_init_mode, add_bn, deterministic
|
| 362 |
+
)
|
| 363 |
+
elif fsdp_init_mode == FSDPInitMode.RECURSIVE:
|
| 364 |
+
# Default to the `ModuleWrapPolicy`
|
| 365 |
+
if "auto_wrap_policy" not in fsdp_kwargs:
|
| 366 |
+
auto_wrap_policy = ModuleWrapPolicy(
|
| 367 |
+
{
|
| 368 |
+
TransformerEncoderLayer,
|
| 369 |
+
TransformerDecoderLayer,
|
| 370 |
+
}
|
| 371 |
+
)
|
| 372 |
+
else:
|
| 373 |
+
auto_wrap_policy = fsdp_kwargs.pop("auto_wrap_policy")
|
| 374 |
+
|
| 375 |
+
if (
|
| 376 |
+
"sharding_strategy" in fsdp_kwargs
|
| 377 |
+
and fsdp_kwargs["sharding_strategy"]
|
| 378 |
+
in {ShardingStrategy.HYBRID_SHARD, ShardingStrategy._HYBRID_SHARD_ZERO2}
|
| 379 |
+
and not isinstance(group, tuple)
|
| 380 |
+
):
|
| 381 |
+
fsdp_pg = None
|
| 382 |
+
else:
|
| 383 |
+
fsdp_pg = group
|
| 384 |
+
|
| 385 |
+
if isinstance(group, tuple):
|
| 386 |
+
tformer_pg = group[0]
|
| 387 |
+
else:
|
| 388 |
+
tformer_pg = group
|
| 389 |
+
|
| 390 |
+
m = TransformerWithSharedParams(
|
| 391 |
+
tformer_pg, device_init_mode, add_bn, deterministic
|
| 392 |
+
)
|
| 393 |
+
fsdp_model = FSDP(
|
| 394 |
+
m,
|
| 395 |
+
fsdp_pg,
|
| 396 |
+
auto_wrap_policy=auto_wrap_policy,
|
| 397 |
+
**fsdp_kwargs,
|
| 398 |
+
)
|
| 399 |
+
if device_init_mode == DEVICEInitMode.DEVICE_AFTER:
|
| 400 |
+
fsdp_model = fsdp_model.to(DEVICE_TYPE)
|
| 401 |
+
return fsdp_model
|
| 402 |
+
raise ValueError(f"Unsupported FSDP init mode: {fsdp_init_mode}")
|
| 403 |
+
|
| 404 |
+
def get_ignored_modules(self):
|
| 405 |
+
return [self.transformer]
|
| 406 |
+
|
| 407 |
+
|
| 408 |
+
class NestedWrappedModule(FSDPTestModel):
|
| 409 |
+
def __init__(
|
| 410 |
+
self,
|
| 411 |
+
group: dist.ProcessGroup,
|
| 412 |
+
wrap_fsdp: bool,
|
| 413 |
+
device_init_mode: DEVICEInitMode,
|
| 414 |
+
deterministic: bool,
|
| 415 |
+
**fsdp_kwargs,
|
| 416 |
+
):
|
| 417 |
+
super().__init__()
|
| 418 |
+
self.rank = group.rank()
|
| 419 |
+
self.world_size = group.size()
|
| 420 |
+
move_to_device = device_init_mode == DEVICEInitMode.DEVICE_BEFORE
|
| 421 |
+
|
| 422 |
+
def _maybe_wrap(layer):
|
| 423 |
+
if wrap_fsdp:
|
| 424 |
+
return FSDP(layer, group, **fsdp_kwargs)
|
| 425 |
+
return layer
|
| 426 |
+
|
| 427 |
+
if deterministic:
|
| 428 |
+
torch.manual_seed(0)
|
| 429 |
+
self.module = nn.Sequential(
|
| 430 |
+
_move_to_device(nn.Linear(8, 4), move_to_device),
|
| 431 |
+
_maybe_wrap(
|
| 432 |
+
nn.Sequential(
|
| 433 |
+
_maybe_wrap(_move_to_device(nn.Linear(4, 16), move_to_device)),
|
| 434 |
+
_move_to_device(nn.Linear(16, 16), move_to_device),
|
| 435 |
+
),
|
| 436 |
+
),
|
| 437 |
+
_maybe_wrap(_move_to_device(nn.Linear(16, 4), move_to_device)),
|
| 438 |
+
_move_to_device(nn.Linear(4, 8), move_to_device),
|
| 439 |
+
)
|
| 440 |
+
|
| 441 |
+
def get_input(self, device):
|
| 442 |
+
torch.manual_seed(1 + self.rank) # keep everything deterministic
|
| 443 |
+
return (torch.rand(4, 8, device=device),)
|
| 444 |
+
|
| 445 |
+
def forward(self, x):
|
| 446 |
+
return self.module(x)
|
| 447 |
+
|
| 448 |
+
def get_loss(self, input, output):
|
| 449 |
+
loss = output.sum()
|
| 450 |
+
return loss
|
| 451 |
+
|
| 452 |
+
def run_backward(self, loss):
|
| 453 |
+
loss.backward()
|
| 454 |
+
|
| 455 |
+
@staticmethod
|
| 456 |
+
def init(
|
| 457 |
+
group: dist.ProcessGroup,
|
| 458 |
+
fsdp_init_mode: FSDPInitMode,
|
| 459 |
+
device_init_mode: DEVICEInitMode,
|
| 460 |
+
fsdp_kwargs: Optional[dict[str, Any]] = None,
|
| 461 |
+
deterministic: bool = False,
|
| 462 |
+
) -> nn.Module:
|
| 463 |
+
"""
|
| 464 |
+
Initializes a :class:`NestedWrappedModule` instance.
|
| 465 |
+
|
| 466 |
+
Args:
|
| 467 |
+
fsdp_init_mode (FSDPInitMode): If ``NO_FSDP``, then does not wrap
|
| 468 |
+
any modules with FSDP. If ``RECURSIVE``, then wraps some nested
|
| 469 |
+
modules with FSDP but not the top-level module. The model may
|
| 470 |
+
later be wrapped with a top-level FSDP external to this method
|
| 471 |
+
if desired.
|
| 472 |
+
device_init_mode (DEVICEInitMode): Determines model movement to DEVICE.
|
| 473 |
+
fsdp_kwargs (Optional[Dict[str, Any]]): Optional keyword arguments
|
| 474 |
+
forwarded to the FSDP constructor.
|
| 475 |
+
deterministic (bool): Whether to make the model deterministic
|
| 476 |
+
across constructions.
|
| 477 |
+
"""
|
| 478 |
+
if fsdp_kwargs is None:
|
| 479 |
+
fsdp_kwargs = {}
|
| 480 |
+
if fsdp_init_mode == FSDPInitMode.NO_FSDP:
|
| 481 |
+
return NestedWrappedModule(
|
| 482 |
+
group,
|
| 483 |
+
wrap_fsdp=False,
|
| 484 |
+
device_init_mode=device_init_mode,
|
| 485 |
+
deterministic=deterministic,
|
| 486 |
+
)
|
| 487 |
+
elif fsdp_init_mode == FSDPInitMode.RECURSIVE:
|
| 488 |
+
# Does not wrap with top-level FSDP
|
| 489 |
+
fsdp_model = NestedWrappedModule(
|
| 490 |
+
group,
|
| 491 |
+
wrap_fsdp=True,
|
| 492 |
+
device_init_mode=device_init_mode,
|
| 493 |
+
deterministic=deterministic,
|
| 494 |
+
**fsdp_kwargs,
|
| 495 |
+
)
|
| 496 |
+
if device_init_mode == DEVICEInitMode.DEVICE_AFTER:
|
| 497 |
+
fsdp_model = fsdp_model.to(DEVICE_TYPE)
|
| 498 |
+
return fsdp_model
|
| 499 |
+
raise ValueError(f"Unsupported FSDP init mode: {fsdp_init_mode}")
|
| 500 |
+
|
| 501 |
+
|
| 502 |
+
class AlwaysWrapNestedWrappedModule(NestedWrappedModule):
|
| 503 |
+
@staticmethod
|
| 504 |
+
def init(
|
| 505 |
+
group: dist.ProcessGroup,
|
| 506 |
+
fsdp_init_mode: FSDPInitMode,
|
| 507 |
+
device_init_mode: DEVICEInitMode,
|
| 508 |
+
fsdp_kwargs: Optional[dict[str, Any]] = None,
|
| 509 |
+
deterministic: bool = False,
|
| 510 |
+
):
|
| 511 |
+
"""
|
| 512 |
+
Initializes a :class:`NestedWrappedModule` instance, but unlike
|
| 513 |
+
:meth:`NestedWrappedModule.init`, for the ``RECURSIVE`` init mode, this
|
| 514 |
+
wraps with top-level FSDP and the ``always_wrap_policy()`` auto wrap
|
| 515 |
+
policy.
|
| 516 |
+
"""
|
| 517 |
+
model = super(
|
| 518 |
+
AlwaysWrapNestedWrappedModule, AlwaysWrapNestedWrappedModule
|
| 519 |
+
).init(
|
| 520 |
+
group=group,
|
| 521 |
+
fsdp_init_mode=FSDPInitMode.NO_FSDP,
|
| 522 |
+
device_init_mode=device_init_mode,
|
| 523 |
+
fsdp_kwargs=fsdp_kwargs,
|
| 524 |
+
deterministic=deterministic,
|
| 525 |
+
)
|
| 526 |
+
if fsdp_init_mode == FSDPInitMode.NO_FSDP:
|
| 527 |
+
return model
|
| 528 |
+
elif fsdp_init_mode == FSDPInitMode.RECURSIVE:
|
| 529 |
+
fsdp_kwargs = fsdp_kwargs or {}
|
| 530 |
+
fsdp_model = FSDP(model, auto_wrap_policy=always_wrap_policy, **fsdp_kwargs)
|
| 531 |
+
if device_init_mode == DEVICEInitMode.DEVICE_AFTER:
|
| 532 |
+
fsdp_model = fsdp_model.to(DEVICE_TYPE)
|
| 533 |
+
return fsdp_model
|
| 534 |
+
|
| 535 |
+
|
| 536 |
+
class NonUniformReqGradNWM(NestedWrappedModule):
|
| 537 |
+
def __init__(
|
| 538 |
+
self,
|
| 539 |
+
group: dist.ProcessGroup,
|
| 540 |
+
wrap_fsdp: bool,
|
| 541 |
+
device_init_mode: DEVICEInitMode,
|
| 542 |
+
deterministic: bool,
|
| 543 |
+
**fsdp_kwargs,
|
| 544 |
+
):
|
| 545 |
+
super(NestedWrappedModule, self).__init__()
|
| 546 |
+
# This `__init__` only differs from `NestedWrappedModule.__init__` in that
|
| 547 |
+
# the last two `nn.Linear` layers are FSDP wrapped in a `nn.Sequential`
|
| 548 |
+
# container. This arrangement results in all elements of the last two parameters
|
| 549 |
+
# residing on a single rank. Freezing all parameters except those two allows us
|
| 550 |
+
# to verify that `ShardedGradScaler` accommodates situations where some ranks
|
| 551 |
+
# have no (non-zero sized) parameter shards.
|
| 552 |
+
self.rank = group.rank()
|
| 553 |
+
self.world_size = group.size()
|
| 554 |
+
move_to_device = device_init_mode == DEVICEInitMode.DEVICE_BEFORE
|
| 555 |
+
|
| 556 |
+
def _maybe_wrap(layer):
|
| 557 |
+
if wrap_fsdp:
|
| 558 |
+
return FSDP(layer, group, **fsdp_kwargs)
|
| 559 |
+
return layer
|
| 560 |
+
|
| 561 |
+
if deterministic:
|
| 562 |
+
torch.manual_seed(0)
|
| 563 |
+
self.module = nn.Sequential(
|
| 564 |
+
_move_to_device(nn.Linear(8, 4), move_to_device),
|
| 565 |
+
_maybe_wrap(
|
| 566 |
+
nn.Sequential(
|
| 567 |
+
_maybe_wrap(_move_to_device(nn.Linear(4, 16), move_to_device)),
|
| 568 |
+
_move_to_device(nn.Linear(16, 16), move_to_device),
|
| 569 |
+
),
|
| 570 |
+
),
|
| 571 |
+
_maybe_wrap(
|
| 572 |
+
nn.Sequential(
|
| 573 |
+
_move_to_device(nn.Linear(16, 4), move_to_device),
|
| 574 |
+
_move_to_device(nn.Linear(4, 8), move_to_device),
|
| 575 |
+
),
|
| 576 |
+
),
|
| 577 |
+
)
|
| 578 |
+
|
| 579 |
+
@staticmethod
|
| 580 |
+
def _set_nonuniform_req_grad(model, req_grad_mask) -> None:
|
| 581 |
+
for n, p in model.named_parameters():
|
| 582 |
+
if not re.match(req_grad_mask, n):
|
| 583 |
+
p.requires_grad_(False)
|
| 584 |
+
|
| 585 |
+
@staticmethod
|
| 586 |
+
def init(
|
| 587 |
+
group: dist.ProcessGroup,
|
| 588 |
+
fsdp_init_mode: FSDPInitMode,
|
| 589 |
+
device_init_mode: DEVICEInitMode,
|
| 590 |
+
fsdp_kwargs: Optional[dict[str, Any]] = None,
|
| 591 |
+
deterministic: bool = False,
|
| 592 |
+
):
|
| 593 |
+
"""
|
| 594 |
+
Initializes a :class:`NestedWrappedModule` instance, but unlike
|
| 595 |
+
:meth:`NestedWrappedModule.init`, it wraps a second :class:`torch.nn.Sequential`
|
| 596 |
+
container to enable the desired non-uniform ``requires_grad``
|
| 597 |
+
``use_orig_params=True`` tests. For both ``RECURSIVE`` and ``NO_FSDP``
|
| 598 |
+
init modes, freezes all parameters except the last two to validate
|
| 599 |
+
``ShardedGradScaler`` support for ranks with no (non-zero sized) local shards in
|
| 600 |
+
FSDP ``use_orig_params=True`` mode.
|
| 601 |
+
"""
|
| 602 |
+
# The parameters that should remain unfrozen are in `module.2.1`. The regex
|
| 603 |
+
# pattern below matches the relevant parameter names both with and without
|
| 604 |
+
# an interstitial FSDP module indicator (`_fsdp_wrapped_module`) present.
|
| 605 |
+
req_grad_pattern = re.compile(r"module\.2.*\.1.*")
|
| 606 |
+
if fsdp_init_mode == FSDPInitMode.NO_FSDP:
|
| 607 |
+
ddp_model = NonUniformReqGradNWM(
|
| 608 |
+
group,
|
| 609 |
+
wrap_fsdp=False,
|
| 610 |
+
device_init_mode=device_init_mode,
|
| 611 |
+
deterministic=deterministic,
|
| 612 |
+
)
|
| 613 |
+
NonUniformReqGradNWM._set_nonuniform_req_grad(ddp_model, req_grad_pattern)
|
| 614 |
+
return ddp_model
|
| 615 |
+
elif fsdp_init_mode == FSDPInitMode.RECURSIVE:
|
| 616 |
+
if fsdp_kwargs is None:
|
| 617 |
+
fsdp_kwargs = {}
|
| 618 |
+
fsdp_model = NonUniformReqGradNWM(
|
| 619 |
+
group,
|
| 620 |
+
wrap_fsdp=True,
|
| 621 |
+
device_init_mode=device_init_mode,
|
| 622 |
+
deterministic=deterministic,
|
| 623 |
+
**fsdp_kwargs,
|
| 624 |
+
)
|
| 625 |
+
if device_init_mode == DEVICEInitMode.DEVICE_AFTER:
|
| 626 |
+
fsdp_model = fsdp_model.to(DEVICE_TYPE)
|
| 627 |
+
NonUniformReqGradNWM._set_nonuniform_req_grad(fsdp_model, req_grad_pattern)
|
| 628 |
+
return fsdp_model
|
| 629 |
+
raise ValueError(f"Unsupported FSDP init mode: {fsdp_init_mode}")
|
| 630 |
+
|
| 631 |
+
|
| 632 |
+
class ModuleWithDelay(FSDPTestModel):
|
| 633 |
+
"""This class wraps a :class:`FSDPTestModel` to optionally add a delay
|
| 634 |
+
after computing the loss and/or before the gradient reduction."""
|
| 635 |
+
|
| 636 |
+
def __init__(
|
| 637 |
+
self,
|
| 638 |
+
module: nn.Module,
|
| 639 |
+
delay_after_loss_ms: int,
|
| 640 |
+
delay_before_reduction_ms: int,
|
| 641 |
+
):
|
| 642 |
+
super().__init__()
|
| 643 |
+
self.delay_after_loss_ms = delay_after_loss_ms
|
| 644 |
+
self.delay_before_reduction_ms = delay_before_reduction_ms
|
| 645 |
+
self.module = module
|
| 646 |
+
|
| 647 |
+
def get_input(self, device):
|
| 648 |
+
return self.module.get_input(device) # type: ignore[operator]
|
| 649 |
+
|
| 650 |
+
def forward(self, x):
|
| 651 |
+
return self.module(x)
|
| 652 |
+
|
| 653 |
+
def get_loss(self, input, output):
|
| 654 |
+
loss = self.module.get_loss(input, output) # type: ignore[operator]
|
| 655 |
+
if self.delay_after_loss_ms > 0:
|
| 656 |
+
if TEST_HPU or TEST_XPU:
|
| 657 |
+
time.sleep(self.delay_after_loss_ms / 1000)
|
| 658 |
+
elif TEST_CUDA:
|
| 659 |
+
torch.cuda._sleep(int(self.delay_after_loss_ms * get_cycles_per_ms()))
|
| 660 |
+
|
| 661 |
+
return loss
|
| 662 |
+
|
| 663 |
+
def run_backward(self, loss):
|
| 664 |
+
orig_reduce_scatter = torch.distributed.reduce_scatter_tensor
|
| 665 |
+
|
| 666 |
+
def _delayed_reduce_scatter(*args, **kwargs):
|
| 667 |
+
if self.delay_before_reduction_ms > 0:
|
| 668 |
+
if TEST_CUDA:
|
| 669 |
+
torch.cuda._sleep(
|
| 670 |
+
int(self.delay_before_reduction_ms * get_cycles_per_ms())
|
| 671 |
+
)
|
| 672 |
+
elif TEST_HPU or TEST_XPU:
|
| 673 |
+
time.sleep(self.delay_before_reduction_ms / 1000)
|
| 674 |
+
return orig_reduce_scatter(*args, **kwargs)
|
| 675 |
+
|
| 676 |
+
with mock.patch(
|
| 677 |
+
"torch.distributed.reduce_scatter_tensor", _delayed_reduce_scatter
|
| 678 |
+
):
|
| 679 |
+
self.module.run_backward(loss) # type: ignore[operator]
|
| 680 |
+
|
| 681 |
+
@staticmethod
|
| 682 |
+
def init(
|
| 683 |
+
module_class: type[FSDPTestModel],
|
| 684 |
+
*model_args: Any,
|
| 685 |
+
delay_after_loss_ms: int,
|
| 686 |
+
delay_before_reduction_ms: int,
|
| 687 |
+
**model_kwargs: Any,
|
| 688 |
+
):
|
| 689 |
+
"""
|
| 690 |
+
Args:
|
| 691 |
+
module_class (Type[FSDPTestModel]): Wrapped module class to which
|
| 692 |
+
to add delays.
|
| 693 |
+
model_args: Positional arguments forwarded to the ``module_class``
|
| 694 |
+
``init()``.
|
| 695 |
+
delay_after_loss_ms (int): Delay after computing the loss/before
|
| 696 |
+
the optimizer step (in ms).
|
| 697 |
+
delay_before_reduction_ms (int): Delay before reduce-scattering
|
| 698 |
+
gradients (in ms).
|
| 699 |
+
model_kwargs: Keyword arguments forwarded to the ``module_class``
|
| 700 |
+
``init()``.
|
| 701 |
+
"""
|
| 702 |
+
return ModuleWithDelay(
|
| 703 |
+
module_class.init(*model_args, **model_kwargs),
|
| 704 |
+
delay_after_loss_ms,
|
| 705 |
+
delay_before_reduction_ms,
|
| 706 |
+
)
|
| 707 |
+
|
| 708 |
+
|
| 709 |
+
class NestedWrappedModuleWithDelay(ModuleWithDelay):
|
| 710 |
+
@staticmethod
|
| 711 |
+
def init( # type: ignore[override]
|
| 712 |
+
group: dist.ProcessGroup,
|
| 713 |
+
fsdp_init_mode: FSDPInitMode,
|
| 714 |
+
device_init_mode: DEVICEInitMode = DEVICEInitMode.DEVICE_AFTER,
|
| 715 |
+
fsdp_kwargs: Optional[dict[str, Any]] = None,
|
| 716 |
+
deterministic: bool = False,
|
| 717 |
+
delay_after_loss_ms: int = 0,
|
| 718 |
+
delay_before_reduction_ms: int = 0,
|
| 719 |
+
):
|
| 720 |
+
return ModuleWithDelay.init(
|
| 721 |
+
NestedWrappedModule,
|
| 722 |
+
group=group,
|
| 723 |
+
fsdp_init_mode=fsdp_init_mode,
|
| 724 |
+
device_init_mode=device_init_mode,
|
| 725 |
+
fsdp_kwargs=fsdp_kwargs,
|
| 726 |
+
deterministic=deterministic,
|
| 727 |
+
delay_after_loss_ms=delay_after_loss_ms,
|
| 728 |
+
delay_before_reduction_ms=delay_before_reduction_ms,
|
| 729 |
+
)
|
| 730 |
+
|
| 731 |
+
|
| 732 |
+
class DummyDDP(nn.Module):
|
| 733 |
+
def __init__(self, module):
|
| 734 |
+
super().__init__()
|
| 735 |
+
self.module = module
|
| 736 |
+
|
| 737 |
+
def forward(self, *args, **kwargs):
|
| 738 |
+
return self.module(*args, **kwargs)
|
| 739 |
+
|
| 740 |
+
|
| 741 |
+
class MixtureOfExperts(NestedWrappedModule):
|
| 742 |
+
def __init__(
|
| 743 |
+
self,
|
| 744 |
+
group: dist.ProcessGroup,
|
| 745 |
+
wrap_fsdp: bool,
|
| 746 |
+
device_init_mode: DEVICEInitMode,
|
| 747 |
+
delay_before_free_ms: int,
|
| 748 |
+
deterministic: bool,
|
| 749 |
+
**fsdp_kwargs,
|
| 750 |
+
):
|
| 751 |
+
super().__init__(
|
| 752 |
+
group=group,
|
| 753 |
+
wrap_fsdp=wrap_fsdp,
|
| 754 |
+
device_init_mode=device_init_mode,
|
| 755 |
+
deterministic=deterministic,
|
| 756 |
+
)
|
| 757 |
+
self.group = group
|
| 758 |
+
self.delay_before_free_ms = delay_before_free_ms
|
| 759 |
+
self.wrap_fsdp = wrap_fsdp
|
| 760 |
+
self.move_to_device = device_init_mode == DEVICEInitMode.DEVICE_BEFORE
|
| 761 |
+
if deterministic:
|
| 762 |
+
# Give each rank different expert parameters
|
| 763 |
+
torch.manual_seed(42 + self.rank)
|
| 764 |
+
d_expert = 23
|
| 765 |
+
d_shared = 12
|
| 766 |
+
d_input = 8
|
| 767 |
+
expert = _move_to_device(nn.Linear(d_expert, d_shared), self.move_to_device)
|
| 768 |
+
|
| 769 |
+
self.num_expert_params = sum(p.numel() for p in expert.parameters())
|
| 770 |
+
for p in expert.parameters():
|
| 771 |
+
p.expert = True # type: ignore[attr-defined]
|
| 772 |
+
|
| 773 |
+
if deterministic:
|
| 774 |
+
# Keep all other parameters the same across ranks
|
| 775 |
+
torch.manual_seed(0)
|
| 776 |
+
|
| 777 |
+
shared = _move_to_device(nn.Linear(d_shared, d_expert), self.move_to_device)
|
| 778 |
+
|
| 779 |
+
if wrap_fsdp:
|
| 780 |
+
# we create a process group of size 1 for the expert params
|
| 781 |
+
expert_group = torch.distributed.new_group(
|
| 782 |
+
[group.rank()]
|
| 783 |
+
) # world size 1 means no shard
|
| 784 |
+
expert = FSDP(expert, expert_group, **fsdp_kwargs) # type: ignore[assignment]
|
| 785 |
+
shared = FSDP(shared, group, **fsdp_kwargs) # type: ignore[assignment]
|
| 786 |
+
|
| 787 |
+
self.module = nn.Sequential(
|
| 788 |
+
_move_to_device(nn.Linear(d_input, d_shared), self.move_to_device),
|
| 789 |
+
shared,
|
| 790 |
+
expert,
|
| 791 |
+
_move_to_device(nn.Linear(d_shared, d_input), self.move_to_device),
|
| 792 |
+
)
|
| 793 |
+
|
| 794 |
+
def forward(self, x):
|
| 795 |
+
if self.delay_before_free_ms > 0:
|
| 796 |
+
expert = self.module[2]
|
| 797 |
+
if isinstance(expert, FSDP):
|
| 798 |
+
orig_reshard = torch.distributed.fsdp._runtime_utils._reshard
|
| 799 |
+
|
| 800 |
+
def _delayed_reshard(*args, **kwargs):
|
| 801 |
+
if TEST_CUDA:
|
| 802 |
+
torch.cuda._sleep(
|
| 803 |
+
int(self.delay_before_free_ms * get_cycles_per_ms())
|
| 804 |
+
)
|
| 805 |
+
elif TEST_HPU or TEST_XPU:
|
| 806 |
+
time.sleep(self.delay_before_free_ms / 1000)
|
| 807 |
+
|
| 808 |
+
return orig_reshard(*args, **kwargs)
|
| 809 |
+
|
| 810 |
+
# This patch covers any `import torch..._reshard` uses.
|
| 811 |
+
with mock.patch(
|
| 812 |
+
"torch.distributed.fsdp._runtime_utils._reshard", _delayed_reshard
|
| 813 |
+
):
|
| 814 |
+
return self.module(x)
|
| 815 |
+
|
| 816 |
+
return self.module(x)
|
| 817 |
+
|
| 818 |
+
def run_backward(self, loss):
|
| 819 |
+
loss.backward()
|
| 820 |
+
# Manually reduce gradients if not wrapped in FullyShardedDataParallel
|
| 821 |
+
if not self.wrap_fsdp:
|
| 822 |
+
with torch.no_grad():
|
| 823 |
+
for p in self.parameters():
|
| 824 |
+
if hasattr(p, "expert"):
|
| 825 |
+
continue # these params don't need grad reduction
|
| 826 |
+
if p.grad is not None:
|
| 827 |
+
p.grad.div_(self.world_size)
|
| 828 |
+
torch.distributed.all_reduce(p.grad, group=self.group)
|
| 829 |
+
|
| 830 |
+
@staticmethod
|
| 831 |
+
def init(
|
| 832 |
+
group: dist.ProcessGroup,
|
| 833 |
+
fsdp_init_mode: FSDPInitMode,
|
| 834 |
+
device_init_mode: DEVICEInitMode,
|
| 835 |
+
fsdp_kwargs: Optional[dict[str, Any]] = None,
|
| 836 |
+
deterministic: bool = False,
|
| 837 |
+
delay_before_free_ms: int = 0,
|
| 838 |
+
):
|
| 839 |
+
"""
|
| 840 |
+
Initializes a :class:`MixtureOfExperts` instance.
|
| 841 |
+
|
| 842 |
+
Args:
|
| 843 |
+
fsdp_init_mode (FSDPInitMode): If ``NO_FSDP``, then does not wrap
|
| 844 |
+
any modules with FSDP. If ``RECURSIVE``, then wraps some nested
|
| 845 |
+
modules with FSDP, including the expert and shared layers, but
|
| 846 |
+
not the top-level module. The model may later be wrapped with a
|
| 847 |
+
top-level FSDP external to this method if desired.
|
| 848 |
+
device_init_mode (DEVICEInitMode): Determines model movement to DEVICE.
|
| 849 |
+
fsdp_kwargs (Optional[Dict[str, Any]]): Optional keyword arguments
|
| 850 |
+
forwarded to the FSDP constructor.
|
| 851 |
+
deterministic (bool): Whether to make the model deterministic
|
| 852 |
+
across constructions.
|
| 853 |
+
delay_before_free_ms (int): Delay before resharding expert
|
| 854 |
+
parameters in the forward pass (in ms).
|
| 855 |
+
"""
|
| 856 |
+
if fsdp_kwargs is None:
|
| 857 |
+
fsdp_kwargs = {}
|
| 858 |
+
if fsdp_init_mode == FSDPInitMode.NO_FSDP:
|
| 859 |
+
return MixtureOfExperts(
|
| 860 |
+
group,
|
| 861 |
+
wrap_fsdp=False,
|
| 862 |
+
device_init_mode=device_init_mode,
|
| 863 |
+
delay_before_free_ms=delay_before_free_ms,
|
| 864 |
+
deterministic=deterministic,
|
| 865 |
+
)
|
| 866 |
+
elif fsdp_init_mode == FSDPInitMode.RECURSIVE:
|
| 867 |
+
# Does not wrap with top-level FSDP
|
| 868 |
+
fsdp_model = MixtureOfExperts(
|
| 869 |
+
group,
|
| 870 |
+
wrap_fsdp=True,
|
| 871 |
+
device_init_mode=device_init_mode,
|
| 872 |
+
delay_before_free_ms=delay_before_free_ms,
|
| 873 |
+
deterministic=deterministic,
|
| 874 |
+
**fsdp_kwargs,
|
| 875 |
+
)
|
| 876 |
+
if device_init_mode == DEVICEInitMode.DEVICE_AFTER:
|
| 877 |
+
fsdp_model = fsdp_model.to(DEVICE_TYPE)
|
| 878 |
+
return fsdp_model
|
| 879 |
+
raise ValueError(f"Unsupported FSDP init mode: {fsdp_init_mode}")
|
| 880 |
+
|
| 881 |
+
|
| 882 |
+
class MLP(nn.Module):
|
| 883 |
+
def __init__(
|
| 884 |
+
self,
|
| 885 |
+
dim: int,
|
| 886 |
+
device: Optional[torch.device] = None,
|
| 887 |
+
*,
|
| 888 |
+
bias: bool = True,
|
| 889 |
+
with_buffer: bool = False,
|
| 890 |
+
dim_multiplier: int = 4,
|
| 891 |
+
):
|
| 892 |
+
super().__init__()
|
| 893 |
+
self.in_proj = nn.Linear(dim, dim_multiplier * dim, device=device, bias=bias)
|
| 894 |
+
self.out_proj = nn.Linear(dim_multiplier * dim, dim, device=device, bias=bias)
|
| 895 |
+
if with_buffer:
|
| 896 |
+
self.register_buffer("buffer", torch.randn((dim,), device=device))
|
| 897 |
+
else:
|
| 898 |
+
self.buffer = None
|
| 899 |
+
|
| 900 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 901 |
+
z = self.in_proj(x)
|
| 902 |
+
z = F.relu(z)
|
| 903 |
+
z = self.out_proj(z)
|
| 904 |
+
z = F.relu(z)
|
| 905 |
+
if self.buffer is not None:
|
| 906 |
+
z = z + self.buffer
|
| 907 |
+
return z
|
| 908 |
+
|
| 909 |
+
def reset_parameters(self):
|
| 910 |
+
if self.buffer is not None:
|
| 911 |
+
torch.nn.init.normal_(self.buffer)
|
| 912 |
+
|
| 913 |
+
|
| 914 |
+
class MLPStack(nn.Sequential):
|
| 915 |
+
def __init__(self, mlp_dim: int, *, with_seq_parallel: bool = False):
|
| 916 |
+
modules: list[nn.Module] = [
|
| 917 |
+
# Use multiplier of 3 to exercise uneven case
|
| 918 |
+
MLP(mlp_dim, dim_multiplier=3),
|
| 919 |
+
MLP(mlp_dim),
|
| 920 |
+
MLP(mlp_dim, dim_multiplier=3),
|
| 921 |
+
]
|
| 922 |
+
if with_seq_parallel:
|
| 923 |
+
modules.append(nn.LayerNorm(mlp_dim, bias=False))
|
| 924 |
+
super().__init__(*modules)
|
| 925 |
+
self.with_seq_parallel = with_seq_parallel
|
| 926 |
+
|
| 927 |
+
def parallelize(
|
| 928 |
+
self,
|
| 929 |
+
tp_mesh: DeviceMesh,
|
| 930 |
+
dp_mesh: DeviceMesh,
|
| 931 |
+
use_activation_checkpointing: bool,
|
| 932 |
+
**fsdp_kwargs,
|
| 933 |
+
) -> "MLPStack":
|
| 934 |
+
parallelize_plan = {
|
| 935 |
+
# Pass `use_local_output=False` to keep as DTensor to preserve
|
| 936 |
+
# uneven activation dims
|
| 937 |
+
"0.in_proj": ColwiseParallel(use_local_output=False),
|
| 938 |
+
"0.out_proj": RowwiseParallel(use_local_output=False),
|
| 939 |
+
"1.in_proj": ColwiseParallel(use_local_output=False),
|
| 940 |
+
"1.out_proj": RowwiseParallel(use_local_output=False),
|
| 941 |
+
"2.in_proj": ColwiseParallel(use_local_output=False),
|
| 942 |
+
"2.out_proj": RowwiseParallel(output_layouts=Shard(1))
|
| 943 |
+
if self.with_seq_parallel
|
| 944 |
+
else RowwiseParallel(),
|
| 945 |
+
}
|
| 946 |
+
if self.with_seq_parallel:
|
| 947 |
+
parallelize_plan["3"] = SequenceParallel(sequence_dim=1)
|
| 948 |
+
parallelize_module(self, device_mesh=tp_mesh, parallelize_plan=parallelize_plan)
|
| 949 |
+
for module in self:
|
| 950 |
+
if isinstance(module, nn.LayerNorm):
|
| 951 |
+
continue
|
| 952 |
+
if use_activation_checkpointing:
|
| 953 |
+
checkpoint(module)
|
| 954 |
+
fully_shard(module, mesh=dp_mesh, **fsdp_kwargs)
|
| 955 |
+
fully_shard(self, mesh=dp_mesh, **fsdp_kwargs)
|
| 956 |
+
return self
|
| 957 |
+
|
| 958 |
+
|
| 959 |
+
class DoubleLinear(nn.Module):
|
| 960 |
+
"""
|
| 961 |
+
This can be used for returning multiple outputs from a module
|
| 962 |
+
(``use_second_linear=True``) or for having an unused module (``False``).
|
| 963 |
+
"""
|
| 964 |
+
|
| 965 |
+
def __init__(self, dim: int, use_second_linear: bool = True):
|
| 966 |
+
super().__init__()
|
| 967 |
+
self.lin1 = nn.Linear(dim, dim)
|
| 968 |
+
self.lin2 = nn.Linear(dim, dim)
|
| 969 |
+
self.relu = nn.ReLU()
|
| 970 |
+
self.use_second_linear = use_second_linear
|
| 971 |
+
|
| 972 |
+
def forward(
|
| 973 |
+
self, x: torch.Tensor
|
| 974 |
+
) -> Union[tuple[torch.Tensor, torch.Tensor], torch.Tensor]:
|
| 975 |
+
if self.use_second_linear:
|
| 976 |
+
return self.relu(self.lin1(x)), self.relu(self.lin2(x))
|
| 977 |
+
return self.relu(self.lin1(x))
|
| 978 |
+
|
| 979 |
+
|
| 980 |
+
# NOTE: For these patch methods, if we want safety under multi-threading (e.g.
|
| 981 |
+
# when using multi-threaded process group), then we want:
|
| 982 |
+
# (1) a barrier immediately after reading the original value to ensure that all
|
| 983 |
+
# threads see the same original value
|
| 984 |
+
# (2) a barrier immediately before restoring the original value to ensure that
|
| 985 |
+
# all threads use the patched value inside the context
|
| 986 |
+
@contextlib.contextmanager
|
| 987 |
+
def patch_all_gather(new_all_gather_into_tensor: Callable):
|
| 988 |
+
orig_all_gather = dist.all_gather_into_tensor
|
| 989 |
+
dist.barrier()
|
| 990 |
+
dist.all_gather_into_tensor = new_all_gather_into_tensor
|
| 991 |
+
try:
|
| 992 |
+
yield
|
| 993 |
+
finally:
|
| 994 |
+
dist.barrier()
|
| 995 |
+
dist.all_gather_into_tensor = orig_all_gather
|
| 996 |
+
|
| 997 |
+
|
| 998 |
+
@contextlib.contextmanager
|
| 999 |
+
def patch_reduce_scatter(new_reduce_scatter_tensor: Callable):
|
| 1000 |
+
orig_reduce_scatter = dist.reduce_scatter_tensor
|
| 1001 |
+
dist.barrier()
|
| 1002 |
+
dist.reduce_scatter_tensor = new_reduce_scatter_tensor
|
| 1003 |
+
try:
|
| 1004 |
+
yield
|
| 1005 |
+
finally:
|
| 1006 |
+
dist.barrier()
|
| 1007 |
+
dist.reduce_scatter_tensor = orig_reduce_scatter
|
| 1008 |
+
|
| 1009 |
+
|
| 1010 |
+
@contextlib.contextmanager
|
| 1011 |
+
def patch_all_reduce(new_all_reduce: Callable):
|
| 1012 |
+
orig_all_reduce = dist.all_reduce
|
| 1013 |
+
dist.barrier()
|
| 1014 |
+
dist.all_reduce = new_all_reduce
|
| 1015 |
+
try:
|
| 1016 |
+
yield
|
| 1017 |
+
finally:
|
| 1018 |
+
dist.barrier()
|
| 1019 |
+
dist.all_reduce = orig_all_reduce
|
| 1020 |
+
|
| 1021 |
+
|
| 1022 |
+
@no_type_check
|
| 1023 |
+
@contextlib.contextmanager
|
| 1024 |
+
def patch_unshard(new_unshard: Callable):
|
| 1025 |
+
orig_unshard = FSDPParamGroup.unshard
|
| 1026 |
+
dist.barrier()
|
| 1027 |
+
FSDPParamGroup.unshard = new_unshard
|
| 1028 |
+
try:
|
| 1029 |
+
yield
|
| 1030 |
+
finally:
|
| 1031 |
+
dist.barrier()
|
| 1032 |
+
FSDPParamGroup.unshard = orig_unshard
|
| 1033 |
+
|
| 1034 |
+
|
| 1035 |
+
@no_type_check
|
| 1036 |
+
@contextlib.contextmanager
|
| 1037 |
+
def patch_reshard(new_reshard: Callable):
|
| 1038 |
+
orig_reshard = FSDPParamGroup.reshard
|
| 1039 |
+
dist.barrier()
|
| 1040 |
+
FSDPParamGroup.reshard = new_reshard
|
| 1041 |
+
try:
|
| 1042 |
+
yield
|
| 1043 |
+
finally:
|
| 1044 |
+
dist.barrier()
|
| 1045 |
+
FSDPParamGroup.reshard = orig_reshard
|
| 1046 |
+
|
| 1047 |
+
|
| 1048 |
+
@no_type_check
|
| 1049 |
+
@contextlib.contextmanager
|
| 1050 |
+
def patch_post_backward(new_post_backward: Callable):
|
| 1051 |
+
orig_post_backward = FSDPParamGroup.post_backward
|
| 1052 |
+
dist.barrier()
|
| 1053 |
+
FSDPParamGroup.post_backward = new_post_backward
|
| 1054 |
+
try:
|
| 1055 |
+
yield
|
| 1056 |
+
finally:
|
| 1057 |
+
dist.barrier()
|
| 1058 |
+
FSDPParamGroup.post_backward = orig_post_backward
|
| 1059 |
+
|
| 1060 |
+
|
| 1061 |
+
@no_type_check
|
| 1062 |
+
@contextlib.contextmanager
|
| 1063 |
+
def patch_register_post_backward_hook_backward(new_backward: Callable):
|
| 1064 |
+
orig_backward = RegisterPostBackwardFunction.backward
|
| 1065 |
+
dist.barrier()
|
| 1066 |
+
RegisterPostBackwardFunction.backward = new_backward
|
| 1067 |
+
try:
|
| 1068 |
+
yield
|
| 1069 |
+
finally:
|
| 1070 |
+
dist.barrier()
|
| 1071 |
+
RegisterPostBackwardFunction.backward = orig_backward
|
| 1072 |
+
|
| 1073 |
+
|
| 1074 |
+
def reduce_scatter_with_assert(
|
| 1075 |
+
cls,
|
| 1076 |
+
orig_reduce_scatter: Callable,
|
| 1077 |
+
assert_fn: Callable, # `assert_fn(output: Tensor)`
|
| 1078 |
+
*args: Any,
|
| 1079 |
+
**kwargs: Any,
|
| 1080 |
+
):
|
| 1081 |
+
if len(args) > 0:
|
| 1082 |
+
output = args[0]
|
| 1083 |
+
elif "output" in kwargs:
|
| 1084 |
+
output = kwargs["output"]
|
| 1085 |
+
else:
|
| 1086 |
+
raise AssertionError(
|
| 1087 |
+
f"Cannot get reduce-scatter output from\nargs: {args}\nkwargs: {kwargs}"
|
| 1088 |
+
)
|
| 1089 |
+
assert_fn(output)
|
| 1090 |
+
return orig_reduce_scatter(*args, **kwargs)
|
| 1091 |
+
|
| 1092 |
+
|
| 1093 |
+
def check_sharded_parity(
|
| 1094 |
+
cls, # unit test class
|
| 1095 |
+
replicated_module: nn.Module,
|
| 1096 |
+
sharded_module: nn.Module,
|
| 1097 |
+
prefixes_to_ignore: tuple[str, ...] = (),
|
| 1098 |
+
):
|
| 1099 |
+
for (replicated_name, replicated_param), (sharded_name, sharded_param) in zip(
|
| 1100 |
+
replicated_module.named_parameters(), sharded_module.named_parameters()
|
| 1101 |
+
):
|
| 1102 |
+
clean_sharded_name = sharded_name
|
| 1103 |
+
for prefix in prefixes_to_ignore:
|
| 1104 |
+
clean_sharded_name = clean_sharded_name.replace(prefix, "")
|
| 1105 |
+
cls.assertEqual(replicated_name, clean_sharded_name)
|
| 1106 |
+
cls.assertIsInstance(sharded_param, DTensor)
|
| 1107 |
+
assert isinstance(sharded_param, DTensor) # mypy
|
| 1108 |
+
mesh, placements = sharded_param.device_mesh, sharded_param.placements
|
| 1109 |
+
if tuple(placements) == (Shard(0), Shard(0)):
|
| 1110 |
+
raise AssertionError(
|
| 1111 |
+
"FSDP's (Shard(0), Shard(0)) layout differs from distribute_tensor(), "
|
| 1112 |
+
"so we cannot check for equality using it"
|
| 1113 |
+
)
|
| 1114 |
+
sharded_ref_param = distribute_tensor(replicated_param, mesh, placements)
|
| 1115 |
+
cls.assertEqual(sharded_param.to_local(), sharded_ref_param.to_local())
|
| 1116 |
+
if replicated_param.grad is None:
|
| 1117 |
+
cls.assertIsNone(sharded_param.grad)
|
| 1118 |
+
continue
|
| 1119 |
+
cls.assertIsNotNone(sharded_param.grad)
|
| 1120 |
+
sharded_ref_grad = distribute_tensor(replicated_param.grad, mesh, placements)
|
| 1121 |
+
cls.assertIsInstance(sharded_param.grad, DTensor)
|
| 1122 |
+
assert isinstance(sharded_param.grad, DTensor) # mypy
|
| 1123 |
+
cls.assertEqual(sharded_param.grad.to_local(), sharded_ref_grad.to_local())
|
| 1124 |
+
|
| 1125 |
+
|
| 1126 |
+
@unittest.skipIf(TEST_XPU, "not-support-multithread")
|
| 1127 |
+
class FSDPTestMultiThread(MultiThreadedTestCase):
|
| 1128 |
+
@property
|
| 1129 |
+
def world_size(self):
|
| 1130 |
+
return DEVICE_COUNT
|
| 1131 |
+
|
| 1132 |
+
def setUp(self):
|
| 1133 |
+
super().setUp()
|
| 1134 |
+
self._spawn_threads()
|
| 1135 |
+
|
| 1136 |
+
def run_subtests(self, *args, **kwargs):
|
| 1137 |
+
return run_subtests(self, *args, **kwargs)
|
| 1138 |
+
|
| 1139 |
+
def perThreadSetUp(self):
|
| 1140 |
+
torch._dynamo.reset()
|
| 1141 |
+
|
| 1142 |
+
def perThreadTearDown(self):
|
| 1143 |
+
torch._dynamo.reset()
|
| 1144 |
+
|
| 1145 |
+
|
| 1146 |
+
class FSDPTest(MultiProcessTestCase):
|
| 1147 |
+
def setUp(self):
|
| 1148 |
+
super().setUp()
|
| 1149 |
+
# Set TORCH_NCCL_DESYNC_DEBUG=0 to disable the NCCL `workCleanupLoop()`,
|
| 1150 |
+
# which can cause unit test flakiness:
|
| 1151 |
+
# https://github.com/pytorch/pytorch/issues/90848
|
| 1152 |
+
os.environ["TORCH_NCCL_DESYNC_DEBUG"] = "0"
|
| 1153 |
+
self._spawn_processes()
|
| 1154 |
+
|
| 1155 |
+
@property
|
| 1156 |
+
def world_size(self):
|
| 1157 |
+
return DEVICE_COUNT
|
| 1158 |
+
|
| 1159 |
+
@property
|
| 1160 |
+
def process_group(self):
|
| 1161 |
+
return dist.distributed_c10d._get_default_group()
|
| 1162 |
+
|
| 1163 |
+
@property
|
| 1164 |
+
def destroy_pg_upon_exit(self) -> bool:
|
| 1165 |
+
# Overriding base test class: do not auto destroy PG upon exit.
|
| 1166 |
+
return False
|
| 1167 |
+
|
| 1168 |
+
@property
|
| 1169 |
+
def init_method(self):
|
| 1170 |
+
return f"{FILE_SCHEMA}{self.file_name}"
|
| 1171 |
+
|
| 1172 |
+
def _check_cpu_offload(self, fsdp_model, cpu_offload):
|
| 1173 |
+
self.assertEqual(cpu_offload, fsdp_model.cpu_offload)
|
| 1174 |
+
|
| 1175 |
+
def _check_backward_prefetch(self, fsdp_model, backward_prefetch):
|
| 1176 |
+
self.assertEqual(backward_prefetch, fsdp_model.backward_prefetch)
|
| 1177 |
+
|
| 1178 |
+
def _check_forward_prefetch(self, fsdp_model, forward_prefetch):
|
| 1179 |
+
self.assertEqual(forward_prefetch, fsdp_model.forward_prefetch)
|
| 1180 |
+
|
| 1181 |
+
def run_subtests(self, *args, **kwargs):
|
| 1182 |
+
return run_subtests(self, *args, **kwargs)
|
| 1183 |
+
|
| 1184 |
+
@classmethod
|
| 1185 |
+
def _run(cls, rank, test_name, file_name, pipe, **kwargs): # type: ignore[override]
|
| 1186 |
+
self = cls(test_name)
|
| 1187 |
+
self.rank = rank
|
| 1188 |
+
self.file_name = file_name
|
| 1189 |
+
fake_pg = kwargs.get("fake_pg", False)
|
| 1190 |
+
|
| 1191 |
+
print(f"dist init r={self.rank}, world={self.world_size}")
|
| 1192 |
+
if torch.accelerator.device_count() < self.world_size:
|
| 1193 |
+
sys.exit(TEST_SKIPS[f"multi-gpu-{self.world_size}"].exit_code)
|
| 1194 |
+
|
| 1195 |
+
# Specify gloo backend to make 'init_process_group()' succeed,
|
| 1196 |
+
# Actual tests will be skipped if there is no enough GPUs.
|
| 1197 |
+
try:
|
| 1198 |
+
if fake_pg:
|
| 1199 |
+
store = torch.testing._internal.distributed.fake_pg.FakeStore()
|
| 1200 |
+
dist.init_process_group(
|
| 1201 |
+
backend="fake",
|
| 1202 |
+
world_size=self.world_size,
|
| 1203 |
+
rank=rank,
|
| 1204 |
+
store=store,
|
| 1205 |
+
)
|
| 1206 |
+
else:
|
| 1207 |
+
dist.init_process_group(
|
| 1208 |
+
init_method=self.init_method,
|
| 1209 |
+
backend=DISTRIBUTED_BACKEND,
|
| 1210 |
+
world_size=int(self.world_size),
|
| 1211 |
+
rank=self.rank,
|
| 1212 |
+
)
|
| 1213 |
+
except RuntimeError as e:
|
| 1214 |
+
if "recompile" in e.args[0]:
|
| 1215 |
+
sys.exit(TEST_SKIPS["backend_unavailable"].exit_code)
|
| 1216 |
+
|
| 1217 |
+
raise
|
| 1218 |
+
|
| 1219 |
+
device_ids = None
|
| 1220 |
+
device_id = self.rank % DEVICE_COUNT
|
| 1221 |
+
if TEST_CUDA or TEST_XPU:
|
| 1222 |
+
torch.accelerator.set_device_index(device_id)
|
| 1223 |
+
device_ids = [device_id]
|
| 1224 |
+
|
| 1225 |
+
# Execute barrier prior to running test to ensure that every process
|
| 1226 |
+
# has finished initialization and that the following test
|
| 1227 |
+
# immediately exiting due to a skip doesn't cause flakiness.
|
| 1228 |
+
dist.barrier(device_ids=device_ids)
|
| 1229 |
+
|
| 1230 |
+
torch._dynamo.reset()
|
| 1231 |
+
self.run_test(test_name, pipe)
|
| 1232 |
+
torch._dynamo.reset()
|
| 1233 |
+
|
| 1234 |
+
dist.barrier(device_ids=device_ids)
|
| 1235 |
+
|
| 1236 |
+
dist.destroy_process_group()
|
| 1237 |
+
|
| 1238 |
+
def _train_for_several_steps(
|
| 1239 |
+
self,
|
| 1240 |
+
model: nn.Module,
|
| 1241 |
+
num_steps: int,
|
| 1242 |
+
autocast: bool,
|
| 1243 |
+
lr: float = 0.01,
|
| 1244 |
+
fsdp_cpu_offload: Optional[CPUOffload] = None,
|
| 1245 |
+
save_model: bool = False,
|
| 1246 |
+
mixed_precision: Optional[MixedPrecision] = None,
|
| 1247 |
+
enable_sharded_grad_scaler: bool = False,
|
| 1248 |
+
use_pure_fp16: bool = False,
|
| 1249 |
+
sharded_grad_scaler_kwargs: Optional[dict[str, Any]] = None,
|
| 1250 |
+
):
|
| 1251 |
+
cpu_offload_params = fsdp_cpu_offload and fsdp_cpu_offload.offload_params
|
| 1252 |
+
|
| 1253 |
+
model_device = next(model.parameters()).device
|
| 1254 |
+
if sharded_grad_scaler_kwargs is None:
|
| 1255 |
+
sharded_grad_scaler_kwargs = {}
|
| 1256 |
+
sharded_grad_scaler = ShardedGradScaler(
|
| 1257 |
+
enabled=enable_sharded_grad_scaler, **sharded_grad_scaler_kwargs
|
| 1258 |
+
)
|
| 1259 |
+
# use SGD with momentum instead of Adam, since Adam is scale invariant
|
| 1260 |
+
# and this makes it bad for tests
|
| 1261 |
+
optim = torch.optim.SGD(model.parameters(), lr=lr, momentum=0.9)
|
| 1262 |
+
for _ in range(num_steps):
|
| 1263 |
+
optim.zero_grad()
|
| 1264 |
+
with torch.amp.autocast(DEVICE_TYPE, enabled=autocast):
|
| 1265 |
+
# Inputs always cuda regardless of cpu offloading, or model.device
|
| 1266 |
+
input = model.module.get_input(torch.device(DEVICE_TYPE)) # type: ignore[operator, union-attr]
|
| 1267 |
+
if use_pure_fp16 or (mixed_precision and not isinstance(model, FSDP)):
|
| 1268 |
+
if isinstance(input, torch.Tensor):
|
| 1269 |
+
input = input.half()
|
| 1270 |
+
else:
|
| 1271 |
+
input = tuple(x.half() for x in input)
|
| 1272 |
+
output = model(*input)
|
| 1273 |
+
# Post-forward, if CPU offloading model param should be on CPU.
|
| 1274 |
+
if (
|
| 1275 |
+
cpu_offload_params
|
| 1276 |
+
and isinstance(model, FSDP)
|
| 1277 |
+
# If not resharding after forward, the parameters are still
|
| 1278 |
+
# exposed as unsharded views into the GPU flat parameter
|
| 1279 |
+
and model.sharding_strategy
|
| 1280 |
+
not in NO_RESHARD_AFTER_FORWARD_STRATEGIES
|
| 1281 |
+
):
|
| 1282 |
+
for p in model.parameters():
|
| 1283 |
+
# Params should always be on CPU
|
| 1284 |
+
self.assertEqual(p.device, torch.device("cpu"))
|
| 1285 |
+
|
| 1286 |
+
loss = model.module.get_loss(input, output).to(model_device) # type: ignore[operator, union-attr]
|
| 1287 |
+
loss = sharded_grad_scaler.scale(loss)
|
| 1288 |
+
|
| 1289 |
+
if not mixed_precision and not use_pure_fp16:
|
| 1290 |
+
assert loss.dtype == torch.float32, (
|
| 1291 |
+
"loss data type should be float32, as the original \
|
| 1292 |
+
parameter data type is float32."
|
| 1293 |
+
)
|
| 1294 |
+
else:
|
| 1295 |
+
if use_pure_fp16:
|
| 1296 |
+
self.assertEqual(loss.dtype, torch.float16)
|
| 1297 |
+
# FSDP loss is fp16, DDP AMP loss is fp32
|
| 1298 |
+
elif isinstance(model, FSDP):
|
| 1299 |
+
assert mixed_precision is not None # mypy
|
| 1300 |
+
self.assertEqual(loss.dtype, mixed_precision.param_dtype)
|
| 1301 |
+
else:
|
| 1302 |
+
self.assertEqual(loss.dtype, torch.float32)
|
| 1303 |
+
model.module.run_backward(loss) # type: ignore[operator, union-attr]
|
| 1304 |
+
# Post-backward, if CPU offloading model params should be on CPU.
|
| 1305 |
+
if cpu_offload_params and isinstance(model, FSDP):
|
| 1306 |
+
for p in model.parameters():
|
| 1307 |
+
# Params should always be on CPU
|
| 1308 |
+
self.assertEqual(p.device, torch.device("cpu"))
|
| 1309 |
+
# Unscale the gradients and step
|
| 1310 |
+
sharded_grad_scaler.step(optim)
|
| 1311 |
+
# Update the scale factor
|
| 1312 |
+
sharded_grad_scaler.update()
|
| 1313 |
+
# if save_model, simulate save + load.
|
| 1314 |
+
if save_model:
|
| 1315 |
+
state_dict = {k: v.clone() for k, v in model.state_dict().items()}
|
| 1316 |
+
# Zero params, if save/load state_dict did not work properly, this
|
| 1317 |
+
# would break the parity test with DDP.
|
| 1318 |
+
_zero_model(model)
|
| 1319 |
+
model.load_state_dict(state_dict)
|
| 1320 |
+
|
| 1321 |
+
if isinstance(model, FSDP):
|
| 1322 |
+
model._assert_state(TrainingState.IDLE)
|
| 1323 |
+
return loss.detach() # type: ignore[possibly-undefined]
|
| 1324 |
+
|
| 1325 |
+
def _test_fsdp_parity(
|
| 1326 |
+
self,
|
| 1327 |
+
model_class: type[FSDPTestModel],
|
| 1328 |
+
fsdp_init_mode: FSDPInitMode,
|
| 1329 |
+
device_init_mode: DEVICEInitMode,
|
| 1330 |
+
ref_init_fn: Optional[Callable] = None,
|
| 1331 |
+
num_iters: int = 2,
|
| 1332 |
+
save_model: bool = True,
|
| 1333 |
+
cpu_offload: CPUOffload = CPUOffload(),
|
| 1334 |
+
backward_prefetch: Optional[BackwardPrefetch] = None,
|
| 1335 |
+
sharding_strategy: Optional[ShardingStrategy] = None,
|
| 1336 |
+
mixed_precision: Optional[MixedPrecision] = None,
|
| 1337 |
+
forward_prefetch: bool = False,
|
| 1338 |
+
use_orig_params: bool = False,
|
| 1339 |
+
enable_sharded_grad_scaler: bool = False,
|
| 1340 |
+
use_pure_fp16: bool = False,
|
| 1341 |
+
init_kwargs: Optional[dict[str, Any]] = None,
|
| 1342 |
+
sharded_grad_scaler_kwargs: Optional[dict[str, Any]] = None,
|
| 1343 |
+
**fsdp_kwargs,
|
| 1344 |
+
):
|
| 1345 |
+
"""
|
| 1346 |
+
Tests FSDP training against a reference, which defaults to DDP but
|
| 1347 |
+
may be customized with ``ref_init_fn``.
|
| 1348 |
+
|
| 1349 |
+
Args:
|
| 1350 |
+
model_class (Type[FSDPTestModel]): A model class that inherits from
|
| 1351 |
+
``FSDPTestModel``, which defines the expected interface.
|
| 1352 |
+
fsdp_init_mode (FSDPInitMode): The mode to initialize the
|
| 1353 |
+
FSDP-wrapped model. This should not be ``NO_FSDP``.
|
| 1354 |
+
ref_init_fn (Optional[Callable]): A callable to invoke that wraps a
|
| 1355 |
+
non-wrapped model to construct the reference model, where this
|
| 1356 |
+
wrapper should provide data parallel semantics. If ``None``,
|
| 1357 |
+
then the callable defaults to the DDP constructor.
|
| 1358 |
+
"""
|
| 1359 |
+
assert fsdp_init_mode != FSDPInitMode.NO_FSDP, (
|
| 1360 |
+
"Expects an FSDP init mode that wraps with FSDP"
|
| 1361 |
+
)
|
| 1362 |
+
if init_kwargs is None:
|
| 1363 |
+
init_kwargs = {}
|
| 1364 |
+
lr = 1e-2
|
| 1365 |
+
rank = self.process_group.rank()
|
| 1366 |
+
# Establish reference behavior with DDP
|
| 1367 |
+
model = model_class.init(
|
| 1368 |
+
self.process_group,
|
| 1369 |
+
FSDPInitMode.NO_FSDP,
|
| 1370 |
+
DEVICEInitMode.DEVICE_BEFORE,
|
| 1371 |
+
deterministic=True,
|
| 1372 |
+
**init_kwargs,
|
| 1373 |
+
)
|
| 1374 |
+
if ref_init_fn is None:
|
| 1375 |
+
if TEST_HPU:
|
| 1376 |
+
ref_model = DDP(
|
| 1377 |
+
model, device_ids=[DEVICE_TYPE], output_device=DEVICE_TYPE
|
| 1378 |
+
)
|
| 1379 |
+
else:
|
| 1380 |
+
ref_model = DDP(model, device_ids=[rank], output_device=rank)
|
| 1381 |
+
else:
|
| 1382 |
+
ref_model = ref_init_fn(model)
|
| 1383 |
+
if use_pure_fp16:
|
| 1384 |
+
ref_model = ref_model.half()
|
| 1385 |
+
ref_loss = self._train_for_several_steps(
|
| 1386 |
+
ref_model,
|
| 1387 |
+
num_iters,
|
| 1388 |
+
autocast=mixed_precision is not None,
|
| 1389 |
+
lr=lr,
|
| 1390 |
+
fsdp_cpu_offload=cpu_offload,
|
| 1391 |
+
mixed_precision=mixed_precision,
|
| 1392 |
+
enable_sharded_grad_scaler=enable_sharded_grad_scaler,
|
| 1393 |
+
use_pure_fp16=use_pure_fp16,
|
| 1394 |
+
sharded_grad_scaler_kwargs=sharded_grad_scaler_kwargs,
|
| 1395 |
+
)
|
| 1396 |
+
ddp_params = list(ref_model.parameters())
|
| 1397 |
+
# Check against FSDP behavior
|
| 1398 |
+
fsdp_kwargs.update(
|
| 1399 |
+
{
|
| 1400 |
+
"cpu_offload": cpu_offload,
|
| 1401 |
+
"backward_prefetch": backward_prefetch,
|
| 1402 |
+
"sharding_strategy": sharding_strategy,
|
| 1403 |
+
"mixed_precision": mixed_precision,
|
| 1404 |
+
"forward_prefetch": forward_prefetch,
|
| 1405 |
+
"use_orig_params": use_orig_params,
|
| 1406 |
+
}
|
| 1407 |
+
)
|
| 1408 |
+
try:
|
| 1409 |
+
fsdp_model = model_class.init(
|
| 1410 |
+
self.process_group,
|
| 1411 |
+
fsdp_init_mode,
|
| 1412 |
+
device_init_mode,
|
| 1413 |
+
fsdp_kwargs,
|
| 1414 |
+
deterministic=True,
|
| 1415 |
+
**init_kwargs,
|
| 1416 |
+
)
|
| 1417 |
+
except Exception as e:
|
| 1418 |
+
raise ValueError(f"Initializing {model_class} raised error {str(e)}") from e
|
| 1419 |
+
if not isinstance(fsdp_model, FSDP):
|
| 1420 |
+
# Enforce that we wrap with top-level FSDP since we are comparing
|
| 1421 |
+
# assuming a data parallel reference and some test models may not
|
| 1422 |
+
# do so in their `init()` method
|
| 1423 |
+
fsdp_model = FSDP(fsdp_model, self.process_group, **fsdp_kwargs)
|
| 1424 |
+
if use_pure_fp16:
|
| 1425 |
+
# Change the model parameter dtype after FSDP initialization
|
| 1426 |
+
fsdp_model = fsdp_model.half()
|
| 1427 |
+
if device_init_mode == DEVICEInitMode.DEVICE_AFTER:
|
| 1428 |
+
fsdp_model = fsdp_model.to(DEVICE_TYPE)
|
| 1429 |
+
offload_params = cpu_offload is not None and cpu_offload.offload_params
|
| 1430 |
+
# Offloading parameters with `DEVICE_AFTER` should raise an error during
|
| 1431 |
+
# lazy initialization due to the parameter devices not being CPU;
|
| 1432 |
+
# otherwise, all parameter devices should be CPU
|
| 1433 |
+
expects_device_error = (
|
| 1434 |
+
offload_params and device_init_mode == DEVICEInitMode.DEVICE_AFTER
|
| 1435 |
+
)
|
| 1436 |
+
expects_cpu_device = (
|
| 1437 |
+
offload_params and device_init_mode != DEVICEInitMode.DEVICE_AFTER
|
| 1438 |
+
)
|
| 1439 |
+
if expects_cpu_device:
|
| 1440 |
+
cpu_device = torch.device("cpu")
|
| 1441 |
+
for param in fsdp_model.parameters():
|
| 1442 |
+
self.assertEqual(param.device, cpu_device)
|
| 1443 |
+
context = (
|
| 1444 |
+
self.assertRaisesRegex(
|
| 1445 |
+
RuntimeError,
|
| 1446 |
+
"An FSDP-managed module with parameter CPU offloading enabled "
|
| 1447 |
+
f"has parameters on {DEVICE_TYPE}",
|
| 1448 |
+
)
|
| 1449 |
+
if expects_device_error
|
| 1450 |
+
else nullcontext()
|
| 1451 |
+
)
|
| 1452 |
+
with context:
|
| 1453 |
+
fsdp_loss = self._train_for_several_steps(
|
| 1454 |
+
fsdp_model,
|
| 1455 |
+
num_iters,
|
| 1456 |
+
autocast=False,
|
| 1457 |
+
lr=lr,
|
| 1458 |
+
fsdp_cpu_offload=cpu_offload,
|
| 1459 |
+
save_model=save_model,
|
| 1460 |
+
mixed_precision=mixed_precision,
|
| 1461 |
+
enable_sharded_grad_scaler=enable_sharded_grad_scaler,
|
| 1462 |
+
use_pure_fp16=use_pure_fp16,
|
| 1463 |
+
sharded_grad_scaler_kwargs=sharded_grad_scaler_kwargs,
|
| 1464 |
+
)
|
| 1465 |
+
# No need to check for parameter and loss parity if expecting an error
|
| 1466 |
+
if expects_device_error:
|
| 1467 |
+
return
|
| 1468 |
+
# Check parameter devices are CPU if offloading to CPU before calling
|
| 1469 |
+
# `get_full_params()`, which will cast the parameters to FP32
|
| 1470 |
+
if offload_params:
|
| 1471 |
+
cpu_device = torch.device("cpu")
|
| 1472 |
+
for param in fsdp_model.parameters():
|
| 1473 |
+
self.assertEqual(param.device, cpu_device)
|
| 1474 |
+
fsdp_loss = fsdp_loss.to(DEVICE_TYPE)
|
| 1475 |
+
fsdp_unsharded_params = get_full_params(fsdp_model)
|
| 1476 |
+
# Do not check dtype since the reference DDP loss may not be the same
|
| 1477 |
+
# dtype as the FSDP loss in the case of mixed precision
|
| 1478 |
+
torch.testing.assert_close(ref_loss, fsdp_loss, check_dtype=False)
|
| 1479 |
+
# Do not check for parameter parity if using mixed precision since (1)
|
| 1480 |
+
# the DDP parameters are in FP16 (from `half()`) while the FSDP
|
| 1481 |
+
# parameters are in FP32 (from `summon_full_params()`) and (2) DDP runs
|
| 1482 |
+
# the optimizer in FP16 while FSDP runs it in FP32
|
| 1483 |
+
# TODO: Disable checking the parameters for pure FP16 due to floating
|
| 1484 |
+
# point inaccuracy. Note that this means that the backward pass is not
|
| 1485 |
+
# checked: https://github.com/pytorch/pytorch/issues/90784
|
| 1486 |
+
if mixed_precision is None and not use_pure_fp16:
|
| 1487 |
+
self.assertEqual(
|
| 1488 |
+
ddp_params,
|
| 1489 |
+
fsdp_unsharded_params,
|
| 1490 |
+
exact_device=True,
|
| 1491 |
+
msg="FSDP did not match DDP",
|
| 1492 |
+
)
|
| 1493 |
+
|
| 1494 |
+
|
| 1495 |
+
def compiled_fsdp_test(compile_compute_on_module: Optional[type] = None):
|
| 1496 |
+
def fully_shard_with_compiled_compute(*args, **kwargs):
|
| 1497 |
+
torch.distributed.fsdp.fully_shard(*args, **kwargs) # type: ignore[operator]
|
| 1498 |
+
if compile_compute_on_module is None or isinstance(
|
| 1499 |
+
args[0], compile_compute_on_module
|
| 1500 |
+
):
|
| 1501 |
+
args[0].compile()
|
| 1502 |
+
|
| 1503 |
+
class FullyShardMode(Enum):
|
| 1504 |
+
EAGER = auto()
|
| 1505 |
+
COMPILED_COMPUTE = auto()
|
| 1506 |
+
|
| 1507 |
+
def decorator(func):
|
| 1508 |
+
@wraps(func)
|
| 1509 |
+
def wrapper(*args, **kwargs):
|
| 1510 |
+
original_fully_shard: Any = torch.distributed.fsdp.fully_shard
|
| 1511 |
+
for mode in FullyShardMode:
|
| 1512 |
+
if mode != FullyShardMode.EAGER and not has_triton():
|
| 1513 |
+
warnings.warn("Inductor on GPU needs Triton and recent GPU arch")
|
| 1514 |
+
continue
|
| 1515 |
+
# barrier to ensure thread reading the same value
|
| 1516 |
+
original_skip_fsdp_hooks = torch._dynamo.config.skip_fsdp_hooks
|
| 1517 |
+
original_compile_threads = torch._inductor.config.compile_threads
|
| 1518 |
+
torch.distributed.barrier()
|
| 1519 |
+
|
| 1520 |
+
if mode == FullyShardMode.EAGER:
|
| 1521 |
+
fully_shard_patch = original_fully_shard
|
| 1522 |
+
elif mode == FullyShardMode.COMPILED_COMPUTE:
|
| 1523 |
+
torch._dynamo.config.skip_fsdp_hooks = True
|
| 1524 |
+
torch._inductor.config.compile_threads = 1
|
| 1525 |
+
fully_shard_patch = fully_shard_with_compiled_compute # type: ignore[assignment]
|
| 1526 |
+
else:
|
| 1527 |
+
raise NotImplementedError(
|
| 1528 |
+
f"Need to implement FullyShardMode={mode}"
|
| 1529 |
+
)
|
| 1530 |
+
|
| 1531 |
+
# fully_shard is imported as a global
|
| 1532 |
+
# through `from ... import fully_shard`
|
| 1533 |
+
func.__globals__[original_fully_shard.__name__] = fully_shard_patch
|
| 1534 |
+
func(*args, **kwargs)
|
| 1535 |
+
# other threads use patched func before this thread restores
|
| 1536 |
+
torch.distributed.barrier()
|
| 1537 |
+
func.__globals__[original_fully_shard.__name__] = original_fully_shard
|
| 1538 |
+
torch._dynamo.config.skip_fsdp_hooks = original_skip_fsdp_hooks
|
| 1539 |
+
torch._inductor.config.compile_threads = original_compile_threads
|
| 1540 |
+
|
| 1541 |
+
return wrapper
|
| 1542 |
+
|
| 1543 |
+
return decorator
|
| 1544 |
+
|
| 1545 |
+
|
| 1546 |
+
class SkipModule(nn.Module):
|
| 1547 |
+
def __init__(self) -> None:
|
| 1548 |
+
super().__init__()
|
| 1549 |
+
self.lin = nn.Linear(10, 10, bias=False)
|
| 1550 |
+
|
| 1551 |
+
def forward(self, x):
|
| 1552 |
+
return self.lin(x)
|
| 1553 |
+
|
| 1554 |
+
|
| 1555 |
+
class NestedLinear(nn.Module):
|
| 1556 |
+
def __init__(self, fsdp_wrap):
|
| 1557 |
+
super().__init__()
|
| 1558 |
+
if fsdp_wrap:
|
| 1559 |
+
self.nested_linear = wrap(nn.Linear(10, 10, bias=False).to(DEVICE_TYPE))
|
| 1560 |
+
else:
|
| 1561 |
+
self.nested_linear = nn.Linear(10, 10, bias=False).to(DEVICE_TYPE)
|
| 1562 |
+
|
| 1563 |
+
def forward(self, x):
|
| 1564 |
+
return self.nested_linear(x)
|
| 1565 |
+
|
| 1566 |
+
|
| 1567 |
+
class SkipModel(nn.Module):
|
| 1568 |
+
def __init__(self, double_nest):
|
| 1569 |
+
super().__init__()
|
| 1570 |
+
self.linear = nn.Linear(10, 10, bias=False).to(DEVICE_TYPE)
|
| 1571 |
+
self.linear_skip = SkipModule().to(DEVICE_TYPE)
|
| 1572 |
+
self.nested_linear = wrap(
|
| 1573 |
+
NestedLinear(fsdp_wrap=double_nest), device_id=DEVICE_TYPE
|
| 1574 |
+
)
|
| 1575 |
+
|
| 1576 |
+
def forward(self, x):
|
| 1577 |
+
x = self.linear(x)
|
| 1578 |
+
x = self.linear_skip(x)
|
| 1579 |
+
x = self.nested_linear(x)
|
| 1580 |
+
return x
|
pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/common_jit.py
ADDED
|
@@ -0,0 +1,323 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: ignore-errors
|
| 2 |
+
|
| 3 |
+
# Torch
|
| 4 |
+
import torch
|
| 5 |
+
import torch.cuda
|
| 6 |
+
import torch.jit
|
| 7 |
+
import torch.jit._logging
|
| 8 |
+
import torch.jit.frontend
|
| 9 |
+
import torch.jit.quantized
|
| 10 |
+
|
| 11 |
+
# Testing utils
|
| 12 |
+
from torch.testing._internal.common_dtype import floating_and_complex_types_and
|
| 13 |
+
from torch.testing._internal.common_utils import TestCase, \
|
| 14 |
+
freeze_rng_state, TemporaryFileName, enable_profiling_mode_for_profiling_tests, is_iterable_of_tensors
|
| 15 |
+
from torch.testing._internal.common_utils import enable_profiling_mode # noqa: F401
|
| 16 |
+
|
| 17 |
+
# Standard library
|
| 18 |
+
from itertools import chain
|
| 19 |
+
from typing import Union
|
| 20 |
+
from torch._C import TensorType
|
| 21 |
+
|
| 22 |
+
import io
|
| 23 |
+
|
| 24 |
+
def check_output_types(self, func, ref_outputs, args, kwargs):
|
| 25 |
+
graph = getattr(func, 'last_graph', None)
|
| 26 |
+
types = [o.type() for o in graph.outputs()]
|
| 27 |
+
self.assertTrue(len(types) == 1)
|
| 28 |
+
t = types[0]
|
| 29 |
+
torch._C._jit_assert_is_instance(ref_outputs, t)
|
| 30 |
+
|
| 31 |
+
# Test names in this set are only checked for a single derivative
|
| 32 |
+
nn_functional_single_grad = frozenset('test_nn_' + name for name in [
|
| 33 |
+
'pdist',
|
| 34 |
+
'multilabel_margin_loss',
|
| 35 |
+
'max_unpool3d',
|
| 36 |
+
'multi_margin_loss',
|
| 37 |
+
'binary_cross_entropy',
|
| 38 |
+
'binary_cross_entropy_size_average',
|
| 39 |
+
'ctc_loss',
|
| 40 |
+
'grid_sample',
|
| 41 |
+
])
|
| 42 |
+
|
| 43 |
+
def check_against_reference(self, func, reference_func, output_func, args, kwargs=None,
|
| 44 |
+
allow_unused=True, check_types=True, no_grad=False, no_gradgrad=False):
|
| 45 |
+
"""Verifies a function performs identically to some reference implementation.
|
| 46 |
+
|
| 47 |
+
Commonly, this is used to verify that a JIT implementation
|
| 48 |
+
(output_func) matches the behavior of the eager implementation
|
| 49 |
+
(reference_func).
|
| 50 |
+
"""
|
| 51 |
+
kwargs = kwargs if kwargs else {}
|
| 52 |
+
|
| 53 |
+
def allSum(vs):
|
| 54 |
+
if isinstance(vs, torch.Tensor):
|
| 55 |
+
vs = (vs,)
|
| 56 |
+
return sum((i + 1) * v.sum().abs() if v.dtype.is_complex else (i + 1) * v.sum()
|
| 57 |
+
for i, v in enumerate(vs)
|
| 58 |
+
if v is not None and v.dtype in floating_and_complex_types_and(torch.half, torch.bfloat16))
|
| 59 |
+
|
| 60 |
+
def clone_tensor(t, preserve_requires_grad):
|
| 61 |
+
require_grad = preserve_requires_grad and t.requires_grad
|
| 62 |
+
return t.detach().clone().requires_grad_(require_grad)
|
| 63 |
+
|
| 64 |
+
def clone_inputs(preserve_requires_grad: bool):
|
| 65 |
+
inputs: list[Union[torch.Tensor, list[torch.Tensor]]] = []
|
| 66 |
+
|
| 67 |
+
for arg in args:
|
| 68 |
+
if isinstance(arg, torch.Tensor):
|
| 69 |
+
inputs.append(clone_tensor(arg, preserve_requires_grad))
|
| 70 |
+
elif is_iterable_of_tensors(arg):
|
| 71 |
+
inputs.append([clone_tensor(t, preserve_requires_grad) for t in arg])
|
| 72 |
+
else:
|
| 73 |
+
inputs.append(arg)
|
| 74 |
+
|
| 75 |
+
return inputs
|
| 76 |
+
|
| 77 |
+
# Returns tensors in args that requires_grad, including tensors in TensorList args
|
| 78 |
+
def get_recording_tensors(args):
|
| 79 |
+
recording_tensors: list[torch.Tensor] = []
|
| 80 |
+
|
| 81 |
+
for arg in args:
|
| 82 |
+
if isinstance(arg, torch.Tensor) and arg.requires_grad:
|
| 83 |
+
recording_tensors.append(arg)
|
| 84 |
+
elif is_iterable_of_tensors(arg):
|
| 85 |
+
recording_tensors.extend(filter(lambda t: t.requires_grad, arg))
|
| 86 |
+
|
| 87 |
+
return recording_tensors
|
| 88 |
+
|
| 89 |
+
# test no gradients case
|
| 90 |
+
nograd_inputs = clone_inputs(preserve_requires_grad=False)
|
| 91 |
+
outputs = self.runAndSaveRNG(reference_func, nograd_inputs, kwargs)
|
| 92 |
+
with enable_profiling_mode_for_profiling_tests():
|
| 93 |
+
outputs_test = self.runAndSaveRNG(func, nograd_inputs, kwargs)
|
| 94 |
+
self.assertEqual(outputs, outputs_test)
|
| 95 |
+
|
| 96 |
+
if check_types:
|
| 97 |
+
check_output_types(self, func, outputs_test, nograd_inputs, kwargs)
|
| 98 |
+
|
| 99 |
+
if no_grad:
|
| 100 |
+
# skip grad tests
|
| 101 |
+
return
|
| 102 |
+
|
| 103 |
+
with enable_profiling_mode_for_profiling_tests():
|
| 104 |
+
# test single grad case
|
| 105 |
+
recording_inputs = clone_inputs(preserve_requires_grad=True)
|
| 106 |
+
recording_tensors = get_recording_tensors(recording_inputs)
|
| 107 |
+
outputs = output_func(self.runAndSaveRNG(reference_func, recording_inputs, kwargs))
|
| 108 |
+
grads = torch.autograd.grad(allSum(outputs), recording_tensors,
|
| 109 |
+
allow_unused=allow_unused)
|
| 110 |
+
outputs_test = output_func(self.runAndSaveRNG(func, recording_inputs, kwargs))
|
| 111 |
+
grads_test = torch.autograd.grad(allSum(outputs_test), recording_tensors,
|
| 112 |
+
allow_unused=allow_unused)
|
| 113 |
+
self.assertEqual(outputs, outputs_test)
|
| 114 |
+
self.assertEqual(grads, grads_test)
|
| 115 |
+
# test the grad grad case
|
| 116 |
+
if self._testMethodName in nn_functional_single_grad or no_gradgrad:
|
| 117 |
+
return
|
| 118 |
+
|
| 119 |
+
outputs = output_func(self.runAndSaveRNG(reference_func, recording_inputs, kwargs))
|
| 120 |
+
l1 = allSum(outputs)
|
| 121 |
+
grads = torch.autograd.grad(l1, recording_tensors, create_graph=True,
|
| 122 |
+
allow_unused=allow_unused)
|
| 123 |
+
|
| 124 |
+
l2 = (allSum(grads) * l1)
|
| 125 |
+
grads2 = torch.autograd.grad(l2, recording_tensors, allow_unused=allow_unused)
|
| 126 |
+
recording_inputs = clone_inputs(preserve_requires_grad=True)
|
| 127 |
+
recording_tensors = get_recording_tensors(recording_inputs)
|
| 128 |
+
outputs_test = output_func(self.runAndSaveRNG(func, recording_inputs, kwargs))
|
| 129 |
+
l1_test = allSum(outputs_test)
|
| 130 |
+
grads_test = torch.autograd.grad(
|
| 131 |
+
l1_test, recording_tensors, create_graph=True, allow_unused=allow_unused)
|
| 132 |
+
|
| 133 |
+
l2_test = (allSum(grads_test) * l1_test)
|
| 134 |
+
grads2_test = torch.autograd.grad(l2_test, recording_tensors, allow_unused=allow_unused)
|
| 135 |
+
|
| 136 |
+
self.assertEqual(outputs, outputs_test)
|
| 137 |
+
self.assertEqual(grads, grads_test)
|
| 138 |
+
for g2, g2_test in zip(grads2, grads2_test):
|
| 139 |
+
if g2 is None and g2_test is None:
|
| 140 |
+
continue
|
| 141 |
+
self.assertEqual(g2, g2_test, atol=5e-4, rtol=1e-4)
|
| 142 |
+
|
| 143 |
+
class JitCommonTestCase(TestCase):
|
| 144 |
+
def createFunctionFromGraph(self, trace):
|
| 145 |
+
graph = trace if isinstance(trace, torch._C.Graph) else trace.graph()
|
| 146 |
+
return torch._C._create_function_from_graph("forward", graph)
|
| 147 |
+
|
| 148 |
+
def assertExportImport(self, trace, inputs):
|
| 149 |
+
m = self.createFunctionFromGraph(trace)
|
| 150 |
+
self.assertExportImportModule(m, inputs)
|
| 151 |
+
|
| 152 |
+
def assertExportImportModule(self, m, inputs):
|
| 153 |
+
m_import = self.getExportImportCopy(m)
|
| 154 |
+
a = self.runAndSaveRNG(m, inputs)
|
| 155 |
+
b = self.runAndSaveRNG(m_import, inputs)
|
| 156 |
+
self.assertEqual(a, b, "Results of original model and "
|
| 157 |
+
"exported/imported version of model differed")
|
| 158 |
+
|
| 159 |
+
def runAndSaveRNG(self, func, inputs, kwargs=None):
|
| 160 |
+
kwargs = kwargs if kwargs else {}
|
| 161 |
+
with freeze_rng_state():
|
| 162 |
+
results = func(*inputs, **kwargs)
|
| 163 |
+
return results
|
| 164 |
+
|
| 165 |
+
def getExportImportCopy(self, m, also_test_file=True, map_location=None):
|
| 166 |
+
buffer = io.BytesIO()
|
| 167 |
+
torch.jit.save(m, buffer)
|
| 168 |
+
buffer.seek(0)
|
| 169 |
+
imported = torch.jit.load(buffer, map_location=map_location)
|
| 170 |
+
|
| 171 |
+
if not also_test_file:
|
| 172 |
+
return imported
|
| 173 |
+
|
| 174 |
+
with TemporaryFileName() as fname:
|
| 175 |
+
torch.jit.save(imported, fname)
|
| 176 |
+
return torch.jit.load(fname, map_location=map_location)
|
| 177 |
+
|
| 178 |
+
def autoDiffErrorMessage(self, should_autodiff_node, nodes_not_in_diff_graph,
|
| 179 |
+
fusion_nodes_not_found, non_fusible_nodes_being_fused,
|
| 180 |
+
fusion_nodes_found, nodes_in_diff_graph):
|
| 181 |
+
err_msg = "\nFailure in testing nodes' autodifferentiation. "
|
| 182 |
+
if should_autodiff_node:
|
| 183 |
+
err_msg += "One or more nodes were expected to be autodiffed, " \
|
| 184 |
+
"but were not found in specified fusible/nonfusible " \
|
| 185 |
+
"DifferentiableGraph groups. \nSpecifically:"
|
| 186 |
+
# The node is intended to appear in a differentiable graph but doesn't
|
| 187 |
+
diff_nodes_missing = []
|
| 188 |
+
# The node is intended to appear in a differentiable graph
|
| 189 |
+
# outside of a fusion group but instead is in a fusion group
|
| 190 |
+
diff_nodes_in_fusion = []
|
| 191 |
+
# The node is intended to appear in a fusion group but doesn't
|
| 192 |
+
fusion_nodes_missing = []
|
| 193 |
+
# The node is intended to appear in a fusion group but instead
|
| 194 |
+
# is just in an outer differentiable graph
|
| 195 |
+
fusion_nodes_in_diff = []
|
| 196 |
+
for node in nodes_not_in_diff_graph:
|
| 197 |
+
if node in non_fusible_nodes_being_fused:
|
| 198 |
+
diff_nodes_in_fusion.append(node)
|
| 199 |
+
else:
|
| 200 |
+
diff_nodes_missing.append(node)
|
| 201 |
+
for node in fusion_nodes_not_found:
|
| 202 |
+
if node in nodes_in_diff_graph:
|
| 203 |
+
fusion_nodes_in_diff.append(node)
|
| 204 |
+
else:
|
| 205 |
+
fusion_nodes_missing.append(node)
|
| 206 |
+
if len(diff_nodes_missing) > 0:
|
| 207 |
+
err_msg += f"\n {diff_nodes_missing} were not in one of the " \
|
| 208 |
+
"DifferentiableGraphs when they were expected to be. " \
|
| 209 |
+
"Did you intend for these nodes to be autodiffed? " \
|
| 210 |
+
"If not, remove them from the list of nonfusible nodes."
|
| 211 |
+
if len(diff_nodes_in_fusion) > 0:
|
| 212 |
+
err_msg += f"\n {diff_nodes_in_fusion} were found in one of the FusionGroups " \
|
| 213 |
+
"when they were expected to be just in a DifferentiableGraph. If it was " \
|
| 214 |
+
"intended for these nodes to be in FusionGroups, reclassify these nodes as " \
|
| 215 |
+
"fusible nodes. If these nodes were not intended to be fused, your " \
|
| 216 |
+
"autodifferentiation logic might be wrong."
|
| 217 |
+
if len(fusion_nodes_missing) > 0:
|
| 218 |
+
err_msg += f"\n {fusion_nodes_missing} were not in one of the FusionGroups " \
|
| 219 |
+
"of the DifferentiableGraphs when they were expected to be. " \
|
| 220 |
+
"They were also not found in an outer DifferentiableGraph. Did you " \
|
| 221 |
+
"intend for these nodes to be autodifferentiated? If not, you should " \
|
| 222 |
+
"remove these nodes from the test's fusible nodes. Otherwise your " \
|
| 223 |
+
"autodifferentiation logic might be wrong."
|
| 224 |
+
if len(fusion_nodes_in_diff) > 0:
|
| 225 |
+
err_msg += f"\n {fusion_nodes_in_diff} were not in one of the FusionGroups " \
|
| 226 |
+
"of the DifferentiableGraphs when they were expected to be, " \
|
| 227 |
+
"instead they were found just in an outer DifferentiableGraph. " \
|
| 228 |
+
"Did you intend for these nodes to be fused? If not, you should " \
|
| 229 |
+
"move these nodes into the test's nonfusible nodes. Otherwise your " \
|
| 230 |
+
"autodifferentiation logic might be wrong."
|
| 231 |
+
else:
|
| 232 |
+
err_msg += "One or more nodes were not expected to be autodiffed " \
|
| 233 |
+
"but were found in a DifferentiableGraph or in a FusionGroup " \
|
| 234 |
+
"of a DifferentiableGraph. Did you intend for these nodes to be " \
|
| 235 |
+
"autodiffed? If so, change this test to expect autodifferentiation. " \
|
| 236 |
+
"\nSpecifically:"
|
| 237 |
+
if len(fusion_nodes_found) > 0:
|
| 238 |
+
err_msg += f"\n {fusion_nodes_found} were not expected to be in " \
|
| 239 |
+
"one of the DifferentiableGraphs, but appeared in a FusionGroup " \
|
| 240 |
+
"of a DifferentiableGraph. "
|
| 241 |
+
if len(nodes_in_diff_graph) > 0:
|
| 242 |
+
err_msg += f"\n {nodes_in_diff_graph} were not expected to " \
|
| 243 |
+
"be in one of the DifferentiableGraphs but were."
|
| 244 |
+
return err_msg
|
| 245 |
+
|
| 246 |
+
def assertAutodiffNode(self, graph, should_autodiff_node, nonfusible_nodes, fusible_nodes):
|
| 247 |
+
diff_nodes = graph.findAllNodes('prim::DifferentiableGraph')
|
| 248 |
+
diff_subgraphs = [node.g('Subgraph') for node in diff_nodes]
|
| 249 |
+
|
| 250 |
+
# Note: currently no tests have fusible_nodes
|
| 251 |
+
fusion_nodes = list(chain.from_iterable([g.findAllNodes('prim::FusionGroup') for g in diff_subgraphs]))
|
| 252 |
+
fusion_subgraphs = [node.g('Subgraph') for node in fusion_nodes]
|
| 253 |
+
|
| 254 |
+
# For any non-fusible node, it must show up in one of the DifferentiableGraphs.
|
| 255 |
+
nodes_in_diff_graph = []
|
| 256 |
+
nodes_not_in_diff_graph = []
|
| 257 |
+
non_fusible_nodes_being_fused = []
|
| 258 |
+
for node in nonfusible_nodes:
|
| 259 |
+
if any(g.findNode(node) is not None for g in diff_subgraphs):
|
| 260 |
+
nodes_in_diff_graph.append(node)
|
| 261 |
+
else:
|
| 262 |
+
nodes_not_in_diff_graph.append(node)
|
| 263 |
+
if any(g.findNode(node) is not None for g in fusion_subgraphs):
|
| 264 |
+
non_fusible_nodes_being_fused.append(node)
|
| 265 |
+
found_all_nonfusible_nodes = len(nodes_in_diff_graph) == len(nonfusible_nodes)
|
| 266 |
+
|
| 267 |
+
# For any fusible node, it must show up in one of the FusionGroups in one of the DifferentiableGraphs.
|
| 268 |
+
fusion_nodes_found = []
|
| 269 |
+
fusion_nodes_not_found = []
|
| 270 |
+
for node in fusible_nodes:
|
| 271 |
+
if any(g.findNode(node) is not None for g in fusion_subgraphs):
|
| 272 |
+
fusion_nodes_found.append(node)
|
| 273 |
+
else:
|
| 274 |
+
fusion_nodes_not_found.append(node)
|
| 275 |
+
found_all_fusible_nodes = len(fusion_nodes_found) == len(fusible_nodes)
|
| 276 |
+
|
| 277 |
+
if should_autodiff_node is not None:
|
| 278 |
+
err_msg = self.autoDiffErrorMessage(should_autodiff_node,
|
| 279 |
+
nodes_not_in_diff_graph,
|
| 280 |
+
fusion_nodes_not_found,
|
| 281 |
+
non_fusible_nodes_being_fused,
|
| 282 |
+
fusion_nodes_found,
|
| 283 |
+
nodes_in_diff_graph)
|
| 284 |
+
self.assertEqual(should_autodiff_node,
|
| 285 |
+
found_all_nonfusible_nodes and found_all_fusible_nodes, err_msg)
|
| 286 |
+
|
| 287 |
+
def checkShapeAnalysis(self, out_sizes: Union[list[int], list[list[int]]],
|
| 288 |
+
traced_graph, assert_propagation, constant_prop=True):
|
| 289 |
+
# repropagte input shapes provided by tracing,
|
| 290 |
+
prev_symbolic_shapes_test_enabled = torch._C._jit_symbolic_shapes_test_mode_enabled()
|
| 291 |
+
for enable_test_mode in [True, False]:
|
| 292 |
+
# here we are testing allowing/disallowing substituting in complete shapes as constants,
|
| 293 |
+
# disallowing constants helps stress test partial eval and substitution pipeline
|
| 294 |
+
torch._C._jit_set_symbolic_shapes_test_mode(enable_test_mode)
|
| 295 |
+
torch._C._jit_erase_non_input_shape_information(traced_graph)
|
| 296 |
+
if constant_prop:
|
| 297 |
+
torch._C._jit_pass_constant_propagation(traced_graph)
|
| 298 |
+
torch._C._jit_pass_propagate_shapes_on_graph(traced_graph)
|
| 299 |
+
# Add sizes to default tensor type to avoid checking something out of scope
|
| 300 |
+
# and difficulties with tracer leaving in other parts of tensor type
|
| 301 |
+
output = next(traced_graph.outputs()).type()
|
| 302 |
+
|
| 303 |
+
def test_type(type, actual_size):
|
| 304 |
+
sizes = type.symbolic_sizes()
|
| 305 |
+
out_type = TensorType.get().with_sizes(sizes)
|
| 306 |
+
actual_type = TensorType.get().with_sizes(actual_size)
|
| 307 |
+
|
| 308 |
+
# always check actual shape is a subtype of the output
|
| 309 |
+
self.assertTrue(actual_type.isSubtypeOf(out_type))
|
| 310 |
+
|
| 311 |
+
# and then if assertion flag is provided, check shape analysis
|
| 312 |
+
# is successful
|
| 313 |
+
if assert_propagation:
|
| 314 |
+
self.assertEqual(out_type.sizes(), actual_size)
|
| 315 |
+
|
| 316 |
+
if output.isSubtypeOf(torch._C.TensorType.get()):
|
| 317 |
+
test_type(output, out_sizes)
|
| 318 |
+
else:
|
| 319 |
+
tuple_elements = output.elements()
|
| 320 |
+
for i in range(len(tuple_elements)):
|
| 321 |
+
test_type(tuple_elements[i], out_sizes[i])
|
| 322 |
+
|
| 323 |
+
torch._C._jit_set_symbolic_shapes_test_mode(prev_symbolic_shapes_test_enabled)
|
pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/common_methods_invocations.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/common_mkldnn.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: ignore-errors
|
| 2 |
+
|
| 3 |
+
import contextlib
|
| 4 |
+
import functools
|
| 5 |
+
import inspect
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def bf32_is_not_fp32():
|
| 11 |
+
if not torch.backends.mkldnn.is_available():
|
| 12 |
+
return False
|
| 13 |
+
if not torch.ops.mkldnn._is_mkldnn_bf16_supported():
|
| 14 |
+
return False
|
| 15 |
+
return True
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def tf32_is_not_fp32():
|
| 19 |
+
if not torch.backends.mkldnn.is_available():
|
| 20 |
+
return False
|
| 21 |
+
if not torch._C._cpu._is_amx_fp16_supported():
|
| 22 |
+
return False
|
| 23 |
+
return True
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
@contextlib.contextmanager
|
| 27 |
+
def reduced_f32_off():
|
| 28 |
+
old_matmul_precision = torch.backends.mkldnn.matmul.fp32_precision
|
| 29 |
+
old_conv_precision = torch.backends.mkldnn.conv.fp32_precision
|
| 30 |
+
try:
|
| 31 |
+
torch.backends.mkldnn.matmul.fp32_precision = "ieee"
|
| 32 |
+
torch.backends.mkldnn.conv.fp32_precision = "ieee"
|
| 33 |
+
yield
|
| 34 |
+
finally:
|
| 35 |
+
torch.backends.mkldnn.matmul.fp32_precision = old_matmul_precision
|
| 36 |
+
torch.backends.mkldnn.conv.fp32_precision = old_conv_precision
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
@contextlib.contextmanager
|
| 40 |
+
def bf32_on(self, bf32_precision=1e-2):
|
| 41 |
+
old_matmul_precision = torch.backends.mkldnn.matmul.fp32_precision
|
| 42 |
+
old_conv_precision = torch.backends.mkldnn.conv.fp32_precision
|
| 43 |
+
old_precision = self.precision
|
| 44 |
+
try:
|
| 45 |
+
torch.backends.mkldnn.matmul.fp32_precision = "bf16"
|
| 46 |
+
torch.backends.mkldnn.conv.fp32_precision = "bf16"
|
| 47 |
+
self.precision = bf32_precision
|
| 48 |
+
yield
|
| 49 |
+
finally:
|
| 50 |
+
torch.backends.mkldnn.matmul.fp32_precision = old_matmul_precision
|
| 51 |
+
torch.backends.mkldnn.conv.fp32_precision = old_conv_precision
|
| 52 |
+
self.precision = old_precision
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
@contextlib.contextmanager
|
| 56 |
+
def tf32_on(self, tf32_precision=1e-5):
|
| 57 |
+
old_matmul_precision = torch.backends.mkldnn.matmul.fp32_precision
|
| 58 |
+
old_conv_precision = torch.backends.mkldnn.conv.fp32_precision
|
| 59 |
+
old_precision = self.precision
|
| 60 |
+
try:
|
| 61 |
+
torch.backends.mkldnn.matmul.fp32_precision = "tf32"
|
| 62 |
+
torch.backends.mkldnn.conv.fp32_precision = "tf32"
|
| 63 |
+
self.precision = tf32_precision
|
| 64 |
+
yield
|
| 65 |
+
finally:
|
| 66 |
+
torch.backends.mkldnn.matmul.fp32_precision = old_matmul_precision
|
| 67 |
+
torch.backends.mkldnn.conv.fp32_precision = old_conv_precision
|
| 68 |
+
self.precision = old_precision
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
# This is a wrapper that wraps a test to run this test three times, one with
|
| 72 |
+
# reduced_f32 OFF, the others with reduced_f32 ON (including bf32 ON and tf32
|
| 73 |
+
# ON). When running with reduced_f32 ON, it will use reduced precision (bf16/
|
| 74 |
+
# tf32) as specified by the argument.
|
| 75 |
+
def reduced_f32_on_and_off(bf32_precision=1e-2, tf32_precision=1e-5):
|
| 76 |
+
def with_reduced_f32_disabled(self, function_call):
|
| 77 |
+
with reduced_f32_off():
|
| 78 |
+
function_call()
|
| 79 |
+
|
| 80 |
+
def with_bf32_enabled(self, function_call):
|
| 81 |
+
with bf32_on(self, bf32_precision):
|
| 82 |
+
function_call()
|
| 83 |
+
|
| 84 |
+
def with_tf32_enabled(self, function_call):
|
| 85 |
+
with tf32_on(self, tf32_precision):
|
| 86 |
+
function_call()
|
| 87 |
+
|
| 88 |
+
def wrapper(f):
|
| 89 |
+
params = inspect.signature(f).parameters
|
| 90 |
+
arg_names = tuple(params.keys())
|
| 91 |
+
|
| 92 |
+
@functools.wraps(f)
|
| 93 |
+
def wrapped(*args, **kwargs):
|
| 94 |
+
kwargs.update(zip(arg_names, args))
|
| 95 |
+
cond = True
|
| 96 |
+
if "device" in kwargs:
|
| 97 |
+
cond = cond and (torch.device(kwargs["device"]).type == "cpu")
|
| 98 |
+
if "dtype" in kwargs:
|
| 99 |
+
cond = cond and (kwargs["dtype"] == torch.float)
|
| 100 |
+
bf32_cond = cond and bf32_is_not_fp32()
|
| 101 |
+
tf32_cond = cond and tf32_is_not_fp32()
|
| 102 |
+
if bf32_cond or tf32_cond:
|
| 103 |
+
with_reduced_f32_disabled(kwargs["self"], lambda: f(**kwargs))
|
| 104 |
+
if bf32_cond:
|
| 105 |
+
with_bf32_enabled(kwargs["self"], lambda: f(**kwargs))
|
| 106 |
+
if tf32_cond:
|
| 107 |
+
with_tf32_enabled(kwargs["self"], lambda: f(**kwargs))
|
| 108 |
+
else:
|
| 109 |
+
f(**kwargs)
|
| 110 |
+
|
| 111 |
+
return wrapped
|
| 112 |
+
|
| 113 |
+
return wrapper
|
pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/common_modules.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/common_mps.py
ADDED
|
@@ -0,0 +1,850 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
from collections.abc import Sequence
|
| 3 |
+
from typing import Optional
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
|
| 7 |
+
from .common_utils import MACOS_VERSION
|
| 8 |
+
from .opinfo.core import DecorateInfo, OpInfo
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
if torch.backends.mps.is_available():
|
| 12 |
+
|
| 13 |
+
def mps_ops_modifier(
|
| 14 |
+
ops: Sequence[OpInfo],
|
| 15 |
+
device_type: str = "mps",
|
| 16 |
+
xfail_exclusion: Optional[list[str]] = None,
|
| 17 |
+
sparse: bool = False,
|
| 18 |
+
) -> Sequence[OpInfo]:
|
| 19 |
+
if xfail_exclusion is None:
|
| 20 |
+
xfail_exclusion = []
|
| 21 |
+
|
| 22 |
+
# Supported complex OPS
|
| 23 |
+
SUPPORTED_COMPLEX_OPS = {
|
| 24 |
+
"__radd__",
|
| 25 |
+
"__rmul__",
|
| 26 |
+
"__rsub__",
|
| 27 |
+
"__getitem__",
|
| 28 |
+
"_unsafe_masked_index",
|
| 29 |
+
"_unsafe_masked_index_put_accumulate",
|
| 30 |
+
"abs",
|
| 31 |
+
"add",
|
| 32 |
+
"alias_copy",
|
| 33 |
+
"argwhere",
|
| 34 |
+
"atleast_1d",
|
| 35 |
+
"atleast_2d",
|
| 36 |
+
"atleast_3d",
|
| 37 |
+
"as_strided",
|
| 38 |
+
"as_strided_copy",
|
| 39 |
+
"as_strided_scatter",
|
| 40 |
+
"asin",
|
| 41 |
+
"asinh",
|
| 42 |
+
"acos",
|
| 43 |
+
"atan",
|
| 44 |
+
"broadcast_tensors",
|
| 45 |
+
"broadcast_to",
|
| 46 |
+
"chalf",
|
| 47 |
+
"cfloat",
|
| 48 |
+
"chunk",
|
| 49 |
+
"clone",
|
| 50 |
+
"conj",
|
| 51 |
+
"conj_physical",
|
| 52 |
+
"contiguous",
|
| 53 |
+
"cos",
|
| 54 |
+
"cosh",
|
| 55 |
+
"diag",
|
| 56 |
+
"diag_embed",
|
| 57 |
+
"diagflat",
|
| 58 |
+
"diagonal",
|
| 59 |
+
"diagonal_copy",
|
| 60 |
+
"diagonal_scatter",
|
| 61 |
+
"divno_rounding_mode",
|
| 62 |
+
"dsplit",
|
| 63 |
+
"empty",
|
| 64 |
+
"empty_permuted",
|
| 65 |
+
"empty_strided",
|
| 66 |
+
"exp",
|
| 67 |
+
"expm1",
|
| 68 |
+
"exp2",
|
| 69 |
+
"expand",
|
| 70 |
+
"expand_as",
|
| 71 |
+
"expand_copy",
|
| 72 |
+
"flatten",
|
| 73 |
+
"fill",
|
| 74 |
+
"full",
|
| 75 |
+
"full_like",
|
| 76 |
+
"H",
|
| 77 |
+
"hsplit",
|
| 78 |
+
"imag",
|
| 79 |
+
"index_add",
|
| 80 |
+
"index_copy",
|
| 81 |
+
"index_select",
|
| 82 |
+
"index_put",
|
| 83 |
+
"isfinite",
|
| 84 |
+
"isinf",
|
| 85 |
+
"isreal",
|
| 86 |
+
"item",
|
| 87 |
+
"kron",
|
| 88 |
+
"linalg.diagonal",
|
| 89 |
+
"linalg.svd",
|
| 90 |
+
"log10",
|
| 91 |
+
"log1p",
|
| 92 |
+
"log2",
|
| 93 |
+
"log",
|
| 94 |
+
"mH",
|
| 95 |
+
"mT",
|
| 96 |
+
"masked_fill",
|
| 97 |
+
"masked_scatter",
|
| 98 |
+
"masked_select",
|
| 99 |
+
"meshgridlist_of_tensors",
|
| 100 |
+
"meshgridvariadic_tensors",
|
| 101 |
+
"movedim",
|
| 102 |
+
"mul",
|
| 103 |
+
"narrow",
|
| 104 |
+
"narrow_copy",
|
| 105 |
+
"neg",
|
| 106 |
+
"new_full",
|
| 107 |
+
"new_ones",
|
| 108 |
+
"new_zeros",
|
| 109 |
+
"nn.functional.conv1d",
|
| 110 |
+
"nn.functional.conv2d",
|
| 111 |
+
"nn.functional.conv_transpose1d",
|
| 112 |
+
"nn.functional.conv_transpose2d",
|
| 113 |
+
"nn.functional.conv_transpose3d",
|
| 114 |
+
"nn.functional.feature_alpha_dropoutwithout_train",
|
| 115 |
+
"nn.functional.padcircular",
|
| 116 |
+
"nn.functional.softsign",
|
| 117 |
+
"nn.functional.tanhshrink",
|
| 118 |
+
"nn.functional.unfold",
|
| 119 |
+
"nonzero",
|
| 120 |
+
"ones",
|
| 121 |
+
"ones_like",
|
| 122 |
+
"outer",
|
| 123 |
+
"permute",
|
| 124 |
+
"permute_copy",
|
| 125 |
+
"positive",
|
| 126 |
+
"randn",
|
| 127 |
+
"ravel",
|
| 128 |
+
"real",
|
| 129 |
+
"repeat_interleave",
|
| 130 |
+
"reshape_as",
|
| 131 |
+
"reshape",
|
| 132 |
+
"resolve_conj",
|
| 133 |
+
"resolve_neg",
|
| 134 |
+
"rsqrt",
|
| 135 |
+
"rsub",
|
| 136 |
+
"scalar_tensor",
|
| 137 |
+
"select",
|
| 138 |
+
"sgn",
|
| 139 |
+
"sigmoid",
|
| 140 |
+
"sin",
|
| 141 |
+
"sinc",
|
| 142 |
+
"sinh",
|
| 143 |
+
"slice",
|
| 144 |
+
"special.spherical_bessel_j0",
|
| 145 |
+
"special.entr",
|
| 146 |
+
"special.xlog1py",
|
| 147 |
+
"special.zeta",
|
| 148 |
+
"split",
|
| 149 |
+
"split_with_sizes",
|
| 150 |
+
"split_with_sizes_copy",
|
| 151 |
+
"splitlist_args",
|
| 152 |
+
"sqrt",
|
| 153 |
+
"squeeze",
|
| 154 |
+
"squeeze_copy",
|
| 155 |
+
"squeezemultiple",
|
| 156 |
+
"sub",
|
| 157 |
+
"svd",
|
| 158 |
+
"t",
|
| 159 |
+
"t_copy",
|
| 160 |
+
"tanh",
|
| 161 |
+
"tan",
|
| 162 |
+
"tensor_split",
|
| 163 |
+
"transpose",
|
| 164 |
+
"transpose_copy",
|
| 165 |
+
"tril",
|
| 166 |
+
"triu",
|
| 167 |
+
"true_divide",
|
| 168 |
+
"T",
|
| 169 |
+
"unbind",
|
| 170 |
+
"unbind_copy",
|
| 171 |
+
"unflatten",
|
| 172 |
+
"unfold",
|
| 173 |
+
"unfold_copy",
|
| 174 |
+
"unsafe_chunk",
|
| 175 |
+
"unsafe_split",
|
| 176 |
+
"unsqueeze",
|
| 177 |
+
"unsqueeze_copy",
|
| 178 |
+
"view_as",
|
| 179 |
+
"view_as_real",
|
| 180 |
+
"view",
|
| 181 |
+
"view_copy",
|
| 182 |
+
"vsplit",
|
| 183 |
+
"zero_",
|
| 184 |
+
"zeros",
|
| 185 |
+
"zeros_like",
|
| 186 |
+
"__rdiv__",
|
| 187 |
+
"__rmatmul__",
|
| 188 |
+
"_chunk_cat",
|
| 189 |
+
"acosh",
|
| 190 |
+
"all",
|
| 191 |
+
"allclose",
|
| 192 |
+
"angle",
|
| 193 |
+
"any",
|
| 194 |
+
"addcdiv",
|
| 195 |
+
"addcmul",
|
| 196 |
+
"addmmdecomposed",
|
| 197 |
+
"addmv",
|
| 198 |
+
"atanh",
|
| 199 |
+
"bfloat16",
|
| 200 |
+
"bmm",
|
| 201 |
+
"bool",
|
| 202 |
+
"cartesian_prod",
|
| 203 |
+
"cat",
|
| 204 |
+
"char",
|
| 205 |
+
"column_stack",
|
| 206 |
+
"combinations",
|
| 207 |
+
"corrcoef",
|
| 208 |
+
"constant_pad_nd",
|
| 209 |
+
"cov",
|
| 210 |
+
"count_nonzero",
|
| 211 |
+
"diff",
|
| 212 |
+
"div",
|
| 213 |
+
"dot",
|
| 214 |
+
"dstack",
|
| 215 |
+
"einsum",
|
| 216 |
+
"eq",
|
| 217 |
+
"equal",
|
| 218 |
+
"eye",
|
| 219 |
+
"fft.fft",
|
| 220 |
+
"fft.fft2",
|
| 221 |
+
"fft.fftn",
|
| 222 |
+
"fft.fftshift",
|
| 223 |
+
"fft.ifft",
|
| 224 |
+
"fft.ifft2",
|
| 225 |
+
"fft.ifftn",
|
| 226 |
+
"fft.ifftshift",
|
| 227 |
+
"fft.irfftn",
|
| 228 |
+
"fft.irfft2",
|
| 229 |
+
"fft.irfft",
|
| 230 |
+
"fft.hfftn",
|
| 231 |
+
"fft.hfft2",
|
| 232 |
+
"fft.hfft",
|
| 233 |
+
"flip",
|
| 234 |
+
"fliplr",
|
| 235 |
+
"flipud",
|
| 236 |
+
"float",
|
| 237 |
+
"gradient",
|
| 238 |
+
"half",
|
| 239 |
+
"hstack",
|
| 240 |
+
"inner",
|
| 241 |
+
"int",
|
| 242 |
+
"isclose",
|
| 243 |
+
"isnan",
|
| 244 |
+
"ldexp",
|
| 245 |
+
"lerp",
|
| 246 |
+
"linalg.multi_dot",
|
| 247 |
+
"linalg.pinv",
|
| 248 |
+
"linspace",
|
| 249 |
+
"linspacetensor_overload",
|
| 250 |
+
"logical_and",
|
| 251 |
+
"logical_not",
|
| 252 |
+
"logical_or",
|
| 253 |
+
"logical_xor",
|
| 254 |
+
"logsumexp",
|
| 255 |
+
"long",
|
| 256 |
+
"masked.mean",
|
| 257 |
+
"masked.prod",
|
| 258 |
+
"masked.std",
|
| 259 |
+
"masked.sum",
|
| 260 |
+
"masked.var",
|
| 261 |
+
"masked.logsumexp",
|
| 262 |
+
"matmul",
|
| 263 |
+
"mean",
|
| 264 |
+
"mm",
|
| 265 |
+
"mv",
|
| 266 |
+
"ne",
|
| 267 |
+
"nn.functional.padconstant",
|
| 268 |
+
"nn.functional.padreflect",
|
| 269 |
+
"nn.functional.padreplicate",
|
| 270 |
+
"nn.functional.pixel_shuffle",
|
| 271 |
+
"nn.functional.pixel_unshuffle",
|
| 272 |
+
"nn.functional.rms_norm",
|
| 273 |
+
"pinverse",
|
| 274 |
+
"prod",
|
| 275 |
+
"reciprocal",
|
| 276 |
+
"roll",
|
| 277 |
+
"rot90",
|
| 278 |
+
"short",
|
| 279 |
+
"square",
|
| 280 |
+
"stack",
|
| 281 |
+
"stft",
|
| 282 |
+
"sum",
|
| 283 |
+
"sum_to_size",
|
| 284 |
+
"tensordot",
|
| 285 |
+
"trace",
|
| 286 |
+
"trapz",
|
| 287 |
+
"trapezoid",
|
| 288 |
+
"vstack",
|
| 289 |
+
"where",
|
| 290 |
+
"byte",
|
| 291 |
+
}
|
| 292 |
+
|
| 293 |
+
MACOS_BEFORE_14_4_XFAILLIST = {
|
| 294 |
+
# These ops work fine in 14.4 but fail in 14.2 or 13.x
|
| 295 |
+
"fft.hfft2": [torch.complex64],
|
| 296 |
+
}
|
| 297 |
+
|
| 298 |
+
# Those ops are not expected to work
|
| 299 |
+
UNIMPLEMENTED_XFAILLIST: dict[str, Optional[list]] = {
|
| 300 |
+
# Failures due to lack of op implementation on MPS backend
|
| 301 |
+
"logspace": None,
|
| 302 |
+
"logspacetensor_overload": None,
|
| 303 |
+
"linalg.eig": None,
|
| 304 |
+
"linalg.eigvals": None,
|
| 305 |
+
"put": None,
|
| 306 |
+
"cauchy_": None,
|
| 307 |
+
"cauchy": None,
|
| 308 |
+
"cholesky_inverse": None,
|
| 309 |
+
"cholesky_solve": None,
|
| 310 |
+
"frexp": None,
|
| 311 |
+
"gcd": None,
|
| 312 |
+
"geqrf": None,
|
| 313 |
+
"nn.functional.grid_sample": None, # Unsupported Border padding mode
|
| 314 |
+
"hash_tensor": None,
|
| 315 |
+
"heaviside": None,
|
| 316 |
+
"index_reduceprod": None,
|
| 317 |
+
"index_reducemean": None,
|
| 318 |
+
"index_reduceamax": None,
|
| 319 |
+
"index_reduceamin": None,
|
| 320 |
+
# "kthvalue": None,
|
| 321 |
+
"lcm": None,
|
| 322 |
+
"linalg.cond": None,
|
| 323 |
+
"linalg.eigh": None,
|
| 324 |
+
"linalg.eigvalsh": None,
|
| 325 |
+
"linalg.householder_product": None,
|
| 326 |
+
"linalg.ldl_factor": None,
|
| 327 |
+
"linalg.ldl_factor_ex": None,
|
| 328 |
+
"linalg.ldl_solve": None,
|
| 329 |
+
"linalg.lstsq": None,
|
| 330 |
+
"linalg.lstsqgrad_oriented": None,
|
| 331 |
+
"linalg.lu": None,
|
| 332 |
+
"linalg.lu_solve": None,
|
| 333 |
+
"linalg.matrix_norm": [torch.float32],
|
| 334 |
+
"linalg.norm": [torch.float32],
|
| 335 |
+
"linalg.normsubgradients_at_zero": [torch.float32],
|
| 336 |
+
"linalg.qr": None,
|
| 337 |
+
"linalg.svdvals": None,
|
| 338 |
+
"linalg.vecdot": None,
|
| 339 |
+
"lu_solve": None,
|
| 340 |
+
"masked.median": None,
|
| 341 |
+
"matrix_exp": None,
|
| 342 |
+
"mode": None,
|
| 343 |
+
"normnuc": None,
|
| 344 |
+
"nn.functional.fractional_max_pool2d": None,
|
| 345 |
+
"nn.functional.fractional_max_pool3d": None,
|
| 346 |
+
"nn.functional.adaptive_avg_pool3d": None,
|
| 347 |
+
"nn.functional.adaptive_max_pool3d": None,
|
| 348 |
+
"nn.functional.interpolatearea": None,
|
| 349 |
+
"nn.functional.interpolatebicubic": [torch.uint8],
|
| 350 |
+
"nn.functional.ctc_loss": None,
|
| 351 |
+
"nn.functional.embedding_bag": None,
|
| 352 |
+
"nn.functional.multi_margin_loss": None,
|
| 353 |
+
"nn.functional.multilabel_margin_loss": None,
|
| 354 |
+
"nn.functional.pdist": None,
|
| 355 |
+
"nn.functional.rrelu": None,
|
| 356 |
+
"nn.functional.norm": None,
|
| 357 |
+
"ormqr": None,
|
| 358 |
+
"pca_lowrank": None,
|
| 359 |
+
"qr": None,
|
| 360 |
+
"scatter_reduceamax": [torch.int32, torch.int64]
|
| 361 |
+
if MACOS_VERSION < 15.0
|
| 362 |
+
else [torch.int64],
|
| 363 |
+
"scatter_reduceamin": [torch.int32, torch.int64]
|
| 364 |
+
if MACOS_VERSION < 15.0
|
| 365 |
+
else [torch.int64],
|
| 366 |
+
"segment_reduce": None,
|
| 367 |
+
"_segment.reduce": None,
|
| 368 |
+
"segment.reduce": None,
|
| 369 |
+
"segment_reduce_offsets": None,
|
| 370 |
+
"_segment_reduce_offsets": None,
|
| 371 |
+
"_segment_reduce_lengths": None,
|
| 372 |
+
"_segment_reducelengths": None,
|
| 373 |
+
"_segment_reduceoffsets": None,
|
| 374 |
+
"sparse.mm": None,
|
| 375 |
+
"sparse.sampled_addmm": None,
|
| 376 |
+
"sparse.mmreduce": None,
|
| 377 |
+
"special.airy_ai": None,
|
| 378 |
+
"special.erfcx": None,
|
| 379 |
+
"special.laguerre_polynomial_l": None,
|
| 380 |
+
"special.legendre_polynomial_p": None,
|
| 381 |
+
"special.log_ndtr": None,
|
| 382 |
+
"special.ndtri": None,
|
| 383 |
+
"svd_lowrank": None,
|
| 384 |
+
"symeig": None,
|
| 385 |
+
"take": None,
|
| 386 |
+
"to": None,
|
| 387 |
+
"to_sparse": None,
|
| 388 |
+
"unique": None,
|
| 389 |
+
"vdot": None,
|
| 390 |
+
"segment_reduce_": None,
|
| 391 |
+
"_upsample_bilinear2d_aa": [torch.uint8], # uint8 is for CPU only
|
| 392 |
+
"_upsample_bicubic2d_aa": [torch.uint8], # uint8 is for CPU only
|
| 393 |
+
"geometric": None,
|
| 394 |
+
"geometric_": None,
|
| 395 |
+
"log_normal_": None,
|
| 396 |
+
"log_normal": None,
|
| 397 |
+
"cdouble": None,
|
| 398 |
+
"double": None,
|
| 399 |
+
"nn.functional.softminwith_dtype": None,
|
| 400 |
+
"log_softmaxwith_dtype": None,
|
| 401 |
+
"softmaxwith_dtype": None,
|
| 402 |
+
"float_power": None,
|
| 403 |
+
"linalg.matrix_rankhermitian": None,
|
| 404 |
+
"linalg.pinvhermitian": None,
|
| 405 |
+
"nonzero_static": None,
|
| 406 |
+
# MPS: input sizes must be divisible by output sizes
|
| 407 |
+
"nn.functional.adaptive_avg_pool1d": None,
|
| 408 |
+
"nn.functional.adaptive_avg_pool2d": None,
|
| 409 |
+
# Convolution for integral types is not supported on MPS
|
| 410 |
+
"nn.functional.conv1d": [torch.int64],
|
| 411 |
+
"nn.functional.conv2d": [torch.int64],
|
| 412 |
+
"nn.functional.conv3d": [torch.int64],
|
| 413 |
+
"nn.functional.conv_transpose1d": [torch.int64],
|
| 414 |
+
"nn.functional.conv_transpose2d": [torch.int64, torch.bfloat16],
|
| 415 |
+
"nn.functional.conv_transpose3d": [
|
| 416 |
+
torch.int64,
|
| 417 |
+
torch.bfloat16,
|
| 418 |
+
torch.float16,
|
| 419 |
+
],
|
| 420 |
+
# Unsupported dtypes
|
| 421 |
+
"histc": [torch.float16, torch.bfloat16],
|
| 422 |
+
# GEMM on MPS is not supported for integral types
|
| 423 |
+
"nn.functional.linear": [
|
| 424 |
+
torch.int16,
|
| 425 |
+
torch.int32,
|
| 426 |
+
torch.int64,
|
| 427 |
+
torch.uint8,
|
| 428 |
+
torch.int8,
|
| 429 |
+
],
|
| 430 |
+
"addbmm": [torch.int16, torch.int32, torch.int64, torch.uint8, torch.int8],
|
| 431 |
+
"baddbmm": [torch.int16, torch.int32, torch.int64, torch.uint8, torch.int8],
|
| 432 |
+
"mat": [torch.int16, torch.int32, torch.int64, torch.uint8, torch.int8],
|
| 433 |
+
# returned output on CPU is float64
|
| 434 |
+
"bincount": [
|
| 435 |
+
torch.int16,
|
| 436 |
+
torch.int32,
|
| 437 |
+
torch.int64,
|
| 438 |
+
torch.uint8,
|
| 439 |
+
torch.int8,
|
| 440 |
+
],
|
| 441 |
+
}
|
| 442 |
+
UNIMPLEMENTED_XFAILLIST_SPARSE: dict[str, Optional[list]] = {
|
| 443 |
+
"logspace": None,
|
| 444 |
+
"logspacetensor_overload": None,
|
| 445 |
+
"linalg.eig": None,
|
| 446 |
+
"linalg.eigvals": None,
|
| 447 |
+
"put": None,
|
| 448 |
+
}
|
| 449 |
+
|
| 450 |
+
if MACOS_VERSION < 15.0:
|
| 451 |
+
UNIMPLEMENTED_XFAILLIST.update(
|
| 452 |
+
{
|
| 453 |
+
"quantile": None,
|
| 454 |
+
"nanquantile": None,
|
| 455 |
+
}
|
| 456 |
+
)
|
| 457 |
+
if sparse:
|
| 458 |
+
UNIMPLEMENTED_XFAILLIST.update(UNIMPLEMENTED_XFAILLIST_SPARSE)
|
| 459 |
+
|
| 460 |
+
UNDEFINED_XFAILLIST: dict[str, Optional[list]] = {
|
| 461 |
+
# Top 60 operators
|
| 462 |
+
# topk fails with duplicate indices
|
| 463 |
+
"topk": [
|
| 464 |
+
torch.int16,
|
| 465 |
+
torch.int32,
|
| 466 |
+
torch.int64,
|
| 467 |
+
torch.uint8,
|
| 468 |
+
torch.int8,
|
| 469 |
+
],
|
| 470 |
+
# Failures due to random output that they generate using
|
| 471 |
+
# Philox engine causing mismatch with CPU results
|
| 472 |
+
"multinomial": [
|
| 473 |
+
torch.float16,
|
| 474 |
+
torch.float32,
|
| 475 |
+
torch.bfloat16,
|
| 476 |
+
], # random results
|
| 477 |
+
"uniform": [torch.float16, torch.float32, torch.bfloat16],
|
| 478 |
+
"rand_like": [torch.float16, torch.float32, torch.bfloat16],
|
| 479 |
+
"randint": None,
|
| 480 |
+
"randint_like": None,
|
| 481 |
+
"randn": None,
|
| 482 |
+
"randn_like": None,
|
| 483 |
+
"bernoulli": [torch.float16, torch.float32, torch.bfloat16],
|
| 484 |
+
"exponential": [torch.float16, torch.float32, torch.bfloat16],
|
| 485 |
+
"nn.functional.feature_alpha_dropoutwith_train": [
|
| 486 |
+
torch.float16,
|
| 487 |
+
torch.float32,
|
| 488 |
+
torch.bfloat16,
|
| 489 |
+
],
|
| 490 |
+
"normal": [torch.float16, torch.float32, torch.bfloat16],
|
| 491 |
+
"normalin_place": [torch.float16, torch.float32, torch.bfloat16],
|
| 492 |
+
"normalnumber_mean": [torch.float16, torch.float32, torch.bfloat16],
|
| 493 |
+
"nn.functional.alpha_dropout": [
|
| 494 |
+
torch.float16,
|
| 495 |
+
torch.float32,
|
| 496 |
+
torch.bfloat16,
|
| 497 |
+
],
|
| 498 |
+
"nn.functional.dropout": [torch.float16, torch.float32, torch.bfloat16],
|
| 499 |
+
"nn.functional.dropout2d": [torch.float16, torch.float32, torch.bfloat16],
|
| 500 |
+
"nn.functional.dropout3d": [torch.float16, torch.float32, torch.bfloat16],
|
| 501 |
+
# See https://github.com/pytorch/pytorch/issues/111479
|
| 502 |
+
"nn.functional.multi_head_attention_forward": [
|
| 503 |
+
torch.float32,
|
| 504 |
+
torch.float16,
|
| 505 |
+
torch.bfloat16,
|
| 506 |
+
],
|
| 507 |
+
# zero to negative integer powers are undefined
|
| 508 |
+
"__rpow__": [torch.int8, torch.int16, torch.int32, torch.int64],
|
| 509 |
+
"resize_": [torch.float16, torch.float32, torch.bfloat16],
|
| 510 |
+
"resize_as_": [torch.float16, torch.float32, torch.bfloat16],
|
| 511 |
+
# CPU Errors:
|
| 512 |
+
"addr": [
|
| 513 |
+
torch.bool,
|
| 514 |
+
torch.int16,
|
| 515 |
+
torch.int32,
|
| 516 |
+
torch.int64,
|
| 517 |
+
torch.uint8,
|
| 518 |
+
torch.int8,
|
| 519 |
+
], # "addmv_impl_cpu" not implemented for 'Half'
|
| 520 |
+
"as_stridedpartial_views": None, # cpu result off, showing random values
|
| 521 |
+
# random results
|
| 522 |
+
# mps vs cpu:
|
| 523 |
+
# Mismatched elements: 40 / 96 (41.7%)
|
| 524 |
+
# Greatest absolute difference: 17.892311096191406 at index (1, 0, 2) (up to 1e-05 allowed)
|
| 525 |
+
# Greatest relative difference: inf at index (1, 0, 0) (up to 1.3e-06 allowed)
|
| 526 |
+
# cuda(2.0.0.dev20230301+cu117) vs cpu:
|
| 527 |
+
# Mismatched elements: 56 / 96 (58.3%)
|
| 528 |
+
# Greatest absolute difference: 17.892311096191406 at index (1, 0, 2) (up to 1e-05 allowed)
|
| 529 |
+
# Greatest relative difference: inf at index (1, 0, 0) (up to 1.3e-06 allowed)
|
| 530 |
+
"nn.functional.scaled_dot_product_attention": [
|
| 531 |
+
torch.float32,
|
| 532 |
+
torch.float16,
|
| 533 |
+
torch.bfloat16,
|
| 534 |
+
],
|
| 535 |
+
}
|
| 536 |
+
|
| 537 |
+
ON_MPS_XFAILLIST: dict[str, Optional[list]] = {
|
| 538 |
+
# Failures due to lack of implementation of downstream functions on MPS backend
|
| 539 |
+
# TODO: remove these once downstream function 'aten::_linalg_svd.U' have been implemented
|
| 540 |
+
"linalg.matrix_rank": None,
|
| 541 |
+
# Exception: Caused by `torch.arange(-8.001, -4.0, dtype=torch.uint8, device="mps")`
|
| 542 |
+
"arange": [torch.uint8],
|
| 543 |
+
# before macOS 13.2 it falls back to cpu and pass the forward pass
|
| 544 |
+
"grid_sampler_2d": [
|
| 545 |
+
torch.float32,
|
| 546 |
+
torch.float16,
|
| 547 |
+
torch.bfloat16,
|
| 548 |
+
], # Unsupported Border padding mode
|
| 549 |
+
# Failure due to precision issue for fp16
|
| 550 |
+
# on both cpu and mps there are test cases that might produce inf result
|
| 551 |
+
# 'nn.functional.pairwise_distance': [torch.float16],
|
| 552 |
+
# test blow pass on macOS 12 as it falls back to cpu
|
| 553 |
+
# Argsort case using duplicate indices (undefined behaviour):
|
| 554 |
+
# - CPU output: tensor([2546, 6917, 3181, ..., 7128, 5133, 30], device='cpu')
|
| 555 |
+
# - MPS output: tensor([2546, 6917, 3181, ..., 7128, 30, 5133], device='mps:0')
|
| 556 |
+
# Elements from index 30 and 5133 are both equal.
|
| 557 |
+
# Since CPU is not using argsort with stable=True, these cases result in undefined behaviour.
|
| 558 |
+
"argsort": [
|
| 559 |
+
torch.float16,
|
| 560 |
+
torch.int8,
|
| 561 |
+
torch.uint8,
|
| 562 |
+
torch.bool,
|
| 563 |
+
torch.bfloat16,
|
| 564 |
+
],
|
| 565 |
+
# Same issue as `argsort` with duplicate indices. This test checks both the sorted values and the indices.
|
| 566 |
+
# The values of the sorted tensor match the CPU,
|
| 567 |
+
# but in case of the returned indices this results in undefined behaviour.
|
| 568 |
+
"sort": [
|
| 569 |
+
torch.int8,
|
| 570 |
+
torch.uint8,
|
| 571 |
+
torch.bool,
|
| 572 |
+
torch.float16,
|
| 573 |
+
torch.bfloat16,
|
| 574 |
+
],
|
| 575 |
+
}
|
| 576 |
+
|
| 577 |
+
EMPTY_OPS_SKIPLIST = {
|
| 578 |
+
# Fill tensors with uninitialized data, causing mismatch with CPU.
|
| 579 |
+
# They occasionally match, thus skipping them.
|
| 580 |
+
# See https://github.com/pytorch/pytorch/issues/100175
|
| 581 |
+
"new_empty": None,
|
| 582 |
+
"new_empty_strided": None,
|
| 583 |
+
"empty_strided": None,
|
| 584 |
+
# CPU: empty is returning all 0's and there is a mismatch with MPS
|
| 585 |
+
# allocation (MacOS 13). According to
|
| 586 |
+
# https://pytorch.org/docs/2.0/generated/torch.empty.html
|
| 587 |
+
"empty": None,
|
| 588 |
+
"empty_like": None,
|
| 589 |
+
"empty_permuted": None,
|
| 590 |
+
}
|
| 591 |
+
|
| 592 |
+
SKIPLIST = {
|
| 593 |
+
# Unsupported
|
| 594 |
+
# This doesn't work on M1, but is partially working on M2 with the exception of torch.float16
|
| 595 |
+
"nn.functional.conv3d": None,
|
| 596 |
+
# The CPU impl of grid_sampler_3d does not use opmath_t, so it has a
|
| 597 |
+
# large amount of error compared with the MPS impl for half
|
| 598 |
+
# precision types. So we have to skip these for now.
|
| 599 |
+
"grid_sampler_3d": [torch.float16, torch.bfloat16],
|
| 600 |
+
}
|
| 601 |
+
|
| 602 |
+
def addDecorator(op: OpInfo, d: DecorateInfo) -> None:
|
| 603 |
+
if device_type is not None:
|
| 604 |
+
d.device_type = device_type
|
| 605 |
+
|
| 606 |
+
op.decorators = op.decorators + (d,)
|
| 607 |
+
|
| 608 |
+
for op in ops:
|
| 609 |
+
key = op.name + op.variant_test_name
|
| 610 |
+
addDecorator(
|
| 611 |
+
op,
|
| 612 |
+
DecorateInfo(
|
| 613 |
+
unittest.expectedFailure,
|
| 614 |
+
dtypes=[
|
| 615 |
+
torch.double,
|
| 616 |
+
torch.cdouble,
|
| 617 |
+
],
|
| 618 |
+
),
|
| 619 |
+
)
|
| 620 |
+
if sparse:
|
| 621 |
+
# Skipped due to test_sparse_zero_dims test in test_sparse.py which allocates empty tensor
|
| 622 |
+
# which leads to unexpected success with it
|
| 623 |
+
addDecorator(
|
| 624 |
+
op,
|
| 625 |
+
DecorateInfo(
|
| 626 |
+
unittest.skip(
|
| 627 |
+
"Skipped due to MPS not supporting complex128 tensors"
|
| 628 |
+
),
|
| 629 |
+
dtypes=[
|
| 630 |
+
torch.complex128,
|
| 631 |
+
],
|
| 632 |
+
),
|
| 633 |
+
)
|
| 634 |
+
if key in EMPTY_OPS_SKIPLIST:
|
| 635 |
+
addDecorator(
|
| 636 |
+
op,
|
| 637 |
+
DecorateInfo(
|
| 638 |
+
unittest.skip("Skipping empty ops."),
|
| 639 |
+
dtypes=EMPTY_OPS_SKIPLIST[key],
|
| 640 |
+
),
|
| 641 |
+
)
|
| 642 |
+
if key in SKIPLIST:
|
| 643 |
+
addDecorator(
|
| 644 |
+
op, DecorateInfo(unittest.skip("Skipped!"), dtypes=SKIPLIST[key])
|
| 645 |
+
)
|
| 646 |
+
for xfaillist in [
|
| 647 |
+
UNIMPLEMENTED_XFAILLIST,
|
| 648 |
+
UNDEFINED_XFAILLIST,
|
| 649 |
+
ON_MPS_XFAILLIST,
|
| 650 |
+
]:
|
| 651 |
+
if key in xfaillist and key not in xfail_exclusion:
|
| 652 |
+
addDecorator(
|
| 653 |
+
op,
|
| 654 |
+
DecorateInfo(unittest.expectedFailure, dtypes=xfaillist[key]),
|
| 655 |
+
)
|
| 656 |
+
|
| 657 |
+
if (
|
| 658 |
+
key in MACOS_BEFORE_14_4_XFAILLIST
|
| 659 |
+
and key not in xfail_exclusion
|
| 660 |
+
and (MACOS_VERSION < 14.4)
|
| 661 |
+
):
|
| 662 |
+
addDecorator(
|
| 663 |
+
op,
|
| 664 |
+
DecorateInfo(
|
| 665 |
+
unittest.expectedFailure,
|
| 666 |
+
dtypes=MACOS_BEFORE_14_4_XFAILLIST[key],
|
| 667 |
+
),
|
| 668 |
+
)
|
| 669 |
+
|
| 670 |
+
# If ops is not supported for complex types, expect it to fail
|
| 671 |
+
if key not in SUPPORTED_COMPLEX_OPS:
|
| 672 |
+
addDecorator(
|
| 673 |
+
op,
|
| 674 |
+
DecorateInfo(
|
| 675 |
+
unittest.expectedFailure,
|
| 676 |
+
dtypes=[torch.complex32, torch.complex64],
|
| 677 |
+
),
|
| 678 |
+
)
|
| 679 |
+
|
| 680 |
+
return ops
|
| 681 |
+
|
| 682 |
+
def mps_ops_grad_modifier(ops: Sequence[OpInfo]) -> Sequence[OpInfo]:
|
| 683 |
+
XFAILLIST_GRAD = {
|
| 684 |
+
# Unimplemented ops
|
| 685 |
+
"_segment_reduce": [torch.float16, torch.float32],
|
| 686 |
+
"_chunk_cat": [torch.float16, torch.float32],
|
| 687 |
+
"_upsample_bilinear2d_aa": None, # `_upsample_bilinear2d_aa_backward_out` not implemented for MPS
|
| 688 |
+
"_upsample_bicubic2d_aa": None, # `_upsample_bilinear2d_aa_backward_out` not implemented for MPS
|
| 689 |
+
"sparse.mmreduce": [torch.float32], # csr not supported
|
| 690 |
+
"unique_consecutive": [torch.float16, torch.float32],
|
| 691 |
+
"scalar_tensor": [torch.float16, torch.float32],
|
| 692 |
+
"cdist": [torch.float32],
|
| 693 |
+
"masked.scatter": [torch.float16, torch.float32],
|
| 694 |
+
"grid_sampler_3d": None,
|
| 695 |
+
"index_fill": [torch.float16, torch.float32], # missing `aten::_unique`.
|
| 696 |
+
"igamma": None, # currently not supported for any device
|
| 697 |
+
"igammac": None, # currently not supported for any device
|
| 698 |
+
"linalg.solve": [torch.float16, torch.float32], # missing `aten::lu_solve`.
|
| 699 |
+
"linalg.solve_ex": [
|
| 700 |
+
torch.float16,
|
| 701 |
+
torch.float32,
|
| 702 |
+
], # missing `aten::lu_solve`.
|
| 703 |
+
"linalg.tensorsolve": [
|
| 704 |
+
torch.float16,
|
| 705 |
+
torch.float32,
|
| 706 |
+
], # missing `aten::lu_solve`.
|
| 707 |
+
"linalg.det": [torch.float16, torch.float32], # missing aten::lu_solve.out
|
| 708 |
+
"linalg.slogdet": [
|
| 709 |
+
torch.float16,
|
| 710 |
+
torch.float32,
|
| 711 |
+
], # missing aten::lu_solve.out
|
| 712 |
+
"logdet": [torch.float16, torch.float32], # missing aten::lu_solve.out
|
| 713 |
+
"aminmax": [torch.float32, torch.float16],
|
| 714 |
+
"special.i1": [torch.float16], # "i1_backward" not implemented for 'Half'
|
| 715 |
+
"special.i1e": [torch.float16], # "i1e_backward" not implemented for 'Half'
|
| 716 |
+
# Correctness issues
|
| 717 |
+
"atanh": [torch.float32],
|
| 718 |
+
# Same issue as `argsort` and `sort` with duplicate elements (undefined behaviour).
|
| 719 |
+
# Forward pass is passing since `msort` doesn't return the indices, just the values, which match the CPU.
|
| 720 |
+
# On the backward pass for `sort` both are used (values and indices), thus resulting in a issmatch between CPU and MPS.
|
| 721 |
+
# Running `msort` with stable `sort` passes.
|
| 722 |
+
"msort": [torch.float16],
|
| 723 |
+
# Random output
|
| 724 |
+
"exponential": [torch.float16, torch.float32],
|
| 725 |
+
# CPU errors
|
| 726 |
+
# derivative for zeta is not implemented
|
| 727 |
+
"special.zeta": None,
|
| 728 |
+
# derivative for aten::nextafter is not implemented on CPU
|
| 729 |
+
"nextafter": None,
|
| 730 |
+
# derivative for aten::floor_divide is not implemented on CPU
|
| 731 |
+
"floor_divide": [torch.float16, torch.float32],
|
| 732 |
+
# derivative for aten::narrow_copy is not implemented on CPU
|
| 733 |
+
"narrow_copy": [torch.float16, torch.float32],
|
| 734 |
+
# derivative for aten::_histogramdd_from_bin_cts is not implemented on CPU
|
| 735 |
+
"histogramdd": [torch.float16, torch.float32],
|
| 736 |
+
# derivative for aten::histogram is not implemented
|
| 737 |
+
"histogram": [torch.float16, torch.float32],
|
| 738 |
+
# 'bool' object is not iterable
|
| 739 |
+
"allclose": [torch.float16, torch.float32],
|
| 740 |
+
"equal": [torch.float16, torch.float32],
|
| 741 |
+
# 'float' object is not iterable
|
| 742 |
+
"item": [torch.float16, torch.float32],
|
| 743 |
+
# "smooth_l1_backward_cpu_out" not implemented for 'Half'
|
| 744 |
+
"nn.functional.smooth_l1_loss": [torch.float16],
|
| 745 |
+
# cpu error: grad requires non-empty inputs
|
| 746 |
+
"randn": [torch.float16, torch.float32],
|
| 747 |
+
"signal.windows.bartlett": [torch.float32],
|
| 748 |
+
"signal.windows.blackman": [torch.float32],
|
| 749 |
+
"signal.windows.cosine": [torch.float32],
|
| 750 |
+
"signal.windows.exponential": [torch.float32],
|
| 751 |
+
"signal.windows.gaussian": [torch.float32],
|
| 752 |
+
"signal.windows.general_cosine": [torch.float32],
|
| 753 |
+
"signal.windows.general_hamming": [torch.float32],
|
| 754 |
+
"signal.windows.hamming": [torch.float32],
|
| 755 |
+
"signal.windows.hann": [torch.float32],
|
| 756 |
+
"signal.windows.kaiser": [torch.float32],
|
| 757 |
+
"signal.windows.nuttall": [torch.float32],
|
| 758 |
+
"eye": [torch.float16, torch.float32],
|
| 759 |
+
# topk fails with duplicate indices
|
| 760 |
+
"topk": [torch.float16],
|
| 761 |
+
}
|
| 762 |
+
|
| 763 |
+
SKIPLIST_GRAD = {
|
| 764 |
+
"nn.functional.pairwise_distance": [torch.float16],
|
| 765 |
+
# failed assertion `destination datatype must be fp32'
|
| 766 |
+
"nn.functional.conv1d": [torch.float16],
|
| 767 |
+
"nn.functional.conv2d": [torch.float16],
|
| 768 |
+
"nn.functional.conv3d": [torch.float16],
|
| 769 |
+
"nn.functional.conv_transpose1d": [torch.float16],
|
| 770 |
+
"nn.functional.conv_transpose2d": [torch.float16],
|
| 771 |
+
"nn.functional.conv_transpose3d": [torch.float16],
|
| 772 |
+
}
|
| 773 |
+
|
| 774 |
+
ON_MPS_XFAILLIST = {
|
| 775 |
+
# Failures due to lack of implementation of downstream functions on MPS backend
|
| 776 |
+
# TODO: remove these once downstream function 'aten::_linalg_svd.U' have been implemented
|
| 777 |
+
"linalg.matrix_rank": None,
|
| 778 |
+
# Exception: Caused by sample input at index 3 on MPS
|
| 779 |
+
"nn.functional.conv3d": [torch.float32],
|
| 780 |
+
}
|
| 781 |
+
|
| 782 |
+
def addDecorator(op: OpInfo, d: DecorateInfo) -> None:
|
| 783 |
+
op.decorators = op.decorators + (d,)
|
| 784 |
+
|
| 785 |
+
for op in ops:
|
| 786 |
+
key = op.name + op.variant_test_name
|
| 787 |
+
if key in XFAILLIST_GRAD:
|
| 788 |
+
addDecorator(
|
| 789 |
+
op,
|
| 790 |
+
DecorateInfo(unittest.expectedFailure, dtypes=XFAILLIST_GRAD[key]),
|
| 791 |
+
)
|
| 792 |
+
|
| 793 |
+
if key in SKIPLIST_GRAD:
|
| 794 |
+
addDecorator(op, DecorateInfo(unittest.skip, dtypes=SKIPLIST_GRAD[key]))
|
| 795 |
+
|
| 796 |
+
if key in ON_MPS_XFAILLIST:
|
| 797 |
+
addDecorator(
|
| 798 |
+
op,
|
| 799 |
+
DecorateInfo(
|
| 800 |
+
unittest.expectedFailure, dtypes=ON_MPS_XFAILLIST[key]
|
| 801 |
+
),
|
| 802 |
+
)
|
| 803 |
+
|
| 804 |
+
return ops
|
| 805 |
+
|
| 806 |
+
def mps_ops_error_inputs_modifier(ops: Sequence[OpInfo]) -> Sequence[OpInfo]:
|
| 807 |
+
# Error input samples do not take a dtype argument.
|
| 808 |
+
XFAILLIST = {
|
| 809 |
+
# Exceptions are not raised
|
| 810 |
+
"__rmod__",
|
| 811 |
+
"__rsub__",
|
| 812 |
+
"__rpow__",
|
| 813 |
+
"bernoulli",
|
| 814 |
+
"clamp_max",
|
| 815 |
+
"clamp_min",
|
| 816 |
+
"masked_scatter",
|
| 817 |
+
# unsupported float64 dtype
|
| 818 |
+
"multinomial",
|
| 819 |
+
"nn.functional.conv1d",
|
| 820 |
+
"nn.functional.conv2d",
|
| 821 |
+
"nn.functional.conv3d",
|
| 822 |
+
"gather",
|
| 823 |
+
"scatter",
|
| 824 |
+
"scatter_add",
|
| 825 |
+
# MPS does not support tensor dimensions > 16
|
| 826 |
+
"amax",
|
| 827 |
+
"amin",
|
| 828 |
+
"aminmax",
|
| 829 |
+
# memory overlapping checks
|
| 830 |
+
"index_select",
|
| 831 |
+
}
|
| 832 |
+
|
| 833 |
+
def addDecorator(op: OpInfo, d: DecorateInfo) -> None:
|
| 834 |
+
op.decorators = op.decorators + (d,)
|
| 835 |
+
|
| 836 |
+
for op in ops:
|
| 837 |
+
key = op.name + op.variant_test_name
|
| 838 |
+
if key in XFAILLIST:
|
| 839 |
+
addDecorator(op, DecorateInfo(unittest.expectedFailure))
|
| 840 |
+
|
| 841 |
+
return ops
|
| 842 |
+
else:
|
| 843 |
+
|
| 844 |
+
def mps_ops_modifier(
|
| 845 |
+
ops: Sequence[OpInfo],
|
| 846 |
+
device_type: str = "mps",
|
| 847 |
+
xfail_exclusion: Optional[list[str]] = None,
|
| 848 |
+
sparse: bool = False,
|
| 849 |
+
) -> Sequence[OpInfo]:
|
| 850 |
+
return ops
|
pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/common_nn.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/common_optimizers.py
ADDED
|
@@ -0,0 +1,2309 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: ignore-errors
|
| 2 |
+
|
| 3 |
+
import functools
|
| 4 |
+
import itertools
|
| 5 |
+
import sys
|
| 6 |
+
import unittest
|
| 7 |
+
from copy import deepcopy
|
| 8 |
+
from enum import Enum
|
| 9 |
+
from typing import Any, Union
|
| 10 |
+
|
| 11 |
+
import torch
|
| 12 |
+
from torch import Tensor
|
| 13 |
+
from torch.nn import Parameter
|
| 14 |
+
from torch.optim import (
|
| 15 |
+
Adadelta,
|
| 16 |
+
Adafactor,
|
| 17 |
+
Adagrad,
|
| 18 |
+
Adam,
|
| 19 |
+
Adamax,
|
| 20 |
+
AdamW,
|
| 21 |
+
ASGD,
|
| 22 |
+
LBFGS,
|
| 23 |
+
Muon,
|
| 24 |
+
NAdam,
|
| 25 |
+
Optimizer,
|
| 26 |
+
RAdam,
|
| 27 |
+
RMSprop,
|
| 28 |
+
Rprop,
|
| 29 |
+
SGD,
|
| 30 |
+
SparseAdam,
|
| 31 |
+
)
|
| 32 |
+
from torch.optim.lr_scheduler import (
|
| 33 |
+
ConstantLR,
|
| 34 |
+
ExponentialLR,
|
| 35 |
+
LinearLR,
|
| 36 |
+
PolynomialLR,
|
| 37 |
+
ReduceLROnPlateau,
|
| 38 |
+
StepLR,
|
| 39 |
+
)
|
| 40 |
+
from torch.testing._internal.common_device_type import tol, toleranceOverride
|
| 41 |
+
from torch.testing._internal.common_methods_invocations import DecorateInfo
|
| 42 |
+
from torch.testing._internal.common_utils import (
|
| 43 |
+
_TestParametrizer,
|
| 44 |
+
skipIfMPS,
|
| 45 |
+
skipIfTorchDynamo,
|
| 46 |
+
skipIfXpu,
|
| 47 |
+
TEST_WITH_TORCHDYNAMO,
|
| 48 |
+
)
|
| 49 |
+
from torch.utils._foreach_utils import _get_foreach_kernels_supported_devices
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
class OptimizerInput:
|
| 53 |
+
"""Contains args / kwargs to be passed to an optimizer constructor."""
|
| 54 |
+
|
| 55 |
+
__slots__ = ["params", "kwargs", "desc"]
|
| 56 |
+
|
| 57 |
+
def __init__(
|
| 58 |
+
self,
|
| 59 |
+
params: Union[
|
| 60 |
+
list[Parameter], list[Tensor], dict[Any, Any], list[dict[str, Any]]
|
| 61 |
+
],
|
| 62 |
+
kwargs: dict[str, Any],
|
| 63 |
+
desc: str = "",
|
| 64 |
+
):
|
| 65 |
+
# params can be a list of Tensors OR param_groups OR None
|
| 66 |
+
self.params = params
|
| 67 |
+
self.kwargs = kwargs
|
| 68 |
+
self.desc = desc
|
| 69 |
+
|
| 70 |
+
def __repr__(self):
|
| 71 |
+
return f"params={self.params}, kwargs={self.kwargs}, desc={self.desc}"
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
class OptimizerErrorEnum(Enum):
|
| 75 |
+
"""Enumerates when an error is raised when testing optimizers."""
|
| 76 |
+
|
| 77 |
+
CONSTRUCTION_ERROR = 0
|
| 78 |
+
STEP_ERROR = 1
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
class ErrorOptimizerInput:
|
| 82 |
+
"""
|
| 83 |
+
An OptimizerInput that will cause the optimizer to throw an error when constructed.
|
| 84 |
+
Includes the type and string of the resulting error.
|
| 85 |
+
"""
|
| 86 |
+
|
| 87 |
+
__slots__ = ["optimizer_error_input", "error_on", "error_type", "error_regex"]
|
| 88 |
+
|
| 89 |
+
def __init__(
|
| 90 |
+
self,
|
| 91 |
+
optimizer_error_input,
|
| 92 |
+
*,
|
| 93 |
+
error_on=OptimizerErrorEnum.CONSTRUCTION_ERROR,
|
| 94 |
+
error_type=RuntimeError,
|
| 95 |
+
error_regex="",
|
| 96 |
+
):
|
| 97 |
+
self.optimizer_error_input = optimizer_error_input
|
| 98 |
+
self.error_on = error_on
|
| 99 |
+
self.error_type = error_type
|
| 100 |
+
self.error_regex = error_regex
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
class OptimizerInfo:
|
| 104 |
+
"""Optimizer information to be used in testing."""
|
| 105 |
+
|
| 106 |
+
def __init__(
|
| 107 |
+
self,
|
| 108 |
+
optim_cls: Optimizer, # Class object for the Optimizer under test
|
| 109 |
+
*,
|
| 110 |
+
# Function to generate optimizer inputs EXCLUDING params. We delegate params responsibility
|
| 111 |
+
# to the test using the OptimizerInfo. OptimizerInput.params is likely None.
|
| 112 |
+
# Can optionally take in device to filter out certain unsupported configs
|
| 113 |
+
optim_inputs_func,
|
| 114 |
+
# Tuple of lambdas to generate LRScheduler instances to run with the optimizer for the
|
| 115 |
+
# LRScheduler tests like test_forloop_goes_right_direction with_lrsched.
|
| 116 |
+
# We DO NOT expect to thoroughly test LRSchedulers through the optimizers, so not every
|
| 117 |
+
# LRScheduler configuration will be included. See test_lrscheduler.py for that instead.
|
| 118 |
+
# A few optimizers like SGD and Adam will test more LRSchedulers.
|
| 119 |
+
scheduler_inputs=(
|
| 120 |
+
[
|
| 121 |
+
lambda opt: StepLR(opt, gamma=0.9, step_size=10),
|
| 122 |
+
lambda opt: ReduceLROnPlateau(opt),
|
| 123 |
+
],
|
| 124 |
+
),
|
| 125 |
+
# A subset of the global-cliquey flags (fused, foreach, differentiable) the optimizer
|
| 126 |
+
# supports. See NOTE: [optimizer kwarg categories] for what global-cliquey means.
|
| 127 |
+
supported_impls: tuple[str, ...] = ("foreach", "differentiable"),
|
| 128 |
+
# A subset of all flags, signifying which ones were only supported after the
|
| 129 |
+
# original optimizer had already been released. aka impls where we need to check BC.
|
| 130 |
+
not_og_supported_flags: tuple[str, ...] = (
|
| 131 |
+
"foreach",
|
| 132 |
+
"differentiable",
|
| 133 |
+
"maximize",
|
| 134 |
+
"capturable",
|
| 135 |
+
),
|
| 136 |
+
# the optim supports passing in sparse gradients as well as dense grads
|
| 137 |
+
supports_sparse: bool = False,
|
| 138 |
+
# the optimizer constructor supports passing in capturable as a kwarg
|
| 139 |
+
has_capturable_arg: bool = False,
|
| 140 |
+
# the optim only supports one config: sparse grads w/ dense params, see SparseAdam
|
| 141 |
+
only_supports_sparse_grads: bool = False,
|
| 142 |
+
# Tuple of (optimizer kwargs, schedulers_constructors) specifically for sparse tests,
|
| 143 |
+
# with especially tuned hyperparameters. These only apply if the optimizer supports
|
| 144 |
+
# sparse parameters or grads.
|
| 145 |
+
metadata_for_sparse=({}, []),
|
| 146 |
+
# the optim supports complex parameters
|
| 147 |
+
supports_complex: bool = True,
|
| 148 |
+
# whether the optimizer.step() function requires a closure to be passed
|
| 149 |
+
step_requires_closure: bool = False,
|
| 150 |
+
# whether the optimizer supports per-param options with parameter groups
|
| 151 |
+
supports_param_groups: bool = True,
|
| 152 |
+
# whether the optimizer supports parameters on multiple devices
|
| 153 |
+
supports_multiple_devices: bool = True,
|
| 154 |
+
skips=(), # Indicates which tests to skip
|
| 155 |
+
decorators=None, # Additional decorators to apply to generated tests
|
| 156 |
+
optim_error_inputs_func=None, # Function to generate optim inputs that error
|
| 157 |
+
supports_fused_on: tuple[str, ...] = (),
|
| 158 |
+
):
|
| 159 |
+
self.optim_cls = optim_cls
|
| 160 |
+
self.optim_inputs_func = optim_inputs_func
|
| 161 |
+
self.scheduler_inputs = scheduler_inputs
|
| 162 |
+
self.supported_impls = supported_impls
|
| 163 |
+
self.not_og_supported_flags = not_og_supported_flags
|
| 164 |
+
self.supports_sparse = supports_sparse
|
| 165 |
+
self.has_capturable_arg = has_capturable_arg
|
| 166 |
+
self.metadata_for_sparse = metadata_for_sparse
|
| 167 |
+
self.only_supports_sparse_grads = only_supports_sparse_grads
|
| 168 |
+
self.supports_complex = supports_complex
|
| 169 |
+
self.step_requires_closure = step_requires_closure
|
| 170 |
+
self.supports_param_groups = supports_param_groups
|
| 171 |
+
self.supports_multiple_devices = supports_multiple_devices
|
| 172 |
+
self.decorators = (
|
| 173 |
+
*(decorators if decorators else []),
|
| 174 |
+
*(skips if skips else []),
|
| 175 |
+
)
|
| 176 |
+
self.optim_error_inputs_func = optim_error_inputs_func
|
| 177 |
+
self.supports_fused_on = supports_fused_on
|
| 178 |
+
|
| 179 |
+
def get_decorators(self, test_class, test_name, device, dtype, param_kwargs):
|
| 180 |
+
result = []
|
| 181 |
+
for decorator in self.decorators:
|
| 182 |
+
if isinstance(decorator, DecorateInfo):
|
| 183 |
+
if decorator.is_active(
|
| 184 |
+
test_class, test_name, device, dtype, param_kwargs
|
| 185 |
+
):
|
| 186 |
+
result.extend(decorator.decorators)
|
| 187 |
+
else:
|
| 188 |
+
result.append(decorator)
|
| 189 |
+
return result
|
| 190 |
+
|
| 191 |
+
@property
|
| 192 |
+
def name(self):
|
| 193 |
+
return self.optim_cls.__name__
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
class optims(_TestParametrizer):
|
| 197 |
+
"""Decorator for specifying a list of optimizers over which to run a test."""
|
| 198 |
+
|
| 199 |
+
def __init__(self, optim_info_iterable, dtypes=None):
|
| 200 |
+
self.optim_info_list = list(optim_info_iterable)
|
| 201 |
+
|
| 202 |
+
# optimizers aren't limited to be one dtype as parameters can have different dtypes
|
| 203 |
+
# We default to torch.float32, but dtypes should be specified through passed in
|
| 204 |
+
# parameters.
|
| 205 |
+
self.dtypes = dtypes if dtypes is not None else [torch.float32]
|
| 206 |
+
|
| 207 |
+
def _parametrize_test(self, test, generic_cls, device_cls):
|
| 208 |
+
if device_cls is None:
|
| 209 |
+
raise RuntimeError(
|
| 210 |
+
"The @optims decorator is only intended to be used in a device-specific "
|
| 211 |
+
"context; use it with instantiate_device_type_tests() instead of "
|
| 212 |
+
"instantiate_parametrized_tests()"
|
| 213 |
+
)
|
| 214 |
+
|
| 215 |
+
for optim_info, dtype in itertools.product(self.optim_info_list, self.dtypes):
|
| 216 |
+
# Construct the test name; device / dtype parts are handled outside.
|
| 217 |
+
# See [Note: device and dtype suffix placement]
|
| 218 |
+
test_name = optim_info.name
|
| 219 |
+
|
| 220 |
+
# Construct parameter kwargs to pass to the test.
|
| 221 |
+
param_kwargs = {"optim_info": optim_info, "dtype": dtype}
|
| 222 |
+
|
| 223 |
+
try:
|
| 224 |
+
|
| 225 |
+
@functools.wraps(test)
|
| 226 |
+
def test_wrapper(*args, **kwargs):
|
| 227 |
+
return test(*args, **kwargs)
|
| 228 |
+
|
| 229 |
+
decorator_fn = functools.partial(
|
| 230 |
+
optim_info.get_decorators,
|
| 231 |
+
generic_cls.__name__,
|
| 232 |
+
test.__name__,
|
| 233 |
+
device_cls.device_type,
|
| 234 |
+
dtype,
|
| 235 |
+
)
|
| 236 |
+
|
| 237 |
+
yield (test_wrapper, test_name, param_kwargs, decorator_fn)
|
| 238 |
+
except Exception as ex:
|
| 239 |
+
# Provides an error message for debugging before rethrowing the exception
|
| 240 |
+
print(
|
| 241 |
+
f"Failed to instantiate {test_name} for module {optim_info.name}!"
|
| 242 |
+
)
|
| 243 |
+
raise ex
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
# Helper function for generating error inputs for all optimizers, used below.
|
| 247 |
+
def get_error_inputs_for_all_optims(device, dtype):
|
| 248 |
+
if _get_device_type(device) == "cpu":
|
| 249 |
+
# Creating 2D parameters for compatibility with Muon.
|
| 250 |
+
sample_param = Parameter(torch.randn(1, 1, device=device, dtype=dtype))
|
| 251 |
+
sample_param2 = Parameter(torch.randn(1, 1, device=device, dtype=dtype))
|
| 252 |
+
return [
|
| 253 |
+
ErrorOptimizerInput(
|
| 254 |
+
OptimizerInput(
|
| 255 |
+
params=sample_param,
|
| 256 |
+
kwargs={},
|
| 257 |
+
desc="invalid param type",
|
| 258 |
+
),
|
| 259 |
+
error_type=TypeError,
|
| 260 |
+
error_regex="params argument given to the optimizer should be an iterable of Tensors or dicts",
|
| 261 |
+
),
|
| 262 |
+
ErrorOptimizerInput(
|
| 263 |
+
OptimizerInput(
|
| 264 |
+
params=[sample_param, sample_param],
|
| 265 |
+
kwargs={},
|
| 266 |
+
desc="a param group cannot have duplicate parameters",
|
| 267 |
+
),
|
| 268 |
+
error_type=UserWarning,
|
| 269 |
+
error_regex=".*a parameter group with duplicate parameters.*",
|
| 270 |
+
),
|
| 271 |
+
ErrorOptimizerInput(
|
| 272 |
+
OptimizerInput(
|
| 273 |
+
params=[{"params": sample_param}, {"params": sample_param}],
|
| 274 |
+
kwargs={},
|
| 275 |
+
desc="duplicate parameters should not occur across param groups either",
|
| 276 |
+
),
|
| 277 |
+
error_type=ValueError,
|
| 278 |
+
error_regex="some parameters appear in more than one parameter group",
|
| 279 |
+
),
|
| 280 |
+
ErrorOptimizerInput(
|
| 281 |
+
OptimizerInput(
|
| 282 |
+
params=None,
|
| 283 |
+
kwargs=dict(lr=torch.tensor([0.001, 0.001])),
|
| 284 |
+
desc="Tensor lr must be 1-element",
|
| 285 |
+
),
|
| 286 |
+
error_type=ValueError,
|
| 287 |
+
error_regex="Tensor lr must be 1-element",
|
| 288 |
+
),
|
| 289 |
+
ErrorOptimizerInput(
|
| 290 |
+
OptimizerInput(
|
| 291 |
+
params=[("weight", sample_param), sample_param2],
|
| 292 |
+
kwargs={},
|
| 293 |
+
desc="all optimizer params should be with/without names",
|
| 294 |
+
),
|
| 295 |
+
error_type=ValueError,
|
| 296 |
+
error_regex="all optimizer params should be with/without names. Some param names are missing",
|
| 297 |
+
),
|
| 298 |
+
ErrorOptimizerInput(
|
| 299 |
+
OptimizerInput(
|
| 300 |
+
params=[
|
| 301 |
+
{"params": [sample_param], "lr": 1e-2},
|
| 302 |
+
{"params": [("weight", sample_param2)]},
|
| 303 |
+
],
|
| 304 |
+
kwargs={},
|
| 305 |
+
desc="all optimizer param groups should be with/without names.",
|
| 306 |
+
),
|
| 307 |
+
error_type=ValueError,
|
| 308 |
+
error_regex="all optimizer param groups should be with/without names. "
|
| 309 |
+
"cannot add param group with names to the optimizer",
|
| 310 |
+
),
|
| 311 |
+
]
|
| 312 |
+
else:
|
| 313 |
+
return []
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
# ------------------------------------------------------------------------------------------
|
| 317 |
+
# NOTE: [optimizer kwarg categories]
|
| 318 |
+
# We categorize optimizer kwargs as 3 types:
|
| 319 |
+
# 1. optimizer-specific flags are like amsgrad or rho or beta, flags that are specific to
|
| 320 |
+
# algorithms and thus only show up for certain optimizers. There are many of these, so I
|
| 321 |
+
# do not bother gathering them all and listing them here. The converse to these would be
|
| 322 |
+
# global flags that every optimizer ideally _should_ support. We break global flags into
|
| 323 |
+
# 2 further categories and list them all below.
|
| 324 |
+
# 2. global-friendly = ["lr", "weight_decay", "maximize", "capturable"]
|
| 325 |
+
# global-friendly flags are global flags who play nicely with all other global flags,
|
| 326 |
+
# i.e., are mutually exclusive in function. This means that any pair of the following
|
| 327 |
+
# flags can be toggled at once (e.g., maximize and weight_decay). Furthermore, any of the
|
| 328 |
+
# following flags theoretically can be enabled with ANY other global flag, including the
|
| 329 |
+
# cliquey ones (e.g, capturable and foreach).
|
| 330 |
+
# 3. global-cliquey = ["foreach", "fused", "differentiable"]
|
| 331 |
+
# global-cliquey flags are global flags that do NOT coexist with other cliquey flags,
|
| 332 |
+
# usually because they contradict each other in function. For example, one should not flip
|
| 333 |
+
# both foreach AND fused to True, because they are two differing performance optimizations
|
| 334 |
+
# in which you can only opt into one.
|
| 335 |
+
#
|
| 336 |
+
# The following optim_inputs_func_* sampling functions only return constructor combinations of
|
| 337 |
+
# optimizer-specific and global-friendly flags. This is because we are confident they would mesh
|
| 338 |
+
# well with additional kwargs. On the flip side of the same coin, we reserve setting the
|
| 339 |
+
# global-cliquey flags to individual tests and fully expect tests to edit OptimizerInput.kwargs.
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
def optim_inputs_func_adadelta(device, dtype=None):
|
| 343 |
+
cuda_supported_configs = [
|
| 344 |
+
OptimizerInput(params=None, kwargs={"capturable": True}, desc="capturable"),
|
| 345 |
+
OptimizerInput(
|
| 346 |
+
params=None,
|
| 347 |
+
kwargs={"weight_decay": 0.1, "capturable": True},
|
| 348 |
+
desc="capturable with weight decay",
|
| 349 |
+
),
|
| 350 |
+
OptimizerInput(
|
| 351 |
+
params=None,
|
| 352 |
+
kwargs={"lr": torch.tensor(0.001), "capturable": True},
|
| 353 |
+
desc="Tensor lr with capturable",
|
| 354 |
+
),
|
| 355 |
+
]
|
| 356 |
+
|
| 357 |
+
return [
|
| 358 |
+
OptimizerInput(params=None, kwargs={}, desc="default"),
|
| 359 |
+
OptimizerInput(params=None, kwargs={"lr": 0.01}, desc="non-default lr"),
|
| 360 |
+
OptimizerInput(
|
| 361 |
+
params=None, kwargs={"weight_decay": 0.1}, desc="nonzero weight_decay"
|
| 362 |
+
),
|
| 363 |
+
OptimizerInput(params=None, kwargs={"maximize": True}, desc="maximize"),
|
| 364 |
+
OptimizerInput(
|
| 365 |
+
params=None,
|
| 366 |
+
kwargs={"weight_decay": 0.1, "maximize": True},
|
| 367 |
+
desc="maximize, weight_decay",
|
| 368 |
+
),
|
| 369 |
+
OptimizerInput(
|
| 370 |
+
params=None, kwargs={"rho": 0.95, "weight_decay": 0.9}, desc="rho"
|
| 371 |
+
),
|
| 372 |
+
] + (cuda_supported_configs if _get_device_type(device) == "cuda" else [])
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
def optim_error_inputs_func_adadelta(device, dtype):
|
| 376 |
+
error_inputs = get_error_inputs_for_all_optims(device, dtype)
|
| 377 |
+
if _get_device_type(device) == "cpu":
|
| 378 |
+
error_inputs += [
|
| 379 |
+
ErrorOptimizerInput(
|
| 380 |
+
OptimizerInput(
|
| 381 |
+
params=None,
|
| 382 |
+
kwargs=dict(lr=1e-2, rho=1.1),
|
| 383 |
+
desc="rho should be between 0 and 1",
|
| 384 |
+
),
|
| 385 |
+
error_type=ValueError,
|
| 386 |
+
error_regex="Invalid rho value: 1.1",
|
| 387 |
+
),
|
| 388 |
+
]
|
| 389 |
+
return error_inputs
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
def optim_inputs_func_adafactor(device, dtype=None):
|
| 393 |
+
return [
|
| 394 |
+
OptimizerInput(params=None, kwargs={}, desc="default"),
|
| 395 |
+
OptimizerInput(
|
| 396 |
+
params=None,
|
| 397 |
+
kwargs={"weight_decay": 0.1, "lr": 0.01},
|
| 398 |
+
desc="nonzero weight_decay",
|
| 399 |
+
),
|
| 400 |
+
OptimizerInput(
|
| 401 |
+
params=None,
|
| 402 |
+
kwargs={"weight_decay": 0.1, "maximize": True},
|
| 403 |
+
desc="maximize",
|
| 404 |
+
),
|
| 405 |
+
OptimizerInput(
|
| 406 |
+
params=None,
|
| 407 |
+
kwargs={"beta2_decay": -1.0},
|
| 408 |
+
desc="non-default beta2_decay",
|
| 409 |
+
),
|
| 410 |
+
OptimizerInput(
|
| 411 |
+
params=None,
|
| 412 |
+
kwargs={"d": 1.5},
|
| 413 |
+
desc="non-default clipping threshold d",
|
| 414 |
+
),
|
| 415 |
+
]
|
| 416 |
+
|
| 417 |
+
|
| 418 |
+
def optim_error_inputs_func_adafactor(device, dtype):
|
| 419 |
+
error_inputs = get_error_inputs_for_all_optims(device, dtype)
|
| 420 |
+
if _get_device_type(device) == "cpu":
|
| 421 |
+
complex_param = torch.rand(2, 3, device=device, dtype=torch.complex64)
|
| 422 |
+
complex_param.grad = torch.rand_like(complex_param)
|
| 423 |
+
error_inputs += [
|
| 424 |
+
ErrorOptimizerInput(
|
| 425 |
+
OptimizerInput(
|
| 426 |
+
params=None,
|
| 427 |
+
kwargs=dict(eps=(-1e-30, 1e-3)),
|
| 428 |
+
desc="epsilon1 should be >= 0",
|
| 429 |
+
),
|
| 430 |
+
error_type=ValueError,
|
| 431 |
+
error_regex="epsilon1 should be >= 0",
|
| 432 |
+
),
|
| 433 |
+
ErrorOptimizerInput(
|
| 434 |
+
OptimizerInput(
|
| 435 |
+
params=None,
|
| 436 |
+
kwargs=dict(d=0.0),
|
| 437 |
+
desc="invalid d",
|
| 438 |
+
),
|
| 439 |
+
error_type=ValueError,
|
| 440 |
+
error_regex="Clipping threshold d should be >= 1",
|
| 441 |
+
),
|
| 442 |
+
ErrorOptimizerInput(
|
| 443 |
+
OptimizerInput(
|
| 444 |
+
params=None,
|
| 445 |
+
kwargs=dict(beta2_decay=0.8),
|
| 446 |
+
desc="invalid beta2_decay",
|
| 447 |
+
),
|
| 448 |
+
error_type=ValueError,
|
| 449 |
+
error_regex="beta2_decay should be <= 0",
|
| 450 |
+
),
|
| 451 |
+
ErrorOptimizerInput(
|
| 452 |
+
OptimizerInput(
|
| 453 |
+
params=[complex_param],
|
| 454 |
+
kwargs=dict(),
|
| 455 |
+
desc="does not support complex parameters",
|
| 456 |
+
),
|
| 457 |
+
error_type=RuntimeError,
|
| 458 |
+
error_regex="Adafactor does not support complex parameters",
|
| 459 |
+
error_on=OptimizerErrorEnum.STEP_ERROR,
|
| 460 |
+
),
|
| 461 |
+
]
|
| 462 |
+
return error_inputs
|
| 463 |
+
|
| 464 |
+
|
| 465 |
+
def optim_inputs_func_adagrad(device, dtype=None):
|
| 466 |
+
return [
|
| 467 |
+
OptimizerInput(params=None, kwargs={}, desc="default"),
|
| 468 |
+
OptimizerInput(
|
| 469 |
+
params=None, kwargs={"weight_decay": 0.1}, desc="nonzero weight_decay"
|
| 470 |
+
),
|
| 471 |
+
OptimizerInput(
|
| 472 |
+
params=None,
|
| 473 |
+
kwargs={"weight_decay": 0.1, "maximize": True},
|
| 474 |
+
desc="maximize",
|
| 475 |
+
),
|
| 476 |
+
OptimizerInput(params=None, kwargs={"lr": 0.1}, desc="non-default lr"),
|
| 477 |
+
OptimizerInput(
|
| 478 |
+
params=None,
|
| 479 |
+
kwargs={"initial_accumulator_value": 0.1, "weight_decay": 0.1},
|
| 480 |
+
desc="initial_accumulator_value",
|
| 481 |
+
),
|
| 482 |
+
OptimizerInput(
|
| 483 |
+
params=None,
|
| 484 |
+
kwargs={"lr": 0.1, "lr_decay": 0.5, "weight_decay": 0.1},
|
| 485 |
+
desc="lr_decay",
|
| 486 |
+
), # TODO: Move out to testing in param_group?
|
| 487 |
+
OptimizerInput(
|
| 488 |
+
params=None,
|
| 489 |
+
kwargs={"lr": torch.tensor(0.001)},
|
| 490 |
+
desc="Tensor lr",
|
| 491 |
+
),
|
| 492 |
+
]
|
| 493 |
+
|
| 494 |
+
|
| 495 |
+
def optim_error_inputs_func_adagrad(device, dtype):
|
| 496 |
+
error_inputs = get_error_inputs_for_all_optims(device, dtype)
|
| 497 |
+
if _get_device_type(device) == "cpu":
|
| 498 |
+
error_inputs += [
|
| 499 |
+
ErrorOptimizerInput(
|
| 500 |
+
OptimizerInput(
|
| 501 |
+
params=None,
|
| 502 |
+
kwargs=dict(lr=1e-2, lr_decay=-0.5),
|
| 503 |
+
desc="lr_decay must be bigger than 0",
|
| 504 |
+
),
|
| 505 |
+
error_type=ValueError,
|
| 506 |
+
error_regex="Invalid lr_decay value: -0.5",
|
| 507 |
+
),
|
| 508 |
+
]
|
| 509 |
+
return error_inputs
|
| 510 |
+
|
| 511 |
+
|
| 512 |
+
# TODO: consider tensor LR! See multi_tensor_optimizer_configs in test_optim.py --> tensor LR should work
|
| 513 |
+
# with all implementation code paths...
|
| 514 |
+
def optim_inputs_func_adam(device, dtype=None):
|
| 515 |
+
cuda_supported_configs = [
|
| 516 |
+
OptimizerInput(params=None, kwargs={"capturable": True}, desc="capturable"),
|
| 517 |
+
OptimizerInput(
|
| 518 |
+
params=None,
|
| 519 |
+
kwargs={"weight_decay": 0.1, "amsgrad": True, "capturable": True},
|
| 520 |
+
desc="capturable, amsgrad",
|
| 521 |
+
),
|
| 522 |
+
OptimizerInput(
|
| 523 |
+
params=None,
|
| 524 |
+
kwargs={"lr": torch.tensor(0.001), "amsgrad": True, "capturable": True},
|
| 525 |
+
desc="Tensor lr with capturable and amsgrad",
|
| 526 |
+
),
|
| 527 |
+
OptimizerInput(
|
| 528 |
+
params=None,
|
| 529 |
+
kwargs={
|
| 530 |
+
"lr": torch.tensor(0.001),
|
| 531 |
+
"betas": (torch.tensor(0.9), torch.tensor(0.99)),
|
| 532 |
+
"amsgrad": True,
|
| 533 |
+
"capturable": True,
|
| 534 |
+
},
|
| 535 |
+
desc="Tensor lr, Tensor betas, with capturable and amsgrad",
|
| 536 |
+
),
|
| 537 |
+
OptimizerInput(
|
| 538 |
+
params=None,
|
| 539 |
+
kwargs={
|
| 540 |
+
"lr": torch.tensor(0.001),
|
| 541 |
+
"betas": (torch.tensor(0.9), torch.tensor(0.99)),
|
| 542 |
+
"amsgrad": False,
|
| 543 |
+
"capturable": True,
|
| 544 |
+
},
|
| 545 |
+
desc="Tensor lr, Tensor betas, with capturable",
|
| 546 |
+
),
|
| 547 |
+
]
|
| 548 |
+
mps_supported_configs = [
|
| 549 |
+
OptimizerInput(
|
| 550 |
+
params=None, kwargs={"lr": torch.tensor(0.01)}, desc="Tensor lr"
|
| 551 |
+
),
|
| 552 |
+
]
|
| 553 |
+
|
| 554 |
+
total = (
|
| 555 |
+
[
|
| 556 |
+
OptimizerInput(params=None, kwargs={}, desc="default"),
|
| 557 |
+
OptimizerInput(params=None, kwargs={"lr": 0.01}, desc="non-default lr"),
|
| 558 |
+
OptimizerInput(
|
| 559 |
+
params=None, kwargs={"weight_decay": 0.1}, desc="nonzero weight_decay"
|
| 560 |
+
),
|
| 561 |
+
OptimizerInput(
|
| 562 |
+
params=None,
|
| 563 |
+
kwargs={"weight_decay": 0.1, "maximize": True},
|
| 564 |
+
desc="maximize",
|
| 565 |
+
),
|
| 566 |
+
OptimizerInput(
|
| 567 |
+
params=None,
|
| 568 |
+
kwargs={"weight_decay": 0.1, "amsgrad": True},
|
| 569 |
+
desc="amsgrad",
|
| 570 |
+
),
|
| 571 |
+
]
|
| 572 |
+
+ (cuda_supported_configs if _get_device_type(device) == "cuda" else [])
|
| 573 |
+
+ (mps_supported_configs if _get_device_type(device) == "mps" else [])
|
| 574 |
+
)
|
| 575 |
+
if dtype in (torch.float16,):
|
| 576 |
+
for input in total:
|
| 577 |
+
"""
|
| 578 |
+
Too small eps will make denom to be zero for low precision dtype
|
| 579 |
+
denom = (exp_avg_sq.sqrt() / bias_correction2_sqrt).add_(eps)
|
| 580 |
+
For example,
|
| 581 |
+
>>> a
|
| 582 |
+
tensor([0.], dtype=torch.float16)
|
| 583 |
+
>>> a + 1e-8
|
| 584 |
+
tensor([0.], dtype=torch.float16)
|
| 585 |
+
"""
|
| 586 |
+
input.kwargs["eps"] = 0.1
|
| 587 |
+
return total
|
| 588 |
+
|
| 589 |
+
|
| 590 |
+
def optim_error_inputs_func_adam(device, dtype):
|
| 591 |
+
error_inputs = get_error_inputs_for_all_optims(device, dtype)
|
| 592 |
+
if _get_device_type(device) == "cpu":
|
| 593 |
+
error_inputs += [
|
| 594 |
+
ErrorOptimizerInput(
|
| 595 |
+
OptimizerInput(
|
| 596 |
+
params=None,
|
| 597 |
+
kwargs=dict(lr=1e-2, betas=(1.0, 0.0)),
|
| 598 |
+
desc="beta1 should be between 0 and 1",
|
| 599 |
+
),
|
| 600 |
+
error_type=ValueError,
|
| 601 |
+
error_regex="Invalid beta parameter at index 0: 1.0",
|
| 602 |
+
),
|
| 603 |
+
ErrorOptimizerInput(
|
| 604 |
+
OptimizerInput(
|
| 605 |
+
params=None,
|
| 606 |
+
kwargs=dict(lr=1e-2, weight_decay=-1),
|
| 607 |
+
desc="weight_decay should > 0",
|
| 608 |
+
),
|
| 609 |
+
error_type=ValueError,
|
| 610 |
+
error_regex="Invalid weight_decay value: -1",
|
| 611 |
+
),
|
| 612 |
+
ErrorOptimizerInput(
|
| 613 |
+
OptimizerInput(
|
| 614 |
+
params=None,
|
| 615 |
+
kwargs=dict(lr=torch.tensor(0.001), foreach=True),
|
| 616 |
+
desc="lr as Tensor doesn't work with foreach & not capturable",
|
| 617 |
+
),
|
| 618 |
+
error_type=ValueError,
|
| 619 |
+
error_regex="lr as a Tensor is not supported for capturable=False and foreach=True",
|
| 620 |
+
),
|
| 621 |
+
ErrorOptimizerInput(
|
| 622 |
+
OptimizerInput(
|
| 623 |
+
params=None,
|
| 624 |
+
kwargs=dict(lr=1e-2, betas=(0.9, torch.tensor(0.99))),
|
| 625 |
+
desc="betas must be either both floats or both Tensors",
|
| 626 |
+
),
|
| 627 |
+
error_type=ValueError,
|
| 628 |
+
error_regex="betas must be either both floats or both Tensors",
|
| 629 |
+
),
|
| 630 |
+
ErrorOptimizerInput(
|
| 631 |
+
OptimizerInput(
|
| 632 |
+
params=None,
|
| 633 |
+
kwargs=dict(lr=1e-2, betas=(torch.tensor(0.9), 0.99)),
|
| 634 |
+
desc="betas must be either both floats or both Tensors",
|
| 635 |
+
),
|
| 636 |
+
error_type=ValueError,
|
| 637 |
+
error_regex="betas must be either both floats or both Tensors",
|
| 638 |
+
),
|
| 639 |
+
ErrorOptimizerInput(
|
| 640 |
+
OptimizerInput(
|
| 641 |
+
params=None,
|
| 642 |
+
kwargs=dict(
|
| 643 |
+
lr=1e-2,
|
| 644 |
+
betas=(torch.tensor(0.9), torch.tensor(0.99)),
|
| 645 |
+
foreach=True,
|
| 646 |
+
),
|
| 647 |
+
desc=r"betas\[0\] as a Tensor is not supported for capturable=False and foreach=True",
|
| 648 |
+
),
|
| 649 |
+
error_type=ValueError,
|
| 650 |
+
error_regex=r"betas\[0\] as a Tensor is not supported for capturable=False and foreach=True",
|
| 651 |
+
),
|
| 652 |
+
]
|
| 653 |
+
if _get_device_type(device) == "cuda":
|
| 654 |
+
sample_tensor = torch.empty((), device=device, dtype=dtype)
|
| 655 |
+
error_inputs += [
|
| 656 |
+
ErrorOptimizerInput(
|
| 657 |
+
OptimizerInput(
|
| 658 |
+
params=[sample_tensor],
|
| 659 |
+
kwargs={"foreach": True, "fused": True},
|
| 660 |
+
desc="`fused` and `foreach` cannot be `True` together",
|
| 661 |
+
),
|
| 662 |
+
error_type=RuntimeError,
|
| 663 |
+
error_regex="`fused` and `foreach` cannot be `True` together",
|
| 664 |
+
),
|
| 665 |
+
ErrorOptimizerInput(
|
| 666 |
+
OptimizerInput(
|
| 667 |
+
params=[sample_tensor],
|
| 668 |
+
kwargs={"fused": True, "differentiable": True},
|
| 669 |
+
desc="`fused` does not support `differentiable`",
|
| 670 |
+
),
|
| 671 |
+
error_type=RuntimeError,
|
| 672 |
+
error_regex="`fused` does not support `differentiable`",
|
| 673 |
+
),
|
| 674 |
+
]
|
| 675 |
+
return error_inputs
|
| 676 |
+
|
| 677 |
+
|
| 678 |
+
def optim_inputs_func_adamax(device, dtype=None):
|
| 679 |
+
cuda_supported_configs = [
|
| 680 |
+
OptimizerInput(params=None, kwargs={"capturable": True}, desc="capturable"),
|
| 681 |
+
OptimizerInput(
|
| 682 |
+
params=None,
|
| 683 |
+
kwargs={"weight_decay": 0.9, "maximize": True, "capturable": True},
|
| 684 |
+
desc="capturable, maximize, weight_decay",
|
| 685 |
+
),
|
| 686 |
+
OptimizerInput(
|
| 687 |
+
params=None,
|
| 688 |
+
kwargs={"weight_decay": 0, "maximize": True, "capturable": True},
|
| 689 |
+
desc="capturable, maximize",
|
| 690 |
+
),
|
| 691 |
+
OptimizerInput(
|
| 692 |
+
params=None,
|
| 693 |
+
kwargs={"weight_decay": 0.9, "maximize": False, "capturable": True},
|
| 694 |
+
desc="capturable, weight_decay",
|
| 695 |
+
),
|
| 696 |
+
OptimizerInput(
|
| 697 |
+
params=None,
|
| 698 |
+
kwargs={
|
| 699 |
+
"lr": torch.tensor(0.001),
|
| 700 |
+
"weight_decay": 0.9,
|
| 701 |
+
"maximize": False,
|
| 702 |
+
"capturable": True,
|
| 703 |
+
},
|
| 704 |
+
desc="capturable, weight_decay, tensor LR",
|
| 705 |
+
),
|
| 706 |
+
]
|
| 707 |
+
|
| 708 |
+
return [
|
| 709 |
+
OptimizerInput(params=None, kwargs={}, desc="default"),
|
| 710 |
+
OptimizerInput(params=None, kwargs={"lr": 0.1}, desc="non-default lr"),
|
| 711 |
+
OptimizerInput(
|
| 712 |
+
params=None, kwargs={"weight_decay": 0.1}, desc="nonzero weight_decay"
|
| 713 |
+
),
|
| 714 |
+
OptimizerInput(
|
| 715 |
+
params=None,
|
| 716 |
+
kwargs={"maximize": True},
|
| 717 |
+
desc="maximize",
|
| 718 |
+
),
|
| 719 |
+
OptimizerInput(
|
| 720 |
+
params=None,
|
| 721 |
+
kwargs={"weight_decay": 0.1, "maximize": True},
|
| 722 |
+
desc="maximize, weight_decay",
|
| 723 |
+
),
|
| 724 |
+
] + (cuda_supported_configs if _get_device_type(device) == "cuda" else [])
|
| 725 |
+
|
| 726 |
+
|
| 727 |
+
def optim_error_inputs_func_adamax(device, dtype):
|
| 728 |
+
error_inputs = get_error_inputs_for_all_optims(device, dtype)
|
| 729 |
+
if _get_device_type(device) == "cpu":
|
| 730 |
+
error_inputs += [
|
| 731 |
+
ErrorOptimizerInput(
|
| 732 |
+
OptimizerInput(
|
| 733 |
+
params=None,
|
| 734 |
+
kwargs=dict(lr=1e-2, betas=(0.0, 1.0)),
|
| 735 |
+
desc="beta2 should be between 0 and 1",
|
| 736 |
+
),
|
| 737 |
+
error_type=ValueError,
|
| 738 |
+
error_regex="Invalid beta parameter at index 1: 1.0",
|
| 739 |
+
),
|
| 740 |
+
]
|
| 741 |
+
return error_inputs
|
| 742 |
+
|
| 743 |
+
|
| 744 |
+
def optim_inputs_func_adamw(device, dtype=None):
|
| 745 |
+
return optim_inputs_func_adam(device, dtype)
|
| 746 |
+
|
| 747 |
+
|
| 748 |
+
def optim_error_inputs_func_adamw(device, dtype):
|
| 749 |
+
return optim_error_inputs_func_adam(device, dtype)
|
| 750 |
+
|
| 751 |
+
|
| 752 |
+
def optim_inputs_func_asgd(device, dtype=None):
|
| 753 |
+
cuda_supported_configs = [
|
| 754 |
+
OptimizerInput(params=None, kwargs={"capturable": True}, desc="capturable"),
|
| 755 |
+
OptimizerInput(
|
| 756 |
+
params=None,
|
| 757 |
+
kwargs={"maximize": True, "capturable": True},
|
| 758 |
+
desc="maximize, capturable",
|
| 759 |
+
),
|
| 760 |
+
OptimizerInput(
|
| 761 |
+
params=None,
|
| 762 |
+
kwargs={"weight_decay": 0.1, "capturable": True},
|
| 763 |
+
desc="weight_decay, capturable",
|
| 764 |
+
),
|
| 765 |
+
OptimizerInput(
|
| 766 |
+
params=None,
|
| 767 |
+
kwargs={"weight_decay": 0.1, "maximize": True, "capturable": True},
|
| 768 |
+
desc="maximize, weight_decay, capturable",
|
| 769 |
+
),
|
| 770 |
+
OptimizerInput(
|
| 771 |
+
params=None,
|
| 772 |
+
kwargs={
|
| 773 |
+
"lr": torch.tensor(0.001),
|
| 774 |
+
"weight_decay": 0.1,
|
| 775 |
+
"maximize": True,
|
| 776 |
+
"capturable": True,
|
| 777 |
+
},
|
| 778 |
+
desc="maximize, weight_decay, capturable, tensor LR",
|
| 779 |
+
),
|
| 780 |
+
]
|
| 781 |
+
return [
|
| 782 |
+
OptimizerInput(params=None, kwargs={}, desc="default"),
|
| 783 |
+
OptimizerInput(params=None, kwargs={"lambd": 0.1}, desc="non-default lambd"),
|
| 784 |
+
OptimizerInput(params=None, kwargs={"lr": 0.02}, desc="non-default lr"),
|
| 785 |
+
OptimizerInput(params=None, kwargs={"t0": 100}, desc="t0"),
|
| 786 |
+
OptimizerInput(params=None, kwargs={"maximize": True}, desc="maximize"),
|
| 787 |
+
OptimizerInput(
|
| 788 |
+
params=None, kwargs={"weight_decay": 0.1}, desc="nonzero weight_decay"
|
| 789 |
+
),
|
| 790 |
+
OptimizerInput(
|
| 791 |
+
params=None,
|
| 792 |
+
kwargs={"weight_decay": 0.1, "maximize": True},
|
| 793 |
+
desc="maximize, nonzero weight_decay",
|
| 794 |
+
),
|
| 795 |
+
] + (cuda_supported_configs if _get_device_type(device) == "cuda" else [])
|
| 796 |
+
|
| 797 |
+
|
| 798 |
+
def optim_error_inputs_func_asgd(device, dtype):
|
| 799 |
+
error_inputs = get_error_inputs_for_all_optims(device, dtype)
|
| 800 |
+
if _get_device_type(device) == "cpu":
|
| 801 |
+
error_inputs += [
|
| 802 |
+
ErrorOptimizerInput(
|
| 803 |
+
OptimizerInput(
|
| 804 |
+
params=None,
|
| 805 |
+
kwargs=dict(lr=1e-2, weight_decay=-0.5),
|
| 806 |
+
desc="weight_decay should > 0",
|
| 807 |
+
),
|
| 808 |
+
error_type=ValueError,
|
| 809 |
+
error_regex="Invalid weight_decay value: -0.5",
|
| 810 |
+
),
|
| 811 |
+
]
|
| 812 |
+
return error_inputs
|
| 813 |
+
|
| 814 |
+
|
| 815 |
+
def optim_inputs_func_lbfgs(device, dtype=None):
|
| 816 |
+
return [
|
| 817 |
+
OptimizerInput(params=None, kwargs={}, desc="default"),
|
| 818 |
+
OptimizerInput(params=None, kwargs={"lr": 0.01}, desc="non-default lr"),
|
| 819 |
+
OptimizerInput(
|
| 820 |
+
params=None, kwargs={"lr": torch.tensor(0.001)}, desc="Tensor lr"
|
| 821 |
+
),
|
| 822 |
+
OptimizerInput(
|
| 823 |
+
params=None, kwargs={"tolerance_grad": 1e-6}, desc="tolerance_grad"
|
| 824 |
+
),
|
| 825 |
+
OptimizerInput(
|
| 826 |
+
params=None,
|
| 827 |
+
kwargs={"line_search_fn": "strong_wolfe"},
|
| 828 |
+
desc="strong_wolfe",
|
| 829 |
+
),
|
| 830 |
+
]
|
| 831 |
+
|
| 832 |
+
|
| 833 |
+
def optim_error_inputs_func_lbfgs(device, dtype):
|
| 834 |
+
error_inputs = get_error_inputs_for_all_optims(device, dtype)
|
| 835 |
+
return error_inputs
|
| 836 |
+
|
| 837 |
+
|
| 838 |
+
def optim_inputs_func_muon(device, dtype=None):
|
| 839 |
+
return [
|
| 840 |
+
OptimizerInput(params=None, kwargs={}, desc="default"),
|
| 841 |
+
OptimizerInput(params=None, kwargs={"lr": 0.01}, desc="non-default lr"),
|
| 842 |
+
OptimizerInput(
|
| 843 |
+
params=None, kwargs={"lr": torch.tensor(0.001)}, desc="Tensor lr"
|
| 844 |
+
),
|
| 845 |
+
OptimizerInput(
|
| 846 |
+
params=None,
|
| 847 |
+
kwargs={"weight_decay": 0.2},
|
| 848 |
+
desc="non-default weight_decay",
|
| 849 |
+
),
|
| 850 |
+
OptimizerInput(
|
| 851 |
+
params=None,
|
| 852 |
+
kwargs={"momentum": 0.8},
|
| 853 |
+
desc="non-default momentum",
|
| 854 |
+
),
|
| 855 |
+
OptimizerInput(
|
| 856 |
+
params=None,
|
| 857 |
+
kwargs={"ns_steps": 6},
|
| 858 |
+
desc="passing alternative ns_steps",
|
| 859 |
+
),
|
| 860 |
+
OptimizerInput(
|
| 861 |
+
params=None,
|
| 862 |
+
kwargs={
|
| 863 |
+
"ns_coefficients": (3.4, -4.7, 2.0),
|
| 864 |
+
},
|
| 865 |
+
desc="passing alternative ns_coefficients",
|
| 866 |
+
),
|
| 867 |
+
]
|
| 868 |
+
|
| 869 |
+
|
| 870 |
+
def optim_error_inputs_func_muon(device, dtype):
|
| 871 |
+
error_inputs = get_error_inputs_for_all_optims(device, dtype)
|
| 872 |
+
complex_param = torch.rand(2, 3, device=device, dtype=torch.complex64)
|
| 873 |
+
complex_param.grad = torch.rand_like(complex_param)
|
| 874 |
+
non_2d_param = torch.rand(2, 3, 4, device=device, dtype=dtype)
|
| 875 |
+
non_2d_param.grad = torch.rand_like(non_2d_param)
|
| 876 |
+
param = torch.rand(2, 3, device=device, dtype=dtype)
|
| 877 |
+
param.grad = torch.rand_like(param)
|
| 878 |
+
error_inputs += [
|
| 879 |
+
ErrorOptimizerInput(
|
| 880 |
+
OptimizerInput(
|
| 881 |
+
params=[non_2d_param],
|
| 882 |
+
kwargs=dict(),
|
| 883 |
+
desc="only support 2D parameters",
|
| 884 |
+
),
|
| 885 |
+
error_type=ValueError,
|
| 886 |
+
error_regex="Muon only supports 2D parameters",
|
| 887 |
+
error_on=OptimizerErrorEnum.CONSTRUCTION_ERROR,
|
| 888 |
+
),
|
| 889 |
+
ErrorOptimizerInput(
|
| 890 |
+
OptimizerInput(
|
| 891 |
+
params=[param],
|
| 892 |
+
kwargs={"adjust_lr_fn": "arbitrary"},
|
| 893 |
+
desc="only support `original` and `match_rms_adamw`",
|
| 894 |
+
),
|
| 895 |
+
error_type=ValueError,
|
| 896 |
+
error_regex="Adjust learning rate function arbitrary is not supported",
|
| 897 |
+
error_on=OptimizerErrorEnum.CONSTRUCTION_ERROR,
|
| 898 |
+
),
|
| 899 |
+
ErrorOptimizerInput(
|
| 900 |
+
OptimizerInput(
|
| 901 |
+
params=[complex_param],
|
| 902 |
+
kwargs=dict(),
|
| 903 |
+
desc="does not support complex parameters",
|
| 904 |
+
),
|
| 905 |
+
error_type=RuntimeError,
|
| 906 |
+
error_regex="Muon does not support complex parameters",
|
| 907 |
+
error_on=OptimizerErrorEnum.STEP_ERROR,
|
| 908 |
+
),
|
| 909 |
+
]
|
| 910 |
+
return error_inputs
|
| 911 |
+
|
| 912 |
+
|
| 913 |
+
def optim_inputs_func_nadam(device, dtype=None):
|
| 914 |
+
cuda_supported_configs = [
|
| 915 |
+
OptimizerInput(params=None, kwargs={"capturable": True}, desc="capturable"),
|
| 916 |
+
OptimizerInput(
|
| 917 |
+
params=None,
|
| 918 |
+
kwargs={"weight_decay": 0.9, "momentum_decay": 6e-3, "capturable": True},
|
| 919 |
+
desc="weight_decay, capturable",
|
| 920 |
+
),
|
| 921 |
+
OptimizerInput(
|
| 922 |
+
params=None,
|
| 923 |
+
kwargs={
|
| 924 |
+
"weight_decay": 0.9,
|
| 925 |
+
"momentum_decay": 6e-3,
|
| 926 |
+
"decoupled_weight_decay": True,
|
| 927 |
+
"capturable": True,
|
| 928 |
+
},
|
| 929 |
+
desc="decoupled_weight_decay, capturable",
|
| 930 |
+
),
|
| 931 |
+
OptimizerInput(
|
| 932 |
+
params=None,
|
| 933 |
+
kwargs={
|
| 934 |
+
"lr": torch.tensor(0.001),
|
| 935 |
+
"weight_decay": 0.9,
|
| 936 |
+
"momentum_decay": 6e-3,
|
| 937 |
+
"decoupled_weight_decay": True,
|
| 938 |
+
"capturable": True,
|
| 939 |
+
},
|
| 940 |
+
desc="decoupled_weight_decay, capturable",
|
| 941 |
+
),
|
| 942 |
+
]
|
| 943 |
+
return [
|
| 944 |
+
OptimizerInput(params=None, kwargs={}, desc="default"),
|
| 945 |
+
OptimizerInput(params=None, kwargs={"lr": 1e-3}, desc="non-default lr"),
|
| 946 |
+
OptimizerInput(
|
| 947 |
+
params=None,
|
| 948 |
+
kwargs={"momentum_decay": 6e-3},
|
| 949 |
+
desc="non-zero momentum_decay",
|
| 950 |
+
),
|
| 951 |
+
OptimizerInput(
|
| 952 |
+
params=None,
|
| 953 |
+
kwargs={
|
| 954 |
+
"weight_decay": 0.1,
|
| 955 |
+
},
|
| 956 |
+
desc="weight_decay",
|
| 957 |
+
),
|
| 958 |
+
OptimizerInput(
|
| 959 |
+
params=None,
|
| 960 |
+
kwargs={"weight_decay": 0.1, "momentum_decay": 6e-3},
|
| 961 |
+
desc="weight_decay, momentum_decay",
|
| 962 |
+
),
|
| 963 |
+
OptimizerInput(
|
| 964 |
+
params=None,
|
| 965 |
+
kwargs={
|
| 966 |
+
"weight_decay": 0.1,
|
| 967 |
+
"momentum_decay": 6e-3,
|
| 968 |
+
"decoupled_weight_decay": True,
|
| 969 |
+
},
|
| 970 |
+
desc="decoupled_weight_decay",
|
| 971 |
+
),
|
| 972 |
+
OptimizerInput(
|
| 973 |
+
params=None,
|
| 974 |
+
kwargs={"weight_decay": 0.1, "maximize": True},
|
| 975 |
+
desc="maximize",
|
| 976 |
+
),
|
| 977 |
+
] + (cuda_supported_configs if _get_device_type(device) == "cuda" else [])
|
| 978 |
+
|
| 979 |
+
|
| 980 |
+
def optim_error_inputs_func_nadam(device, dtype):
|
| 981 |
+
error_inputs = get_error_inputs_for_all_optims(device, dtype)
|
| 982 |
+
if _get_device_type(device) == "cpu":
|
| 983 |
+
error_inputs += [
|
| 984 |
+
ErrorOptimizerInput(
|
| 985 |
+
OptimizerInput(
|
| 986 |
+
params=None,
|
| 987 |
+
kwargs=dict(lr=1e-2, betas=(1.0, 0.0)),
|
| 988 |
+
desc="beta1 should be between 0 and 1",
|
| 989 |
+
),
|
| 990 |
+
error_type=ValueError,
|
| 991 |
+
error_regex="Invalid beta parameter at index 0: 1.0",
|
| 992 |
+
),
|
| 993 |
+
ErrorOptimizerInput(
|
| 994 |
+
OptimizerInput(
|
| 995 |
+
params=None,
|
| 996 |
+
kwargs=dict(lr=1e-2, momentum_decay=-0.2),
|
| 997 |
+
desc="momentum_decay should > 0",
|
| 998 |
+
),
|
| 999 |
+
error_type=ValueError,
|
| 1000 |
+
error_regex="Invalid momentum_decay value: -0.2",
|
| 1001 |
+
),
|
| 1002 |
+
]
|
| 1003 |
+
return error_inputs
|
| 1004 |
+
|
| 1005 |
+
|
| 1006 |
+
# Weird story bro, NAdam and RAdam do not have maximize.
|
| 1007 |
+
def optim_inputs_func_radam(device=None, dtype=None):
|
| 1008 |
+
cuda_supported_configs = [
|
| 1009 |
+
OptimizerInput(params=None, kwargs={"capturable": True}, desc="capturable"),
|
| 1010 |
+
OptimizerInput(
|
| 1011 |
+
params=None,
|
| 1012 |
+
kwargs={
|
| 1013 |
+
"capturable": True,
|
| 1014 |
+
"weight_decay": 0.1,
|
| 1015 |
+
},
|
| 1016 |
+
desc="capturable, weight_decay",
|
| 1017 |
+
),
|
| 1018 |
+
OptimizerInput(
|
| 1019 |
+
params=None,
|
| 1020 |
+
kwargs={
|
| 1021 |
+
"capturable": True,
|
| 1022 |
+
"weight_decay": 0.1,
|
| 1023 |
+
"decoupled_weight_decay": True,
|
| 1024 |
+
},
|
| 1025 |
+
desc="capturable, weight_decay, decoupled_weight_decay",
|
| 1026 |
+
),
|
| 1027 |
+
OptimizerInput(
|
| 1028 |
+
params=None,
|
| 1029 |
+
kwargs={
|
| 1030 |
+
"lr": torch.tensor(0.001),
|
| 1031 |
+
"capturable": True,
|
| 1032 |
+
"weight_decay": 0.1,
|
| 1033 |
+
"decoupled_weight_decay": True,
|
| 1034 |
+
},
|
| 1035 |
+
desc="capturable, weight_decay, decoupled_weight_decay, tensor LR",
|
| 1036 |
+
),
|
| 1037 |
+
]
|
| 1038 |
+
return [
|
| 1039 |
+
OptimizerInput(params=None, kwargs={}, desc="default"),
|
| 1040 |
+
OptimizerInput(params=None, kwargs={"lr": 2e-3}, desc="non-default lr"),
|
| 1041 |
+
OptimizerInput(params=None, kwargs={"eps": 1e-6}, desc="non-default eps"),
|
| 1042 |
+
OptimizerInput(
|
| 1043 |
+
params=None, kwargs={"weight_decay": 0.1}, desc="nonzero weight_decay"
|
| 1044 |
+
),
|
| 1045 |
+
OptimizerInput(
|
| 1046 |
+
params=None,
|
| 1047 |
+
kwargs={"weight_decay": 0.1, "decoupled_weight_decay": True},
|
| 1048 |
+
desc="decoupled_weight_decay",
|
| 1049 |
+
),
|
| 1050 |
+
OptimizerInput(
|
| 1051 |
+
params=None,
|
| 1052 |
+
kwargs={"weight_decay": 0.1, "maximize": True},
|
| 1053 |
+
desc="maximize",
|
| 1054 |
+
),
|
| 1055 |
+
] + (cuda_supported_configs if _get_device_type(device) == "cuda" else [])
|
| 1056 |
+
|
| 1057 |
+
|
| 1058 |
+
def optim_error_inputs_func_radam(device, dtype):
|
| 1059 |
+
error_inputs = get_error_inputs_for_all_optims(device, dtype)
|
| 1060 |
+
if _get_device_type(device) == "cpu":
|
| 1061 |
+
error_inputs += [
|
| 1062 |
+
ErrorOptimizerInput(
|
| 1063 |
+
OptimizerInput(
|
| 1064 |
+
params=None,
|
| 1065 |
+
kwargs=dict(lr=1e-2, betas=(1.0, 0.0)),
|
| 1066 |
+
desc="beta1 should be between 0 and 1",
|
| 1067 |
+
),
|
| 1068 |
+
error_type=ValueError,
|
| 1069 |
+
error_regex="Invalid beta parameter at index 0: 1.0",
|
| 1070 |
+
),
|
| 1071 |
+
ErrorOptimizerInput(
|
| 1072 |
+
OptimizerInput(
|
| 1073 |
+
params=None,
|
| 1074 |
+
kwargs=dict(lr=1e-2, weight_decay=-1),
|
| 1075 |
+
desc="weight_decay should > 0",
|
| 1076 |
+
),
|
| 1077 |
+
error_type=ValueError,
|
| 1078 |
+
error_regex="Invalid weight_decay value: -1",
|
| 1079 |
+
),
|
| 1080 |
+
]
|
| 1081 |
+
return error_inputs
|
| 1082 |
+
|
| 1083 |
+
|
| 1084 |
+
def optim_inputs_func_rmsprop(device, dtype=None):
|
| 1085 |
+
cuda_supported_configs = [
|
| 1086 |
+
OptimizerInput(params=None, kwargs={"capturable": True}, desc="capturable"),
|
| 1087 |
+
OptimizerInput(
|
| 1088 |
+
params=None,
|
| 1089 |
+
kwargs={"weight_decay": 0.1, "maximize": True, "capturable": True},
|
| 1090 |
+
desc="capturable, maximize",
|
| 1091 |
+
),
|
| 1092 |
+
OptimizerInput(
|
| 1093 |
+
params=None,
|
| 1094 |
+
kwargs={"lr": torch.tensor(0.001), "capturable": True},
|
| 1095 |
+
desc="Tensor lr with capturable",
|
| 1096 |
+
),
|
| 1097 |
+
]
|
| 1098 |
+
|
| 1099 |
+
return [
|
| 1100 |
+
OptimizerInput(params=None, kwargs={}, desc="default"),
|
| 1101 |
+
OptimizerInput(params=None, kwargs={"lr": 1e-3}, desc="non-default lr"),
|
| 1102 |
+
OptimizerInput(
|
| 1103 |
+
params=None, kwargs={"weight_decay": 0.1}, desc="nonzero weight_decay"
|
| 1104 |
+
),
|
| 1105 |
+
OptimizerInput(
|
| 1106 |
+
params=None,
|
| 1107 |
+
kwargs={
|
| 1108 |
+
"maximize": True,
|
| 1109 |
+
},
|
| 1110 |
+
desc="maximize",
|
| 1111 |
+
),
|
| 1112 |
+
OptimizerInput(
|
| 1113 |
+
params=None,
|
| 1114 |
+
kwargs={"weight_decay": 0.1, "centered": True},
|
| 1115 |
+
desc="centered",
|
| 1116 |
+
),
|
| 1117 |
+
OptimizerInput(
|
| 1118 |
+
params=None,
|
| 1119 |
+
kwargs={
|
| 1120 |
+
"maximize": True,
|
| 1121 |
+
"weight_decay": 0.1,
|
| 1122 |
+
},
|
| 1123 |
+
desc="maximize, weight_decay",
|
| 1124 |
+
),
|
| 1125 |
+
OptimizerInput(
|
| 1126 |
+
params=None,
|
| 1127 |
+
kwargs={"weight_decay": 0.1, "centered": True, "momentum": 0.1},
|
| 1128 |
+
desc="momentum",
|
| 1129 |
+
),
|
| 1130 |
+
OptimizerInput(
|
| 1131 |
+
params=None,
|
| 1132 |
+
kwargs={
|
| 1133 |
+
"weight_decay": 0.1,
|
| 1134 |
+
"centered": True,
|
| 1135 |
+
"momentum": 0.1,
|
| 1136 |
+
"maximize": True,
|
| 1137 |
+
},
|
| 1138 |
+
desc="maximize, centered, weight_decay, w/ momentum",
|
| 1139 |
+
),
|
| 1140 |
+
] + (cuda_supported_configs if _get_device_type(device) == "cuda" else [])
|
| 1141 |
+
|
| 1142 |
+
|
| 1143 |
+
def optim_error_inputs_func_rmsprop(device, dtype):
|
| 1144 |
+
error_inputs = get_error_inputs_for_all_optims(device, dtype)
|
| 1145 |
+
if _get_device_type(device) == "cpu":
|
| 1146 |
+
error_inputs += [
|
| 1147 |
+
ErrorOptimizerInput(
|
| 1148 |
+
OptimizerInput(
|
| 1149 |
+
params=None,
|
| 1150 |
+
kwargs=dict(lr=1e-2, momentum=-1.0),
|
| 1151 |
+
desc="momentum should be between 0 and 1",
|
| 1152 |
+
),
|
| 1153 |
+
error_type=ValueError,
|
| 1154 |
+
error_regex="Invalid momentum value: -1.0",
|
| 1155 |
+
),
|
| 1156 |
+
]
|
| 1157 |
+
return error_inputs
|
| 1158 |
+
|
| 1159 |
+
|
| 1160 |
+
def optim_inputs_func_rprop(device, dtype=None):
|
| 1161 |
+
cuda_supported_configs = [
|
| 1162 |
+
OptimizerInput(params=None, kwargs={"capturable": True}, desc="capturable"),
|
| 1163 |
+
OptimizerInput(
|
| 1164 |
+
params=None,
|
| 1165 |
+
kwargs={"lr": torch.tensor(0.001), "capturable": True},
|
| 1166 |
+
desc="Tensor lr with capturable",
|
| 1167 |
+
),
|
| 1168 |
+
]
|
| 1169 |
+
|
| 1170 |
+
return [
|
| 1171 |
+
OptimizerInput(params=None, kwargs={}, desc="default"),
|
| 1172 |
+
OptimizerInput(params=None, kwargs={"lr": 2e-4}, desc="non-default lr"),
|
| 1173 |
+
OptimizerInput(
|
| 1174 |
+
params=None, kwargs={"etas": (0.5, 1.5)}, desc="non-default etas"
|
| 1175 |
+
),
|
| 1176 |
+
OptimizerInput(
|
| 1177 |
+
params=None,
|
| 1178 |
+
kwargs={"step_sizes": (2e-6, 100)},
|
| 1179 |
+
desc="non-default step_sizes",
|
| 1180 |
+
),
|
| 1181 |
+
OptimizerInput(params=None, kwargs={"maximize": True}, desc="maximize"),
|
| 1182 |
+
] + (cuda_supported_configs if _get_device_type(device) == "cuda" else [])
|
| 1183 |
+
|
| 1184 |
+
|
| 1185 |
+
def optim_error_inputs_func_rprop(device, dtype):
|
| 1186 |
+
error_inputs = get_error_inputs_for_all_optims(device, dtype)
|
| 1187 |
+
if _get_device_type(device) == "cpu":
|
| 1188 |
+
error_inputs += [
|
| 1189 |
+
ErrorOptimizerInput(
|
| 1190 |
+
OptimizerInput(
|
| 1191 |
+
params=None,
|
| 1192 |
+
kwargs=dict(lr=1e-2, etas=(1.0, 0.5)),
|
| 1193 |
+
desc="0 < eta1 < 1 < eta2",
|
| 1194 |
+
),
|
| 1195 |
+
error_type=ValueError,
|
| 1196 |
+
error_regex="Invalid eta values: 1.0, 0.5",
|
| 1197 |
+
),
|
| 1198 |
+
]
|
| 1199 |
+
return error_inputs
|
| 1200 |
+
|
| 1201 |
+
|
| 1202 |
+
def optim_inputs_func_sgd(device, dtype=None):
|
| 1203 |
+
return [
|
| 1204 |
+
OptimizerInput(params=None, kwargs={}, desc="default"),
|
| 1205 |
+
OptimizerInput(params=None, kwargs={"lr": 1e-2}, desc="non-default lr"),
|
| 1206 |
+
OptimizerInput(
|
| 1207 |
+
params=None, kwargs={"lr": torch.tensor(0.001)}, desc="tensor lr"
|
| 1208 |
+
),
|
| 1209 |
+
OptimizerInput(
|
| 1210 |
+
params=None, kwargs={"weight_decay": 0.5}, desc="non-zero weight_decay"
|
| 1211 |
+
),
|
| 1212 |
+
OptimizerInput(params=None, kwargs={"momentum": 0.9}, desc="momentum"),
|
| 1213 |
+
OptimizerInput(
|
| 1214 |
+
params=None,
|
| 1215 |
+
kwargs={"weight_decay": 0.1, "maximize": True},
|
| 1216 |
+
desc="maximize",
|
| 1217 |
+
),
|
| 1218 |
+
OptimizerInput(
|
| 1219 |
+
params=None,
|
| 1220 |
+
kwargs={"momentum": 0.9, "dampening": 0.5},
|
| 1221 |
+
desc="dampening",
|
| 1222 |
+
),
|
| 1223 |
+
OptimizerInput(
|
| 1224 |
+
params=None,
|
| 1225 |
+
kwargs={"momentum": 0.9, "weight_decay": 0.1},
|
| 1226 |
+
desc="weight_decay w/ momentum",
|
| 1227 |
+
),
|
| 1228 |
+
OptimizerInput(
|
| 1229 |
+
params=None,
|
| 1230 |
+
kwargs={"momentum": 0.9, "nesterov": True, "weight_decay": 0.1},
|
| 1231 |
+
desc="nesterov",
|
| 1232 |
+
),
|
| 1233 |
+
]
|
| 1234 |
+
|
| 1235 |
+
|
| 1236 |
+
def optim_error_inputs_func_sgd(device, dtype):
|
| 1237 |
+
error_inputs = get_error_inputs_for_all_optims(device, dtype)
|
| 1238 |
+
if _get_device_type(device) == "cpu":
|
| 1239 |
+
error_inputs += [
|
| 1240 |
+
ErrorOptimizerInput(
|
| 1241 |
+
OptimizerInput(
|
| 1242 |
+
params=None,
|
| 1243 |
+
kwargs=dict(lr=1e-2, momentum=-0.5),
|
| 1244 |
+
desc="momentum should be between 0 and 1",
|
| 1245 |
+
),
|
| 1246 |
+
error_type=ValueError,
|
| 1247 |
+
error_regex="Invalid momentum value: -0.5",
|
| 1248 |
+
),
|
| 1249 |
+
]
|
| 1250 |
+
return error_inputs
|
| 1251 |
+
|
| 1252 |
+
|
| 1253 |
+
def optim_inputs_func_sparseadam(device, dtype=None):
|
| 1254 |
+
return [
|
| 1255 |
+
OptimizerInput(params=None, kwargs={}, desc="default"),
|
| 1256 |
+
OptimizerInput(
|
| 1257 |
+
params=None, kwargs={"lr": 0.01}, desc="non-default lr"
|
| 1258 |
+
), # TODO: Move out to testing in param_group?
|
| 1259 |
+
OptimizerInput(
|
| 1260 |
+
params=None, kwargs={"lr": torch.tensor(0.001)}, desc="Tensor lr"
|
| 1261 |
+
),
|
| 1262 |
+
OptimizerInput(params=None, kwargs={"maximize": True}, desc="maximize"),
|
| 1263 |
+
]
|
| 1264 |
+
|
| 1265 |
+
|
| 1266 |
+
def optim_error_inputs_func_sparseadam(device, dtype):
|
| 1267 |
+
error_inputs = get_error_inputs_for_all_optims(device, dtype)
|
| 1268 |
+
|
| 1269 |
+
if _get_device_type(device) == "cpu":
|
| 1270 |
+
error_inputs += [
|
| 1271 |
+
ErrorOptimizerInput(
|
| 1272 |
+
OptimizerInput(
|
| 1273 |
+
params=None,
|
| 1274 |
+
kwargs=dict(lr=1e-2, betas=(1.0, 0.0)),
|
| 1275 |
+
desc="beta1 should be between 0 and 1",
|
| 1276 |
+
),
|
| 1277 |
+
error_type=ValueError,
|
| 1278 |
+
error_regex="Invalid beta parameter at index 0: 1.0",
|
| 1279 |
+
),
|
| 1280 |
+
ErrorOptimizerInput(
|
| 1281 |
+
OptimizerInput(
|
| 1282 |
+
params=[
|
| 1283 |
+
torch.zeros(
|
| 1284 |
+
3, layout=torch.sparse_coo, device=device, dtype=dtype
|
| 1285 |
+
)
|
| 1286 |
+
],
|
| 1287 |
+
kwargs={},
|
| 1288 |
+
desc="dense params required",
|
| 1289 |
+
),
|
| 1290 |
+
error_type=ValueError,
|
| 1291 |
+
error_regex="SparseAdam requires dense parameter tensors",
|
| 1292 |
+
),
|
| 1293 |
+
ErrorOptimizerInput(
|
| 1294 |
+
OptimizerInput(
|
| 1295 |
+
params=[
|
| 1296 |
+
{
|
| 1297 |
+
"params": [
|
| 1298 |
+
torch.zeros(
|
| 1299 |
+
3,
|
| 1300 |
+
layout=torch.sparse_coo,
|
| 1301 |
+
device=device,
|
| 1302 |
+
dtype=dtype,
|
| 1303 |
+
)
|
| 1304 |
+
]
|
| 1305 |
+
}
|
| 1306 |
+
],
|
| 1307 |
+
kwargs={},
|
| 1308 |
+
desc="dense params required in param_groups",
|
| 1309 |
+
),
|
| 1310 |
+
error_type=ValueError,
|
| 1311 |
+
error_regex="SparseAdam requires dense parameter tensors",
|
| 1312 |
+
),
|
| 1313 |
+
ErrorOptimizerInput(
|
| 1314 |
+
OptimizerInput(
|
| 1315 |
+
params=[torch.rand(2, 3, device=device, dtype=torch.complex64)],
|
| 1316 |
+
kwargs={},
|
| 1317 |
+
desc="complex not supported",
|
| 1318 |
+
),
|
| 1319 |
+
error_type=ValueError,
|
| 1320 |
+
error_regex="SparseAdam does not support complex parameters",
|
| 1321 |
+
),
|
| 1322 |
+
]
|
| 1323 |
+
return error_inputs
|
| 1324 |
+
|
| 1325 |
+
|
| 1326 |
+
def _get_device_type(device: Union[str, torch.device]) -> str:
|
| 1327 |
+
# Returns the device type as a string, e.g., "cpu" or "cuda"
|
| 1328 |
+
if isinstance(device, torch.device):
|
| 1329 |
+
device = str(device.type)
|
| 1330 |
+
assert isinstance(device, str)
|
| 1331 |
+
return device.split(":")[0]
|
| 1332 |
+
|
| 1333 |
+
|
| 1334 |
+
def _get_optim_inputs_including_global_cliquey_kwargs(
|
| 1335 |
+
device, dtype, optim_info, skip=()
|
| 1336 |
+
) -> list[OptimizerInput]:
|
| 1337 |
+
"""
|
| 1338 |
+
Return a list of all configs for a given optimizer as a list of OptimizerInputs,
|
| 1339 |
+
including configs that have supported global cliquey kwargs (foreach, fused,
|
| 1340 |
+
differentiable) based on optim_info.supported_impls.
|
| 1341 |
+
|
| 1342 |
+
The configs (optim_inputs) returned by optim_info.optim_inputs_func(...)
|
| 1343 |
+
intentionally do NOT include global cliquey kwargs to give flexibility to tests.
|
| 1344 |
+
For example, testing correctness between toggling foreach on and off is now
|
| 1345 |
+
trivial. That said, we sometimes want to test for all possible configs on an
|
| 1346 |
+
optimizer including all supported flags, so this helper returns all optim inputs.
|
| 1347 |
+
"""
|
| 1348 |
+
assert all(x in ["foreach", "fused", "differentiable"] for x in skip), (
|
| 1349 |
+
"skip must be a subset of ['foreach', 'fused', 'differentiable']"
|
| 1350 |
+
)
|
| 1351 |
+
|
| 1352 |
+
optim_inputs = optim_info.optim_inputs_func(device)
|
| 1353 |
+
|
| 1354 |
+
supported_impls = tuple(
|
| 1355 |
+
x
|
| 1356 |
+
for x in optim_info.supported_impls
|
| 1357 |
+
if x not in skip
|
| 1358 |
+
and (_get_device_type(device) in optim_info.supports_fused_on or x != "fused")
|
| 1359 |
+
and (
|
| 1360 |
+
_get_device_type(device) in _get_foreach_kernels_supported_devices()
|
| 1361 |
+
or x != "foreach"
|
| 1362 |
+
)
|
| 1363 |
+
)
|
| 1364 |
+
|
| 1365 |
+
all_optim_inputs = []
|
| 1366 |
+
for optim_input in optim_inputs:
|
| 1367 |
+
# Add the base config where all the flags are False
|
| 1368 |
+
base_kwargs = deepcopy(optim_input.kwargs)
|
| 1369 |
+
if len(supported_impls) != 0:
|
| 1370 |
+
for flag in supported_impls:
|
| 1371 |
+
base_kwargs[flag] = False
|
| 1372 |
+
all_optim_inputs.append(
|
| 1373 |
+
OptimizerInput(params=None, kwargs=base_kwargs, desc=optim_input.desc)
|
| 1374 |
+
)
|
| 1375 |
+
else:
|
| 1376 |
+
all_optim_inputs.append(optim_input)
|
| 1377 |
+
# Add a config for when each of the global cliquey kwargs is True
|
| 1378 |
+
# Note that in [optimizer kwarg categories], these kwargs are mutually
|
| 1379 |
+
# exclusive, so we do not need to product them together.
|
| 1380 |
+
for flag in supported_impls:
|
| 1381 |
+
new_kwargs = deepcopy(base_kwargs)
|
| 1382 |
+
new_kwargs[flag] = True
|
| 1383 |
+
all_optim_inputs.append(
|
| 1384 |
+
OptimizerInput(
|
| 1385 |
+
params=None, kwargs=new_kwargs, desc=f"{optim_input.desc} & {flag}"
|
| 1386 |
+
)
|
| 1387 |
+
)
|
| 1388 |
+
return all_optim_inputs
|
| 1389 |
+
|
| 1390 |
+
|
| 1391 |
+
# Database of OptimizerInfo entries in alphabetical order.
|
| 1392 |
+
optim_db: list[OptimizerInfo] = [
|
| 1393 |
+
OptimizerInfo(
|
| 1394 |
+
Adadelta,
|
| 1395 |
+
optim_inputs_func=optim_inputs_func_adadelta,
|
| 1396 |
+
optim_error_inputs_func=optim_error_inputs_func_adadelta,
|
| 1397 |
+
supported_impls=("foreach", "differentiable"),
|
| 1398 |
+
has_capturable_arg=True,
|
| 1399 |
+
skips=(
|
| 1400 |
+
DecorateInfo(
|
| 1401 |
+
skipIfTorchDynamo("See #116028"),
|
| 1402 |
+
"TestOptimRenewed",
|
| 1403 |
+
"test_set_default_dtype_works_with_foreach",
|
| 1404 |
+
),
|
| 1405 |
+
DecorateInfo(
|
| 1406 |
+
skipIfTorchDynamo(
|
| 1407 |
+
"Accessing grad.real errors, see https://github.com/pytorch/pytorch/issues/117184"
|
| 1408 |
+
),
|
| 1409 |
+
"TestOptimRenewed",
|
| 1410 |
+
"test_complex_2d",
|
| 1411 |
+
),
|
| 1412 |
+
# Note on tolerances:
|
| 1413 |
+
# test_correctness_Adadelta_cuda_float32
|
| 1414 |
+
# Mismatched elements: 10 / 100 (10.0%)
|
| 1415 |
+
# Greatest absolute difference: 4.838220775127411e-05 at index (7, 4) (up to 1e-05 allowed)
|
| 1416 |
+
# Greatest relative difference: 0.007270356640219688 at index (7, 2) (up to 1e-05 allowed)
|
| 1417 |
+
# This is due to floating point ordering error + usage of sqrt
|
| 1418 |
+
DecorateInfo(
|
| 1419 |
+
toleranceOverride(
|
| 1420 |
+
{
|
| 1421 |
+
torch.float32: tol(
|
| 1422 |
+
rtol=5.5e-4,
|
| 1423 |
+
atol=5e-5,
|
| 1424 |
+
)
|
| 1425 |
+
}
|
| 1426 |
+
),
|
| 1427 |
+
"CompiledOptimizerParityTests",
|
| 1428 |
+
"test_correctness",
|
| 1429 |
+
),
|
| 1430 |
+
DecorateInfo(
|
| 1431 |
+
skipIfTorchDynamo(
|
| 1432 |
+
"This test uses mocks, which dynamo does not support"
|
| 1433 |
+
),
|
| 1434 |
+
"TestOptimRenewed",
|
| 1435 |
+
"test_defaults_changed_to_foreach",
|
| 1436 |
+
),
|
| 1437 |
+
),
|
| 1438 |
+
),
|
| 1439 |
+
OptimizerInfo(
|
| 1440 |
+
Adafactor,
|
| 1441 |
+
optim_inputs_func=optim_inputs_func_adafactor,
|
| 1442 |
+
optim_error_inputs_func=optim_error_inputs_func_adafactor,
|
| 1443 |
+
supported_impls=("foreach",),
|
| 1444 |
+
not_og_supported_flags=("foreach",),
|
| 1445 |
+
supports_complex=False,
|
| 1446 |
+
skips=(
|
| 1447 |
+
DecorateInfo(
|
| 1448 |
+
unittest.skip("See #133268 regarding dtype being None"),
|
| 1449 |
+
"CompiledOptimizerParityTests",
|
| 1450 |
+
"test_correctness",
|
| 1451 |
+
device_type="cuda",
|
| 1452 |
+
active_if=lambda kwargs: kwargs.get("use_closure", False),
|
| 1453 |
+
),
|
| 1454 |
+
DecorateInfo(
|
| 1455 |
+
skipIfTorchDynamo("See #133268 regarding dtype being None"),
|
| 1456 |
+
"TestOptimRenewed",
|
| 1457 |
+
"test_can_load_older_state_dict",
|
| 1458 |
+
device_type="cuda",
|
| 1459 |
+
),
|
| 1460 |
+
DecorateInfo(
|
| 1461 |
+
skipIfTorchDynamo("See #133268 regarding dtype being None"),
|
| 1462 |
+
"TestOptimRenewed",
|
| 1463 |
+
"test_deepcopy_copies_all_public_attrs",
|
| 1464 |
+
device_type="cuda",
|
| 1465 |
+
),
|
| 1466 |
+
DecorateInfo(
|
| 1467 |
+
skipIfTorchDynamo("See #133268 regarding dtype being None"),
|
| 1468 |
+
"TestOptimRenewed",
|
| 1469 |
+
"test_foreach_large_tensor",
|
| 1470 |
+
),
|
| 1471 |
+
DecorateInfo(
|
| 1472 |
+
skipIfTorchDynamo("See #133268 regarding dtype being None"),
|
| 1473 |
+
"TestOptimRenewed",
|
| 1474 |
+
"test_foreach_matches_forloop",
|
| 1475 |
+
),
|
| 1476 |
+
DecorateInfo(
|
| 1477 |
+
skipIfTorchDynamo("See #133268 regarding dtype being None"),
|
| 1478 |
+
"TestOptimRenewed",
|
| 1479 |
+
"test_load_nontensor_step",
|
| 1480 |
+
device_type="cuda",
|
| 1481 |
+
),
|
| 1482 |
+
DecorateInfo(
|
| 1483 |
+
skipIfTorchDynamo("See #133268 regarding dtype being None"),
|
| 1484 |
+
"TestOptimRenewed",
|
| 1485 |
+
"test_mixed_device_dtype",
|
| 1486 |
+
),
|
| 1487 |
+
DecorateInfo(
|
| 1488 |
+
skipIfTorchDynamo("See #133268 regarding dtype being None"),
|
| 1489 |
+
"TestOptimRenewed",
|
| 1490 |
+
"test_param_groups_lr",
|
| 1491 |
+
device_type="cuda",
|
| 1492 |
+
),
|
| 1493 |
+
DecorateInfo(
|
| 1494 |
+
skipIfTorchDynamo("See #133268 regarding dtype being None"),
|
| 1495 |
+
"TestOptimRenewed",
|
| 1496 |
+
"test_param_groups_weight_decay",
|
| 1497 |
+
device_type="cuda",
|
| 1498 |
+
),
|
| 1499 |
+
DecorateInfo(
|
| 1500 |
+
skipIfTorchDynamo("See #133268 regarding dtype being None"),
|
| 1501 |
+
"TestOptimRenewed",
|
| 1502 |
+
"test_peak_memory_foreach",
|
| 1503 |
+
),
|
| 1504 |
+
DecorateInfo(
|
| 1505 |
+
skipIfTorchDynamo("See #133268 regarding dtype being None"),
|
| 1506 |
+
"TestOptimRenewed",
|
| 1507 |
+
"test_save_load_equality_with_weights_only",
|
| 1508 |
+
device_type="cuda",
|
| 1509 |
+
),
|
| 1510 |
+
DecorateInfo(
|
| 1511 |
+
skipIfTorchDynamo("See #116028 regarding copy not supported"),
|
| 1512 |
+
"TestOptimRenewed",
|
| 1513 |
+
"test_set_default_dtype_works_with_foreach",
|
| 1514 |
+
),
|
| 1515 |
+
DecorateInfo(
|
| 1516 |
+
skipIfTorchDynamo("See #133268 regarding dtype being None"),
|
| 1517 |
+
"TestOptimRenewed",
|
| 1518 |
+
"test_state_dict_deterministic",
|
| 1519 |
+
device_type="cuda",
|
| 1520 |
+
),
|
| 1521 |
+
DecorateInfo(
|
| 1522 |
+
skipIfTorchDynamo("See #133268 regarding dtype being None"),
|
| 1523 |
+
"TestOptimRenewed",
|
| 1524 |
+
"test_step_is_noop_for_zero_grads",
|
| 1525 |
+
device_type="cuda",
|
| 1526 |
+
),
|
| 1527 |
+
DecorateInfo(
|
| 1528 |
+
unittest.skip("See #133268 regarding dtype being None"),
|
| 1529 |
+
"CompiledOptimizerParityTests",
|
| 1530 |
+
"test_correctness",
|
| 1531 |
+
device_type="xpu",
|
| 1532 |
+
),
|
| 1533 |
+
DecorateInfo(
|
| 1534 |
+
skipIfTorchDynamo("See #133268 regarding dtype being None"),
|
| 1535 |
+
"TestOptimRenewed",
|
| 1536 |
+
"test_can_load_older_state_dict",
|
| 1537 |
+
device_type="xpu",
|
| 1538 |
+
),
|
| 1539 |
+
DecorateInfo(
|
| 1540 |
+
skipIfTorchDynamo("See #133268 regarding dtype being None"),
|
| 1541 |
+
"TestOptimRenewed",
|
| 1542 |
+
"test_deepcopy_copies_all_public_attrs",
|
| 1543 |
+
device_type="xpu",
|
| 1544 |
+
),
|
| 1545 |
+
DecorateInfo(
|
| 1546 |
+
skipIfTorchDynamo("See #133268 regarding dtype being None"),
|
| 1547 |
+
"TestOptimRenewed",
|
| 1548 |
+
"test_load_nontensor_step",
|
| 1549 |
+
device_type="xpu",
|
| 1550 |
+
),
|
| 1551 |
+
DecorateInfo(
|
| 1552 |
+
skipIfTorchDynamo("See #133268 regarding dtype being None"),
|
| 1553 |
+
"TestOptimRenewed",
|
| 1554 |
+
"test_param_groups_lr",
|
| 1555 |
+
device_type="xpu",
|
| 1556 |
+
),
|
| 1557 |
+
DecorateInfo(
|
| 1558 |
+
skipIfTorchDynamo("See #133268 regarding dtype being None"),
|
| 1559 |
+
"TestOptimRenewed",
|
| 1560 |
+
"test_param_groups_weight_decay",
|
| 1561 |
+
device_type="xpu",
|
| 1562 |
+
),
|
| 1563 |
+
DecorateInfo(
|
| 1564 |
+
skipIfTorchDynamo("See #133268 regarding dtype being None"),
|
| 1565 |
+
"TestOptimRenewed",
|
| 1566 |
+
"test_save_load_equality_with_weights_only",
|
| 1567 |
+
device_type="xpu",
|
| 1568 |
+
),
|
| 1569 |
+
DecorateInfo(
|
| 1570 |
+
skipIfTorchDynamo("See #133268 regarding dtype being None"),
|
| 1571 |
+
"TestOptimRenewed",
|
| 1572 |
+
"test_state_dict_deterministic",
|
| 1573 |
+
device_type="xpu",
|
| 1574 |
+
),
|
| 1575 |
+
DecorateInfo(
|
| 1576 |
+
skipIfTorchDynamo("See #133268 regarding dtype being None"),
|
| 1577 |
+
"TestOptimRenewed",
|
| 1578 |
+
"test_step_is_noop_for_zero_grads",
|
| 1579 |
+
device_type="xpu",
|
| 1580 |
+
),
|
| 1581 |
+
),
|
| 1582 |
+
),
|
| 1583 |
+
OptimizerInfo(
|
| 1584 |
+
Adagrad,
|
| 1585 |
+
optim_inputs_func=optim_inputs_func_adagrad,
|
| 1586 |
+
optim_error_inputs_func=optim_error_inputs_func_adagrad,
|
| 1587 |
+
supported_impls=("foreach", "differentiable", "fused"),
|
| 1588 |
+
not_og_supported_flags=(
|
| 1589 |
+
"foreach",
|
| 1590 |
+
"differentiable",
|
| 1591 |
+
"fused",
|
| 1592 |
+
"maximize",
|
| 1593 |
+
"capturable",
|
| 1594 |
+
),
|
| 1595 |
+
supports_fused_on=("cpu",),
|
| 1596 |
+
supports_sparse=True,
|
| 1597 |
+
metadata_for_sparse=(
|
| 1598 |
+
{"lr": 0.1, "weight_decay": 0, "lr_decay": 0},
|
| 1599 |
+
[
|
| 1600 |
+
lambda opt: StepLR(opt, gamma=1 - 1e-5, step_size=500),
|
| 1601 |
+
lambda opt: ReduceLROnPlateau(opt, threshold=1e-4),
|
| 1602 |
+
],
|
| 1603 |
+
),
|
| 1604 |
+
decorators=(
|
| 1605 |
+
DecorateInfo(
|
| 1606 |
+
# Note on tolerances:
|
| 1607 |
+
# difference comes from the fact that the non fused kernel have
|
| 1608 |
+
# more dtype cast operations. We have another test test_fused_cpu_matches_cuda
|
| 1609 |
+
# to make sure there is no discrepancies between cuda fused kernel
|
| 1610 |
+
# and cpu fused kernel
|
| 1611 |
+
toleranceOverride(
|
| 1612 |
+
{
|
| 1613 |
+
torch.bfloat16: tol(atol=5e-3, rtol=5e-3),
|
| 1614 |
+
torch.float16: tol(atol=5e-3, rtol=5e-3),
|
| 1615 |
+
}
|
| 1616 |
+
),
|
| 1617 |
+
"TestOptimRenewed",
|
| 1618 |
+
"test_fused_matches_forloop",
|
| 1619 |
+
),
|
| 1620 |
+
),
|
| 1621 |
+
skips=(
|
| 1622 |
+
DecorateInfo(
|
| 1623 |
+
skipIfTorchDynamo("See #116028"),
|
| 1624 |
+
"TestOptimRenewed",
|
| 1625 |
+
"test_set_default_dtype_works_with_foreach",
|
| 1626 |
+
),
|
| 1627 |
+
DecorateInfo(
|
| 1628 |
+
skipIfTorchDynamo(
|
| 1629 |
+
"Accessing grad.real errors, see https://github.com/pytorch/pytorch/issues/117184"
|
| 1630 |
+
),
|
| 1631 |
+
"TestOptimRenewed",
|
| 1632 |
+
"test_complex_2d",
|
| 1633 |
+
),
|
| 1634 |
+
DecorateInfo(
|
| 1635 |
+
skipIfTorchDynamo(
|
| 1636 |
+
"This test uses mocks, which dynamo does not support"
|
| 1637 |
+
),
|
| 1638 |
+
"TestOptimRenewed",
|
| 1639 |
+
"test_defaults_changed_to_foreach",
|
| 1640 |
+
),
|
| 1641 |
+
),
|
| 1642 |
+
),
|
| 1643 |
+
OptimizerInfo(
|
| 1644 |
+
Adam,
|
| 1645 |
+
optim_inputs_func=optim_inputs_func_adam,
|
| 1646 |
+
scheduler_inputs=(
|
| 1647 |
+
[lambda opt: ExponentialLR(opt, gamma=0.9)],
|
| 1648 |
+
[lambda opt: LinearLR(opt, start_factor=0.4, total_iters=4)],
|
| 1649 |
+
[
|
| 1650 |
+
lambda opt: ConstantLR(opt, factor=0.4, total_iters=4),
|
| 1651 |
+
lambda opt: ExponentialLR(opt, gamma=0.9),
|
| 1652 |
+
],
|
| 1653 |
+
[
|
| 1654 |
+
lambda opt: ExponentialLR(opt, gamma=0.9),
|
| 1655 |
+
lambda opt: ReduceLROnPlateau(opt),
|
| 1656 |
+
],
|
| 1657 |
+
[lambda opt: ConstantLR(opt, factor=0.4, total_iters=4)],
|
| 1658 |
+
[lambda opt: PolynomialLR(opt, power=0.9, total_iters=4)],
|
| 1659 |
+
[
|
| 1660 |
+
lambda opt: StepLR(opt, gamma=0.9, step_size=10),
|
| 1661 |
+
lambda opt: ReduceLROnPlateau(opt),
|
| 1662 |
+
],
|
| 1663 |
+
),
|
| 1664 |
+
optim_error_inputs_func=optim_error_inputs_func_adam,
|
| 1665 |
+
supported_impls=("foreach", "differentiable", "fused"),
|
| 1666 |
+
has_capturable_arg=True,
|
| 1667 |
+
not_og_supported_flags=(
|
| 1668 |
+
"foreach",
|
| 1669 |
+
"differentiable",
|
| 1670 |
+
"fused",
|
| 1671 |
+
"maximize",
|
| 1672 |
+
"capturable",
|
| 1673 |
+
),
|
| 1674 |
+
supports_fused_on=("cpu", "cuda", "mps"),
|
| 1675 |
+
decorators=(
|
| 1676 |
+
# Expected floating point error between fused and compiled forloop
|
| 1677 |
+
DecorateInfo(
|
| 1678 |
+
toleranceOverride({torch.float64: tol(atol=4.5e-7, rtol=2.2e-6)}),
|
| 1679 |
+
"TestOptimRenewed",
|
| 1680 |
+
"test_fused_matches_forloop",
|
| 1681 |
+
active_if=lambda kwargs: TEST_WITH_TORCHDYNAMO
|
| 1682 |
+
and kwargs["dtype"] == torch.float64,
|
| 1683 |
+
),
|
| 1684 |
+
DecorateInfo(
|
| 1685 |
+
# Note on tolerances:
|
| 1686 |
+
# difference comes from the fact that the non fused kernel have
|
| 1687 |
+
# more dtype cast operations. We have another test test_fused_cpu_matches_cuda
|
| 1688 |
+
# to make sure there is no discrepancies between cuda fused kernel
|
| 1689 |
+
# and cpu fused kernel
|
| 1690 |
+
toleranceOverride(
|
| 1691 |
+
{
|
| 1692 |
+
torch.bfloat16: tol(atol=5e-3, rtol=5e-3),
|
| 1693 |
+
torch.float16: tol(atol=5e-3, rtol=5e-3),
|
| 1694 |
+
}
|
| 1695 |
+
),
|
| 1696 |
+
"TestOptimRenewed",
|
| 1697 |
+
"test_fused_matches_forloop",
|
| 1698 |
+
),
|
| 1699 |
+
DecorateInfo(
|
| 1700 |
+
# Note on tolerances:
|
| 1701 |
+
# Tracking through #127000
|
| 1702 |
+
toleranceOverride(
|
| 1703 |
+
{
|
| 1704 |
+
torch.float32: tol(atol=3e-5, rtol=1.3e-06),
|
| 1705 |
+
}
|
| 1706 |
+
),
|
| 1707 |
+
"TestCudaOptims",
|
| 1708 |
+
"test_grad_scaling_autocast_fused_optimizers",
|
| 1709 |
+
),
|
| 1710 |
+
),
|
| 1711 |
+
skips=(
|
| 1712 |
+
DecorateInfo(
|
| 1713 |
+
skipIfTorchDynamo(
|
| 1714 |
+
"Errors w/ Global state changed, see https://github.com/pytorch/pytorch/issues/116028"
|
| 1715 |
+
),
|
| 1716 |
+
"TestOptimRenewed",
|
| 1717 |
+
"test_set_default_dtype_works_with_foreach",
|
| 1718 |
+
),
|
| 1719 |
+
DecorateInfo(
|
| 1720 |
+
skipIfTorchDynamo(
|
| 1721 |
+
"Accessing grad.real errors, see https://github.com/pytorch/pytorch/issues/117184"
|
| 1722 |
+
),
|
| 1723 |
+
"TestOptimRenewed",
|
| 1724 |
+
"test_complex_2d",
|
| 1725 |
+
),
|
| 1726 |
+
DecorateInfo(
|
| 1727 |
+
skipIfTorchDynamo(
|
| 1728 |
+
"This test uses mocks, which dynamo does not support"
|
| 1729 |
+
),
|
| 1730 |
+
"TestOptimRenewed",
|
| 1731 |
+
"test_defaults_changed_to_foreach",
|
| 1732 |
+
),
|
| 1733 |
+
),
|
| 1734 |
+
),
|
| 1735 |
+
OptimizerInfo(
|
| 1736 |
+
Adamax,
|
| 1737 |
+
optim_inputs_func=optim_inputs_func_adamax,
|
| 1738 |
+
optim_error_inputs_func=optim_error_inputs_func_adamax,
|
| 1739 |
+
supported_impls=("foreach", "differentiable"),
|
| 1740 |
+
has_capturable_arg=True,
|
| 1741 |
+
skips=(
|
| 1742 |
+
DecorateInfo(
|
| 1743 |
+
skipIfTorchDynamo("See #116028"),
|
| 1744 |
+
"TestOptimRenewed",
|
| 1745 |
+
"test_set_default_dtype_works_with_foreach",
|
| 1746 |
+
),
|
| 1747 |
+
DecorateInfo(
|
| 1748 |
+
skipIfTorchDynamo(
|
| 1749 |
+
"Accessing grad.real errors, see https://github.com/pytorch/pytorch/issues/117184"
|
| 1750 |
+
),
|
| 1751 |
+
"TestOptimRenewed",
|
| 1752 |
+
"test_complex_2d",
|
| 1753 |
+
),
|
| 1754 |
+
DecorateInfo(
|
| 1755 |
+
unittest.skip("Uses too much memory, even for H100, surprisingly."),
|
| 1756 |
+
"TestOptimRenewed",
|
| 1757 |
+
"test_foreach_large_tensor",
|
| 1758 |
+
),
|
| 1759 |
+
DecorateInfo(
|
| 1760 |
+
skipIfTorchDynamo(
|
| 1761 |
+
"This test uses mocks, which dynamo does not support"
|
| 1762 |
+
),
|
| 1763 |
+
"TestOptimRenewed",
|
| 1764 |
+
"test_defaults_changed_to_foreach",
|
| 1765 |
+
),
|
| 1766 |
+
),
|
| 1767 |
+
),
|
| 1768 |
+
OptimizerInfo(
|
| 1769 |
+
AdamW,
|
| 1770 |
+
optim_inputs_func=optim_inputs_func_adamw,
|
| 1771 |
+
optim_error_inputs_func=optim_error_inputs_func_adamw,
|
| 1772 |
+
supported_impls=("foreach", "differentiable", "fused"),
|
| 1773 |
+
not_og_supported_flags=(
|
| 1774 |
+
"foreach",
|
| 1775 |
+
"differentiable",
|
| 1776 |
+
"fused",
|
| 1777 |
+
"maximize",
|
| 1778 |
+
"capturable",
|
| 1779 |
+
),
|
| 1780 |
+
supports_fused_on=("cpu", "cuda", "mps"),
|
| 1781 |
+
has_capturable_arg=True,
|
| 1782 |
+
decorators=(
|
| 1783 |
+
# Expected error between compiled forloop and fused optimizers
|
| 1784 |
+
DecorateInfo(
|
| 1785 |
+
toleranceOverride({torch.float64: tol(atol=4.5e-7, rtol=2.2e-6)}),
|
| 1786 |
+
"TestOptimRenewed",
|
| 1787 |
+
"test_fused_matches_forloop",
|
| 1788 |
+
active_if=lambda kwargs: TEST_WITH_TORCHDYNAMO
|
| 1789 |
+
and kwargs["dtype"] == torch.float64,
|
| 1790 |
+
),
|
| 1791 |
+
DecorateInfo(
|
| 1792 |
+
toleranceOverride(
|
| 1793 |
+
# Note on tolerances:
|
| 1794 |
+
# difference comes from the fact that the non fused kernel have
|
| 1795 |
+
# more dtype cast operations. We have another test test_fused_cpu_matches_cuda
|
| 1796 |
+
# to make sure there is no discrepancies between cuda fused kernel
|
| 1797 |
+
# and cpu fused kernel
|
| 1798 |
+
{
|
| 1799 |
+
torch.bfloat16: tol(atol=5e-3, rtol=5e-3),
|
| 1800 |
+
torch.float16: tol(atol=5e-3, rtol=5e-3),
|
| 1801 |
+
}
|
| 1802 |
+
),
|
| 1803 |
+
"TestOptimRenewed",
|
| 1804 |
+
"test_fused_matches_forloop",
|
| 1805 |
+
),
|
| 1806 |
+
# Note on tolerances:
|
| 1807 |
+
# Tracking through #127000
|
| 1808 |
+
DecorateInfo(
|
| 1809 |
+
toleranceOverride(
|
| 1810 |
+
{
|
| 1811 |
+
torch.float32: tol(
|
| 1812 |
+
atol=3e-5,
|
| 1813 |
+
rtol=1.3e-06,
|
| 1814 |
+
)
|
| 1815 |
+
}
|
| 1816 |
+
),
|
| 1817 |
+
"TestCudaOptims",
|
| 1818 |
+
"test_grad_scaling_autocast_fused_optimizers",
|
| 1819 |
+
),
|
| 1820 |
+
),
|
| 1821 |
+
skips=(
|
| 1822 |
+
DecorateInfo(
|
| 1823 |
+
skipIfTorchDynamo(
|
| 1824 |
+
"Errors w/ Global state changed, see https://github.com/pytorch/pytorch/issues/116028"
|
| 1825 |
+
),
|
| 1826 |
+
"TestOptimRenewed",
|
| 1827 |
+
"test_set_default_dtype_works_with_foreach",
|
| 1828 |
+
),
|
| 1829 |
+
DecorateInfo(
|
| 1830 |
+
skipIfTorchDynamo(
|
| 1831 |
+
"Accessing grad.real errors, see https://github.com/pytorch/pytorch/issues/117184"
|
| 1832 |
+
),
|
| 1833 |
+
"TestOptimRenewed",
|
| 1834 |
+
"test_complex_2d",
|
| 1835 |
+
),
|
| 1836 |
+
DecorateInfo(
|
| 1837 |
+
skipIfTorchDynamo(
|
| 1838 |
+
"This test uses mocks, which dynamo does not support"
|
| 1839 |
+
),
|
| 1840 |
+
"TestOptimRenewed",
|
| 1841 |
+
"test_defaults_changed_to_foreach",
|
| 1842 |
+
),
|
| 1843 |
+
),
|
| 1844 |
+
),
|
| 1845 |
+
OptimizerInfo(
|
| 1846 |
+
ASGD,
|
| 1847 |
+
optim_inputs_func=optim_inputs_func_asgd,
|
| 1848 |
+
optim_error_inputs_func=optim_error_inputs_func_asgd,
|
| 1849 |
+
supported_impls=("foreach", "differentiable"),
|
| 1850 |
+
has_capturable_arg=True,
|
| 1851 |
+
skips=(
|
| 1852 |
+
DecorateInfo(
|
| 1853 |
+
skipIfTorchDynamo(
|
| 1854 |
+
"Errors w/ Global state changed, see https://github.com/pytorch/pytorch/issues/116028"
|
| 1855 |
+
),
|
| 1856 |
+
"TestOptimRenewed",
|
| 1857 |
+
"test_set_default_dtype_works_with_foreach",
|
| 1858 |
+
),
|
| 1859 |
+
DecorateInfo(
|
| 1860 |
+
skipIfTorchDynamo(
|
| 1861 |
+
"Accessing grad.real errors, see https://github.com/pytorch/pytorch/issues/117184"
|
| 1862 |
+
),
|
| 1863 |
+
"TestOptimRenewed",
|
| 1864 |
+
"test_complex_2d",
|
| 1865 |
+
),
|
| 1866 |
+
DecorateInfo(
|
| 1867 |
+
toleranceOverride(
|
| 1868 |
+
{
|
| 1869 |
+
torch.float32: tol(atol=1.5e-5, rtol=1e-5),
|
| 1870 |
+
}
|
| 1871 |
+
),
|
| 1872 |
+
"TestOptimRenewed",
|
| 1873 |
+
"test_step_is_noop_for_zero_grads",
|
| 1874 |
+
),
|
| 1875 |
+
DecorateInfo(
|
| 1876 |
+
skipIfTorchDynamo(
|
| 1877 |
+
"This test uses mocks, which dynamo does not support"
|
| 1878 |
+
),
|
| 1879 |
+
"TestOptimRenewed",
|
| 1880 |
+
"test_defaults_changed_to_foreach",
|
| 1881 |
+
),
|
| 1882 |
+
DecorateInfo(
|
| 1883 |
+
unittest.skip(
|
| 1884 |
+
"ASGD internally changes the weights even with zero grad"
|
| 1885 |
+
),
|
| 1886 |
+
"TestOptimRenewed",
|
| 1887 |
+
"test_step_is_noop_for_zero_grads",
|
| 1888 |
+
),
|
| 1889 |
+
),
|
| 1890 |
+
),
|
| 1891 |
+
OptimizerInfo(
|
| 1892 |
+
LBFGS,
|
| 1893 |
+
optim_inputs_func=optim_inputs_func_lbfgs,
|
| 1894 |
+
optim_error_inputs_func=optim_error_inputs_func_lbfgs,
|
| 1895 |
+
supported_impls=(),
|
| 1896 |
+
step_requires_closure=True,
|
| 1897 |
+
supports_param_groups=False,
|
| 1898 |
+
supports_multiple_devices=False,
|
| 1899 |
+
skips=(
|
| 1900 |
+
# Fails on MacOS 13.2.1 in CI https://github.com/pytorch/pytorch/issues/117094
|
| 1901 |
+
DecorateInfo(
|
| 1902 |
+
skipIfMPS,
|
| 1903 |
+
"TestOptimRenewed",
|
| 1904 |
+
"test_can_load_older_state_dict",
|
| 1905 |
+
device_type="mps",
|
| 1906 |
+
),
|
| 1907 |
+
DecorateInfo(
|
| 1908 |
+
toleranceOverride(
|
| 1909 |
+
{
|
| 1910 |
+
torch.complex64: tol(
|
| 1911 |
+
rtol=4.5e-5,
|
| 1912 |
+
atol=5e-5,
|
| 1913 |
+
)
|
| 1914 |
+
}
|
| 1915 |
+
),
|
| 1916 |
+
"TestOptimRenewed",
|
| 1917 |
+
"test_complex_2d",
|
| 1918 |
+
),
|
| 1919 |
+
DecorateInfo(
|
| 1920 |
+
unittest.skip("Does not support param groups"),
|
| 1921 |
+
"TestOptimRenewed",
|
| 1922 |
+
"test_param_groups_lr",
|
| 1923 |
+
),
|
| 1924 |
+
DecorateInfo(
|
| 1925 |
+
unittest.skip("Does not support param groups"),
|
| 1926 |
+
"TestOptimRenewed",
|
| 1927 |
+
"test_param_groups_weight_decay",
|
| 1928 |
+
),
|
| 1929 |
+
DecorateInfo(
|
| 1930 |
+
unittest.skip("LBFGS doesn't support multidevice"),
|
| 1931 |
+
"TestOptimRenewed",
|
| 1932 |
+
"test_forloop_goes_right_direction_multigpu",
|
| 1933 |
+
),
|
| 1934 |
+
DecorateInfo(
|
| 1935 |
+
unittest.skip("Does not support param groups"),
|
| 1936 |
+
"TestOptimRenewed",
|
| 1937 |
+
"test_param_group_with_lrscheduler_goes_right_direction",
|
| 1938 |
+
),
|
| 1939 |
+
# https://github.com/pytorch/pytorch/issues/131398
|
| 1940 |
+
DecorateInfo(
|
| 1941 |
+
unittest.expectedFailure,
|
| 1942 |
+
"CompiledOptimizerParityTests",
|
| 1943 |
+
"test_correctness",
|
| 1944 |
+
active_if=lambda kwargs: sys.platform == "darwin"
|
| 1945 |
+
and kwargs["use_closure"],
|
| 1946 |
+
),
|
| 1947 |
+
),
|
| 1948 |
+
),
|
| 1949 |
+
OptimizerInfo(
|
| 1950 |
+
Muon,
|
| 1951 |
+
optim_inputs_func=optim_inputs_func_muon,
|
| 1952 |
+
optim_error_inputs_func=optim_error_inputs_func_muon,
|
| 1953 |
+
supported_impls=(),
|
| 1954 |
+
not_og_supported_flags=(),
|
| 1955 |
+
supports_complex=False,
|
| 1956 |
+
skips=(
|
| 1957 |
+
# Note on numerical differences: `compile` applies different matmul tuning,
|
| 1958 |
+
# which leads to deviations compared to eager mode. In the Newton–Schulz
|
| 1959 |
+
# iteration for orthogonalization, computations are done in bfloat16, further
|
| 1960 |
+
# amplifying these numerical differences.
|
| 1961 |
+
DecorateInfo(
|
| 1962 |
+
unittest.skip(
|
| 1963 |
+
"Expect high difference between compiled and eager due to bfloat16 and iterative process."
|
| 1964 |
+
),
|
| 1965 |
+
"CompiledOptimizerParityTests",
|
| 1966 |
+
"test_correctness",
|
| 1967 |
+
),
|
| 1968 |
+
),
|
| 1969 |
+
),
|
| 1970 |
+
OptimizerInfo(
|
| 1971 |
+
NAdam,
|
| 1972 |
+
optim_inputs_func=optim_inputs_func_nadam,
|
| 1973 |
+
optim_error_inputs_func=optim_error_inputs_func_nadam,
|
| 1974 |
+
supported_impls=("foreach", "differentiable"),
|
| 1975 |
+
has_capturable_arg=True,
|
| 1976 |
+
skips=(
|
| 1977 |
+
DecorateInfo(
|
| 1978 |
+
skipIfTorchDynamo(
|
| 1979 |
+
"Errors w/ Global state changed, see https://github.com/pytorch/pytorch/issues/116028"
|
| 1980 |
+
),
|
| 1981 |
+
"TestOptimRenewed",
|
| 1982 |
+
"test_set_default_dtype_works_with_foreach",
|
| 1983 |
+
),
|
| 1984 |
+
DecorateInfo(
|
| 1985 |
+
skipIfTorchDynamo(
|
| 1986 |
+
"Accessing grad.real errors, see https://github.com/pytorch/pytorch/issues/117184"
|
| 1987 |
+
),
|
| 1988 |
+
"TestOptimRenewed",
|
| 1989 |
+
"test_complex_2d",
|
| 1990 |
+
),
|
| 1991 |
+
DecorateInfo(
|
| 1992 |
+
skipIfTorchDynamo(
|
| 1993 |
+
"Errors, https://github.com/pytorch/pytorch/issues/117150"
|
| 1994 |
+
),
|
| 1995 |
+
"TestOptimRenewed",
|
| 1996 |
+
"test_load_nontensor_step",
|
| 1997 |
+
),
|
| 1998 |
+
DecorateInfo(
|
| 1999 |
+
skipIfTorchDynamo(
|
| 2000 |
+
"This test uses mocks, which dynamo does not support"
|
| 2001 |
+
),
|
| 2002 |
+
"TestOptimRenewed",
|
| 2003 |
+
"test_defaults_changed_to_foreach",
|
| 2004 |
+
),
|
| 2005 |
+
),
|
| 2006 |
+
),
|
| 2007 |
+
OptimizerInfo(
|
| 2008 |
+
RAdam,
|
| 2009 |
+
optim_inputs_func=optim_inputs_func_radam,
|
| 2010 |
+
optim_error_inputs_func=optim_error_inputs_func_radam,
|
| 2011 |
+
supported_impls=("foreach", "differentiable"),
|
| 2012 |
+
has_capturable_arg=True,
|
| 2013 |
+
skips=(
|
| 2014 |
+
DecorateInfo(
|
| 2015 |
+
skipIfTorchDynamo(
|
| 2016 |
+
"Errors w/ Global state changed, see https://github.com/pytorch/pytorch/issues/116028"
|
| 2017 |
+
),
|
| 2018 |
+
"TestOptimRenewed",
|
| 2019 |
+
"test_set_default_dtype_works_with_foreach",
|
| 2020 |
+
),
|
| 2021 |
+
DecorateInfo(
|
| 2022 |
+
skipIfTorchDynamo(
|
| 2023 |
+
"Accessing grad.real errors, see https://github.com/pytorch/pytorch/issues/117184"
|
| 2024 |
+
),
|
| 2025 |
+
"TestOptimRenewed",
|
| 2026 |
+
"test_complex_2d",
|
| 2027 |
+
),
|
| 2028 |
+
DecorateInfo(
|
| 2029 |
+
toleranceOverride(
|
| 2030 |
+
{
|
| 2031 |
+
# previously atol=1e-7, rtol=1e-7
|
| 2032 |
+
torch.float64: tol(atol=1.5e-7, rtol=1.1e-7)
|
| 2033 |
+
}
|
| 2034 |
+
),
|
| 2035 |
+
"TestOptimRenewed",
|
| 2036 |
+
"test_foreach_matches_forloop",
|
| 2037 |
+
),
|
| 2038 |
+
DecorateInfo(
|
| 2039 |
+
skipIfTorchDynamo(
|
| 2040 |
+
"This test uses mocks, which dynamo does not support"
|
| 2041 |
+
),
|
| 2042 |
+
"TestOptimRenewed",
|
| 2043 |
+
"test_defaults_changed_to_foreach",
|
| 2044 |
+
),
|
| 2045 |
+
),
|
| 2046 |
+
),
|
| 2047 |
+
OptimizerInfo(
|
| 2048 |
+
RMSprop,
|
| 2049 |
+
optim_inputs_func=optim_inputs_func_rmsprop,
|
| 2050 |
+
optim_error_inputs_func=optim_error_inputs_func_rmsprop,
|
| 2051 |
+
supported_impls=("foreach", "differentiable"),
|
| 2052 |
+
has_capturable_arg=True,
|
| 2053 |
+
skips=(
|
| 2054 |
+
DecorateInfo(
|
| 2055 |
+
skipIfTorchDynamo("See #116028"),
|
| 2056 |
+
"TestOptimRenewed",
|
| 2057 |
+
"test_set_default_dtype_works_with_foreach",
|
| 2058 |
+
),
|
| 2059 |
+
DecorateInfo(
|
| 2060 |
+
skipIfTorchDynamo(
|
| 2061 |
+
"Accessing grad.real errors, see https://github.com/pytorch/pytorch/issues/117184"
|
| 2062 |
+
),
|
| 2063 |
+
"TestOptimRenewed",
|
| 2064 |
+
"test_complex_2d",
|
| 2065 |
+
),
|
| 2066 |
+
DecorateInfo(
|
| 2067 |
+
toleranceOverride(
|
| 2068 |
+
{ # previously atol=5-05, rtol=0.001, https://github.com/pytorch/pytorch/issues/116202
|
| 2069 |
+
torch.float32: tol(atol=5e-04, rtol=0.01),
|
| 2070 |
+
}
|
| 2071 |
+
),
|
| 2072 |
+
"TestOptimRenewed",
|
| 2073 |
+
"test_mixed_device_dtype",
|
| 2074 |
+
active_if=TEST_WITH_TORCHDYNAMO,
|
| 2075 |
+
),
|
| 2076 |
+
DecorateInfo(
|
| 2077 |
+
skipIfTorchDynamo(
|
| 2078 |
+
"This test uses mocks, which dynamo does not support"
|
| 2079 |
+
),
|
| 2080 |
+
"TestOptimRenewed",
|
| 2081 |
+
"test_defaults_changed_to_foreach",
|
| 2082 |
+
),
|
| 2083 |
+
),
|
| 2084 |
+
),
|
| 2085 |
+
OptimizerInfo(
|
| 2086 |
+
Rprop,
|
| 2087 |
+
optim_inputs_func=optim_inputs_func_rprop,
|
| 2088 |
+
optim_error_inputs_func=optim_error_inputs_func_rprop,
|
| 2089 |
+
supported_impls=("foreach", "differentiable"),
|
| 2090 |
+
has_capturable_arg=True,
|
| 2091 |
+
skips=(
|
| 2092 |
+
DecorateInfo(
|
| 2093 |
+
skipIfTorchDynamo("See #116028"),
|
| 2094 |
+
"TestOptimRenewed",
|
| 2095 |
+
"test_set_default_dtype_works_with_foreach",
|
| 2096 |
+
),
|
| 2097 |
+
DecorateInfo(
|
| 2098 |
+
skipIfTorchDynamo(
|
| 2099 |
+
"Accessing grad.real errors, see https://github.com/pytorch/pytorch/issues/117184"
|
| 2100 |
+
),
|
| 2101 |
+
"TestOptimRenewed",
|
| 2102 |
+
"test_complex_2d",
|
| 2103 |
+
),
|
| 2104 |
+
DecorateInfo(
|
| 2105 |
+
skipIfTorchDynamo(
|
| 2106 |
+
"This test uses mocks, which dynamo does not support"
|
| 2107 |
+
),
|
| 2108 |
+
"TestOptimRenewed",
|
| 2109 |
+
"test_defaults_changed_to_foreach",
|
| 2110 |
+
),
|
| 2111 |
+
),
|
| 2112 |
+
),
|
| 2113 |
+
OptimizerInfo(
|
| 2114 |
+
SGD,
|
| 2115 |
+
optim_inputs_func=optim_inputs_func_sgd,
|
| 2116 |
+
scheduler_inputs=(
|
| 2117 |
+
[lambda opt: StepLR(opt, gamma=0.9, step_size=10)],
|
| 2118 |
+
[
|
| 2119 |
+
lambda opt: LinearLR(
|
| 2120 |
+
opt, start_factor=0.4, end_factor=0.8, total_iters=4
|
| 2121 |
+
)
|
| 2122 |
+
],
|
| 2123 |
+
[
|
| 2124 |
+
lambda opt: StepLR(opt, gamma=0.9, step_size=10),
|
| 2125 |
+
lambda opt: LinearLR(
|
| 2126 |
+
opt, start_factor=0.4, end_factor=0.6, total_iters=4
|
| 2127 |
+
),
|
| 2128 |
+
],
|
| 2129 |
+
[
|
| 2130 |
+
lambda opt: StepLR(opt, gamma=0.99, step_size=10),
|
| 2131 |
+
lambda opt: ExponentialLR(opt, gamma=0.99),
|
| 2132 |
+
lambda opt: ReduceLROnPlateau(opt),
|
| 2133 |
+
],
|
| 2134 |
+
[lambda opt: ConstantLR(opt, factor=0.4, total_iters=4)],
|
| 2135 |
+
[lambda opt: PolynomialLR(opt, power=0.9, total_iters=4)],
|
| 2136 |
+
[
|
| 2137 |
+
lambda opt: StepLR(opt, gamma=0.9, step_size=10),
|
| 2138 |
+
lambda opt: ReduceLROnPlateau(opt),
|
| 2139 |
+
],
|
| 2140 |
+
),
|
| 2141 |
+
optim_error_inputs_func=optim_error_inputs_func_sgd,
|
| 2142 |
+
supported_impls=("foreach", "differentiable", "fused"),
|
| 2143 |
+
not_og_supported_flags=(
|
| 2144 |
+
"foreach",
|
| 2145 |
+
"differentiable",
|
| 2146 |
+
"fused",
|
| 2147 |
+
"maximize",
|
| 2148 |
+
"capturable",
|
| 2149 |
+
),
|
| 2150 |
+
supports_sparse=True,
|
| 2151 |
+
metadata_for_sparse=(
|
| 2152 |
+
{
|
| 2153 |
+
"lr": 4.8e-3,
|
| 2154 |
+
"maximize": False,
|
| 2155 |
+
"momentum": 0,
|
| 2156 |
+
"nesterov": False,
|
| 2157 |
+
"weight_decay": 0,
|
| 2158 |
+
},
|
| 2159 |
+
[lambda opt: StepLR(opt, gamma=0.99999, step_size=300)],
|
| 2160 |
+
),
|
| 2161 |
+
supports_fused_on=(
|
| 2162 |
+
"cpu",
|
| 2163 |
+
"cuda",
|
| 2164 |
+
"mps",
|
| 2165 |
+
),
|
| 2166 |
+
skips=(
|
| 2167 |
+
DecorateInfo(
|
| 2168 |
+
skipIfTorchDynamo(
|
| 2169 |
+
"Errors w/ Global state changed, see https://github.com/pytorch/pytorch/issues/116028"
|
| 2170 |
+
),
|
| 2171 |
+
"TestOptimRenewed",
|
| 2172 |
+
"test_set_default_dtype_works_with_foreach",
|
| 2173 |
+
),
|
| 2174 |
+
DecorateInfo(
|
| 2175 |
+
skipIfTorchDynamo(
|
| 2176 |
+
"Accessing grad.real errors, see https://github.com/pytorch/pytorch/issues/117184"
|
| 2177 |
+
),
|
| 2178 |
+
"TestOptimRenewed",
|
| 2179 |
+
"test_complex_2d",
|
| 2180 |
+
),
|
| 2181 |
+
DecorateInfo(
|
| 2182 |
+
toleranceOverride(
|
| 2183 |
+
{ # previously atol=5-05, rtol=0.001, https://github.com/pytorch/pytorch/issues/116202
|
| 2184 |
+
torch.float32: tol(atol=5e-04, rtol=0.007),
|
| 2185 |
+
}
|
| 2186 |
+
),
|
| 2187 |
+
"TestOptimRenewed",
|
| 2188 |
+
"test_mixed_device_dtype",
|
| 2189 |
+
active_if=TEST_WITH_TORCHDYNAMO,
|
| 2190 |
+
),
|
| 2191 |
+
DecorateInfo(
|
| 2192 |
+
skipIfTorchDynamo(
|
| 2193 |
+
"This test uses mocks, which dynamo does not support"
|
| 2194 |
+
),
|
| 2195 |
+
"TestOptimRenewed",
|
| 2196 |
+
"test_defaults_changed_to_foreach",
|
| 2197 |
+
),
|
| 2198 |
+
),
|
| 2199 |
+
),
|
| 2200 |
+
OptimizerInfo(
|
| 2201 |
+
SparseAdam,
|
| 2202 |
+
optim_inputs_func=optim_inputs_func_sparseadam,
|
| 2203 |
+
optim_error_inputs_func=optim_error_inputs_func_sparseadam,
|
| 2204 |
+
supported_impls=(),
|
| 2205 |
+
only_supports_sparse_grads=True,
|
| 2206 |
+
metadata_for_sparse=({"lr": 4e-2}, []),
|
| 2207 |
+
supports_complex=False, # Missing complex support, see #118153
|
| 2208 |
+
skips=(
|
| 2209 |
+
DecorateInfo(
|
| 2210 |
+
skipIfMPS, # SparseAdam does not support MPS
|
| 2211 |
+
"TestOptimRenewed",
|
| 2212 |
+
device_type="mps",
|
| 2213 |
+
),
|
| 2214 |
+
DecorateInfo(
|
| 2215 |
+
skipIfXpu(msg="SparseAdam is not yet supported on the XPU stack"),
|
| 2216 |
+
),
|
| 2217 |
+
DecorateInfo(
|
| 2218 |
+
skipIfTorchDynamo("cannot call to_sparse on p.grad, see #117184"),
|
| 2219 |
+
"TestOptimRenewed",
|
| 2220 |
+
"test_param_groups_lr",
|
| 2221 |
+
),
|
| 2222 |
+
DecorateInfo(
|
| 2223 |
+
skipIfTorchDynamo("cannot call to_sparse on p.grad, see #117184"),
|
| 2224 |
+
"TestOptimRenewed",
|
| 2225 |
+
"test_tensor_lr",
|
| 2226 |
+
),
|
| 2227 |
+
DecorateInfo(
|
| 2228 |
+
unittest.skip(
|
| 2229 |
+
"SparseAdam does not support dense gradients, see #116507"
|
| 2230 |
+
),
|
| 2231 |
+
"TestOptimRenewed",
|
| 2232 |
+
"test_can_load_older_state_dict",
|
| 2233 |
+
),
|
| 2234 |
+
DecorateInfo(
|
| 2235 |
+
skipIfTorchDynamo("cannot call to_sparse on p.grad, see #117184"),
|
| 2236 |
+
"TestOptimRenewed",
|
| 2237 |
+
"test_load_nontensor_step",
|
| 2238 |
+
),
|
| 2239 |
+
DecorateInfo(
|
| 2240 |
+
skipIfTorchDynamo("cannot call to_sparse on p.grad, see #117184"),
|
| 2241 |
+
"TestOptimRenewed",
|
| 2242 |
+
"test_forloop_goes_right_direction",
|
| 2243 |
+
),
|
| 2244 |
+
DecorateInfo(
|
| 2245 |
+
skipIfTorchDynamo("cannot call to_sparse on p.grad, see #117184"),
|
| 2246 |
+
"TestOptimRenewed",
|
| 2247 |
+
"test_forloop_goes_right_direction_multigpu",
|
| 2248 |
+
),
|
| 2249 |
+
DecorateInfo(
|
| 2250 |
+
skipIfTorchDynamo("cannot call to_sparse on p.grad, see #117184"),
|
| 2251 |
+
"TestOptimRenewed",
|
| 2252 |
+
"test_param_group_with_lrscheduler_goes_right_direction",
|
| 2253 |
+
),
|
| 2254 |
+
DecorateInfo(
|
| 2255 |
+
skipIfTorchDynamo("cannot call to_sparse on p.grad, see #117184"),
|
| 2256 |
+
"TestOptimRenewed",
|
| 2257 |
+
"test_state_dict_with_cuda_params",
|
| 2258 |
+
),
|
| 2259 |
+
DecorateInfo(
|
| 2260 |
+
skipIfTorchDynamo("cannot call to_sparse on p.grad, see #117184"),
|
| 2261 |
+
"TestOptimRenewed",
|
| 2262 |
+
"test_deepcopy_copies_all_public_attrs",
|
| 2263 |
+
),
|
| 2264 |
+
),
|
| 2265 |
+
),
|
| 2266 |
+
]
|
| 2267 |
+
|
| 2268 |
+
|
| 2269 |
+
class TensorTracker:
|
| 2270 |
+
"""
|
| 2271 |
+
A utility to track tensor clones in a list, with the expectation of popping them later (in
|
| 2272 |
+
order) to make fair comparisons between two multi-step computation. The intended use case is
|
| 2273 |
+
usually when comparing two supposed equal computations, such as an optimizer step that each
|
| 2274 |
+
individually consists of multiple steps, where numerical deviation could multiply.
|
| 2275 |
+
|
| 2276 |
+
The goal is to be able to compare and align numbers at every milestone so as to minimize
|
| 2277 |
+
numerical discrepancies, and so when the test fails, it is likely a real problem.
|
| 2278 |
+
"""
|
| 2279 |
+
|
| 2280 |
+
def __init__(self, assert_eq_kwargs=None):
|
| 2281 |
+
if assert_eq_kwargs is None:
|
| 2282 |
+
assert_eq_kwargs = {}
|
| 2283 |
+
self.assert_eq_kwargs = assert_eq_kwargs
|
| 2284 |
+
self.tensors = []
|
| 2285 |
+
|
| 2286 |
+
def add(self, tensor):
|
| 2287 |
+
"""
|
| 2288 |
+
Add a detach().clone()'d version of the tensor
|
| 2289 |
+
"""
|
| 2290 |
+
self.tensors.append(tensor.detach().clone())
|
| 2291 |
+
|
| 2292 |
+
# pops from beginning, like a queue and not a stack!
|
| 2293 |
+
def pop_check_set(self, tensor_to_set, testcase):
|
| 2294 |
+
"""
|
| 2295 |
+
Pop the first element in the tensor tracker, assert equality between the popped tensor and
|
| 2296 |
+
the input tensor, and then set the input tensor to have the same values as the popped tensor
|
| 2297 |
+
(with copy_).
|
| 2298 |
+
"""
|
| 2299 |
+
testcase.assertGreater(len(self.tensors), 0, "no tensors to pop")
|
| 2300 |
+
ref = self.tensors.pop(0)
|
| 2301 |
+
|
| 2302 |
+
testcase.assertTrue(isinstance(ref, Tensor), f"{type(ref)=}")
|
| 2303 |
+
testcase.assertEqual(tensor_to_set, ref, **self.assert_eq_kwargs)
|
| 2304 |
+
|
| 2305 |
+
with torch.no_grad():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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Owner(s): ["module: unknown"]
|
| 2 |
+
|
| 3 |
+
from typing import Any
|
| 4 |
+
from torch.ao.pruning import BaseSparsifier
|
| 5 |
+
import torch
|
| 6 |
+
import torch.nn.functional as F
|
| 7 |
+
from torch import nn
|
| 8 |
+
|
| 9 |
+
class ImplementedSparsifier(BaseSparsifier):
|
| 10 |
+
def __init__(self, **kwargs: dict[str, Any]) -> None:
|
| 11 |
+
super().__init__(defaults=kwargs)
|
| 12 |
+
|
| 13 |
+
def update_mask(self, module: nn.Module, tensor_name: str, **kwargs: dict[str, Any]) -> None:
|
| 14 |
+
module.parametrizations.weight[0].mask[0] = 0 # type: ignore[index, union-attr]
|
| 15 |
+
linear_state = self.state['linear1.weight']
|
| 16 |
+
linear_state['step_count'] = linear_state.get('step_count', 0) + 1
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class MockSparseLinear(nn.Linear):
|
| 20 |
+
"""
|
| 21 |
+
This class is a MockSparseLinear class to check convert functionality.
|
| 22 |
+
It is the same as a normal Linear layer, except with a different type, as
|
| 23 |
+
well as an additional from_dense method.
|
| 24 |
+
"""
|
| 25 |
+
@classmethod
|
| 26 |
+
def from_dense(cls, mod: nn.Linear) -> 'MockSparseLinear':
|
| 27 |
+
"""
|
| 28 |
+
"""
|
| 29 |
+
linear = cls(mod.in_features,
|
| 30 |
+
mod.out_features)
|
| 31 |
+
return linear
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def rows_are_subset(subset_tensor: torch.Tensor, superset_tensor: torch.Tensor) -> bool:
|
| 35 |
+
"""
|
| 36 |
+
Checks to see if all rows in subset tensor are present in the superset tensor
|
| 37 |
+
"""
|
| 38 |
+
i = 0
|
| 39 |
+
for row in subset_tensor:
|
| 40 |
+
while i < len(superset_tensor):
|
| 41 |
+
if not torch.equal(row, superset_tensor[i]):
|
| 42 |
+
i += 1
|
| 43 |
+
else:
|
| 44 |
+
break
|
| 45 |
+
else:
|
| 46 |
+
return False
|
| 47 |
+
return True
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class SimpleLinear(nn.Module):
|
| 51 |
+
r"""Model with only Linear layers without biases, some wrapped in a Sequential,
|
| 52 |
+
some following the Sequential. Used to test basic pruned Linear-Linear fusion."""
|
| 53 |
+
|
| 54 |
+
def __init__(self) -> None:
|
| 55 |
+
super().__init__()
|
| 56 |
+
self.seq = nn.Sequential(
|
| 57 |
+
nn.Linear(7, 5, bias=False),
|
| 58 |
+
nn.Linear(5, 6, bias=False),
|
| 59 |
+
nn.Linear(6, 4, bias=False),
|
| 60 |
+
)
|
| 61 |
+
self.linear1 = nn.Linear(4, 4, bias=False)
|
| 62 |
+
self.linear2 = nn.Linear(4, 10, bias=False)
|
| 63 |
+
|
| 64 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 65 |
+
x = self.seq(x)
|
| 66 |
+
x = self.linear1(x)
|
| 67 |
+
x = self.linear2(x)
|
| 68 |
+
return x
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
class LinearBias(nn.Module):
|
| 72 |
+
r"""Model with only Linear layers, alternating layers with biases,
|
| 73 |
+
wrapped in a Sequential. Used to test pruned Linear-Bias-Linear fusion."""
|
| 74 |
+
|
| 75 |
+
def __init__(self) -> None:
|
| 76 |
+
super().__init__()
|
| 77 |
+
self.seq = nn.Sequential(
|
| 78 |
+
nn.Linear(7, 5, bias=True),
|
| 79 |
+
nn.Linear(5, 6, bias=False),
|
| 80 |
+
nn.Linear(6, 3, bias=True),
|
| 81 |
+
nn.Linear(3, 3, bias=True),
|
| 82 |
+
nn.Linear(3, 10, bias=False),
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 86 |
+
x = self.seq(x)
|
| 87 |
+
return x
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
class LinearActivation(nn.Module):
|
| 91 |
+
r"""Model with only Linear layers, some with bias, some in a Sequential and some following.
|
| 92 |
+
Activation functions modules in between each Linear in the Sequential, and each outside layer.
|
| 93 |
+
Used to test pruned Linear(Bias)-Activation-Linear fusion."""
|
| 94 |
+
|
| 95 |
+
def __init__(self) -> None:
|
| 96 |
+
super().__init__()
|
| 97 |
+
self.seq = nn.Sequential(
|
| 98 |
+
nn.Linear(7, 5, bias=True),
|
| 99 |
+
nn.ReLU(),
|
| 100 |
+
nn.Linear(5, 6, bias=False),
|
| 101 |
+
nn.Tanh(),
|
| 102 |
+
nn.Linear(6, 4, bias=True),
|
| 103 |
+
)
|
| 104 |
+
self.linear1 = nn.Linear(4, 3, bias=True)
|
| 105 |
+
self.act1 = nn.ReLU()
|
| 106 |
+
self.linear2 = nn.Linear(3, 10, bias=False)
|
| 107 |
+
self.act2 = nn.Tanh()
|
| 108 |
+
|
| 109 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 110 |
+
x = self.seq(x)
|
| 111 |
+
x = self.linear1(x)
|
| 112 |
+
x = self.act1(x)
|
| 113 |
+
x = self.linear2(x)
|
| 114 |
+
x = self.act2(x)
|
| 115 |
+
return x
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
class LinearActivationFunctional(nn.Module):
|
| 119 |
+
r"""Model with only Linear layers, some with bias, some in a Sequential and some following.
|
| 120 |
+
Activation functions modules in between each Linear in the Sequential, and functional
|
| 121 |
+
activationals are called in between each outside layer.
|
| 122 |
+
Used to test pruned Linear(Bias)-Activation-Linear fusion."""
|
| 123 |
+
|
| 124 |
+
def __init__(self) -> None:
|
| 125 |
+
super().__init__()
|
| 126 |
+
self.seq = nn.Sequential(
|
| 127 |
+
nn.Linear(7, 5, bias=True),
|
| 128 |
+
nn.ReLU(),
|
| 129 |
+
nn.Linear(5, 6, bias=False),
|
| 130 |
+
nn.ReLU(),
|
| 131 |
+
nn.Linear(6, 4, bias=True),
|
| 132 |
+
)
|
| 133 |
+
self.linear1 = nn.Linear(4, 3, bias=True)
|
| 134 |
+
self.linear2 = nn.Linear(3, 8, bias=False)
|
| 135 |
+
self.linear3 = nn.Linear(8, 10, bias=False)
|
| 136 |
+
self.act1 = nn.ReLU()
|
| 137 |
+
|
| 138 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 139 |
+
x = self.seq(x)
|
| 140 |
+
x = self.linear1(x)
|
| 141 |
+
x = F.relu(x)
|
| 142 |
+
x = self.linear2(x)
|
| 143 |
+
x = F.relu(x)
|
| 144 |
+
x = self.linear3(x)
|
| 145 |
+
x = F.relu(x)
|
| 146 |
+
return x
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
class SimpleConv2d(nn.Module):
|
| 150 |
+
r"""Model with only Conv2d layers, all without bias, some in a Sequential and some following.
|
| 151 |
+
Used to test pruned Conv2d-Conv2d fusion."""
|
| 152 |
+
|
| 153 |
+
def __init__(self) -> None:
|
| 154 |
+
super().__init__()
|
| 155 |
+
self.seq = nn.Sequential(
|
| 156 |
+
nn.Conv2d(1, 32, 3, 1, bias=False),
|
| 157 |
+
nn.Conv2d(32, 64, 3, 1, bias=False),
|
| 158 |
+
)
|
| 159 |
+
self.conv2d1 = nn.Conv2d(64, 48, 3, 1, bias=False)
|
| 160 |
+
self.conv2d2 = nn.Conv2d(48, 52, 3, 1, bias=False)
|
| 161 |
+
|
| 162 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 163 |
+
x = self.seq(x)
|
| 164 |
+
x = self.conv2d1(x)
|
| 165 |
+
x = self.conv2d2(x)
|
| 166 |
+
return x
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
class Conv2dBias(nn.Module):
|
| 170 |
+
r"""Model with only Conv2d layers, some with bias, some in a Sequential and some outside.
|
| 171 |
+
Used to test pruned Conv2d-Bias-Conv2d fusion."""
|
| 172 |
+
|
| 173 |
+
def __init__(self) -> None:
|
| 174 |
+
super().__init__()
|
| 175 |
+
self.seq = nn.Sequential(
|
| 176 |
+
nn.Conv2d(1, 32, 3, 1, bias=True),
|
| 177 |
+
nn.Conv2d(32, 32, 3, 1, bias=True),
|
| 178 |
+
nn.Conv2d(32, 64, 3, 1, bias=False),
|
| 179 |
+
)
|
| 180 |
+
self.conv2d1 = nn.Conv2d(64, 48, 3, 1, bias=True)
|
| 181 |
+
self.conv2d2 = nn.Conv2d(48, 52, 3, 1, bias=False)
|
| 182 |
+
|
| 183 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 184 |
+
x = self.seq(x)
|
| 185 |
+
x = self.conv2d1(x)
|
| 186 |
+
x = self.conv2d2(x)
|
| 187 |
+
return x
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
class Conv2dActivation(nn.Module):
|
| 191 |
+
r"""Model with only Conv2d layers, some with bias, some in a Sequential and some following.
|
| 192 |
+
Activation function modules in between each Sequential layer, functional activations called
|
| 193 |
+
in-between each outside layer.
|
| 194 |
+
Used to test pruned Conv2d-Bias-Activation-Conv2d fusion."""
|
| 195 |
+
|
| 196 |
+
def __init__(self) -> None:
|
| 197 |
+
super().__init__()
|
| 198 |
+
self.seq = nn.Sequential(
|
| 199 |
+
nn.Conv2d(1, 32, 3, 1, bias=True),
|
| 200 |
+
nn.ReLU(),
|
| 201 |
+
nn.Conv2d(32, 64, 3, 1, bias=True),
|
| 202 |
+
nn.Tanh(),
|
| 203 |
+
nn.Conv2d(64, 64, 3, 1, bias=False),
|
| 204 |
+
nn.ReLU(),
|
| 205 |
+
)
|
| 206 |
+
self.conv2d1 = nn.Conv2d(64, 48, 3, 1, bias=False)
|
| 207 |
+
self.conv2d2 = nn.Conv2d(48, 52, 3, 1, bias=True)
|
| 208 |
+
|
| 209 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 210 |
+
x = self.seq(x)
|
| 211 |
+
x = self.conv2d1(x)
|
| 212 |
+
x = F.relu(x)
|
| 213 |
+
x = self.conv2d2(x)
|
| 214 |
+
x = F.hardtanh(x)
|
| 215 |
+
return x
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
class Conv2dPadBias(nn.Module):
|
| 219 |
+
r"""Model with only Conv2d layers, all with bias and some with padding > 0,
|
| 220 |
+
some in a Sequential and some following. Activation function modules in between each layer.
|
| 221 |
+
Used to test that bias is propagated correctly in the special case of
|
| 222 |
+
pruned Conv2d-Bias-(Activation)Conv2d fusion, when the second Conv2d layer has padding > 0."""
|
| 223 |
+
|
| 224 |
+
def __init__(self) -> None:
|
| 225 |
+
super().__init__()
|
| 226 |
+
self.seq = nn.Sequential(
|
| 227 |
+
nn.Conv2d(1, 32, 3, 1, padding=1, bias=True),
|
| 228 |
+
nn.ReLU(),
|
| 229 |
+
nn.Conv2d(32, 32, 3, 1, bias=False),
|
| 230 |
+
nn.ReLU(),
|
| 231 |
+
nn.Conv2d(32, 32, 3, 1, padding=1, bias=True),
|
| 232 |
+
nn.ReLU(),
|
| 233 |
+
nn.Conv2d(32, 32, 3, 1, padding=1, bias=True),
|
| 234 |
+
nn.ReLU(),
|
| 235 |
+
nn.Conv2d(32, 64, 3, 1, bias=True),
|
| 236 |
+
nn.Tanh(),
|
| 237 |
+
)
|
| 238 |
+
self.conv2d1 = nn.Conv2d(64, 48, 3, 1, padding=1, bias=True)
|
| 239 |
+
self.act1 = nn.ReLU()
|
| 240 |
+
self.conv2d2 = nn.Conv2d(48, 52, 3, 1, padding=1, bias=True)
|
| 241 |
+
self.act2 = nn.Tanh()
|
| 242 |
+
|
| 243 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 244 |
+
x = self.seq(x)
|
| 245 |
+
x = self.conv2d1(x)
|
| 246 |
+
x = self.act1(x)
|
| 247 |
+
x = self.conv2d2(x)
|
| 248 |
+
x = self.act2(x)
|
| 249 |
+
return x
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
class Conv2dPool(nn.Module):
|
| 253 |
+
r"""Model with only Conv2d layers, all with bias, some in a Sequential and some following.
|
| 254 |
+
Activation function modules in between each layer, Pool2d modules in between each layer.
|
| 255 |
+
Used to test pruned Conv2d-Pool2d-Conv2d fusion."""
|
| 256 |
+
|
| 257 |
+
def __init__(self) -> None:
|
| 258 |
+
super().__init__()
|
| 259 |
+
self.seq = nn.Sequential(
|
| 260 |
+
nn.Conv2d(1, 32, kernel_size=3, padding=1, bias=True),
|
| 261 |
+
nn.MaxPool2d(kernel_size=2, stride=2, padding=1),
|
| 262 |
+
nn.ReLU(),
|
| 263 |
+
nn.Conv2d(32, 64, kernel_size=3, padding=1, bias=True),
|
| 264 |
+
nn.Tanh(),
|
| 265 |
+
nn.AvgPool2d(kernel_size=2, stride=2, padding=1),
|
| 266 |
+
)
|
| 267 |
+
self.conv2d1 = nn.Conv2d(64, 48, kernel_size=3, padding=1, bias=True)
|
| 268 |
+
self.maxpool = nn.MaxPool2d(kernel_size=2, stride=2, padding=1)
|
| 269 |
+
self.af1 = nn.ReLU()
|
| 270 |
+
self.conv2d2 = nn.Conv2d(48, 52, kernel_size=3, padding=1, bias=True)
|
| 271 |
+
self.conv2d3 = nn.Conv2d(52, 52, kernel_size=3, padding=1, bias=True)
|
| 272 |
+
|
| 273 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 274 |
+
x = self.seq(x)
|
| 275 |
+
x = self.conv2d1(x)
|
| 276 |
+
x = self.maxpool(x)
|
| 277 |
+
x = self.af1(x)
|
| 278 |
+
x = self.conv2d2(x)
|
| 279 |
+
x = F.avg_pool2d(x, kernel_size=2, stride=2, padding=1)
|
| 280 |
+
x = F.relu(x)
|
| 281 |
+
x = self.conv2d3(x)
|
| 282 |
+
return x
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
class Conv2dPoolFlattenFunctional(nn.Module):
|
| 286 |
+
r"""Model with Conv2d layers, all with bias, some in a Sequential and some following, and then a Pool2d
|
| 287 |
+
and a functional Flatten followed by a Linear layer.
|
| 288 |
+
Activation functions and Pool2ds in between each layer also.
|
| 289 |
+
Used to test pruned Conv2d-Pool2d-Flatten-Linear fusion."""
|
| 290 |
+
|
| 291 |
+
def __init__(self) -> None:
|
| 292 |
+
super().__init__()
|
| 293 |
+
self.seq = nn.Sequential(
|
| 294 |
+
nn.Conv2d(1, 3, kernel_size=3, padding=1, bias=True),
|
| 295 |
+
nn.MaxPool2d(kernel_size=2, stride=2, padding=1),
|
| 296 |
+
nn.ReLU(),
|
| 297 |
+
nn.Conv2d(3, 5, kernel_size=3, padding=1, bias=True),
|
| 298 |
+
nn.Tanh(),
|
| 299 |
+
nn.AvgPool2d(kernel_size=2, stride=2, padding=1),
|
| 300 |
+
)
|
| 301 |
+
self.conv2d1 = nn.Conv2d(5, 7, kernel_size=3, padding=1, bias=True)
|
| 302 |
+
self.af1 = nn.ReLU()
|
| 303 |
+
self.conv2d2 = nn.Conv2d(7, 11, kernel_size=3, padding=1, bias=True)
|
| 304 |
+
self.avg_pool = nn.AdaptiveAvgPool2d((1, 1))
|
| 305 |
+
self.fc = nn.Linear(11, 13, bias=True)
|
| 306 |
+
|
| 307 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 308 |
+
x = self.seq(x)
|
| 309 |
+
x = self.conv2d1(x)
|
| 310 |
+
x = F.max_pool2d(x, kernel_size=2, stride=2, padding=1)
|
| 311 |
+
x = self.af1(x)
|
| 312 |
+
x = self.conv2d2(x)
|
| 313 |
+
x = self.avg_pool(x)
|
| 314 |
+
x = torch.flatten(x, 1) # test functional flatten
|
| 315 |
+
x = self.fc(x)
|
| 316 |
+
return x
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
class Conv2dPoolFlatten(nn.Module):
|
| 320 |
+
r"""Model with Conv2d layers, all with bias, some in a Sequential and some following, and then a Pool2d
|
| 321 |
+
and a Flatten module followed by a Linear layer.
|
| 322 |
+
Activation functions and Pool2ds in between each layer also.
|
| 323 |
+
Used to test pruned Conv2d-Pool2d-Flatten-Linear fusion."""
|
| 324 |
+
|
| 325 |
+
def __init__(self) -> None:
|
| 326 |
+
super().__init__()
|
| 327 |
+
self.seq = nn.Sequential(
|
| 328 |
+
nn.Conv2d(1, 3, kernel_size=3, padding=1, bias=True),
|
| 329 |
+
nn.MaxPool2d(kernel_size=2, stride=2, padding=1),
|
| 330 |
+
nn.ReLU(),
|
| 331 |
+
nn.Conv2d(3, 5, kernel_size=3, padding=1, bias=True),
|
| 332 |
+
nn.Tanh(),
|
| 333 |
+
nn.AvgPool2d(kernel_size=2, stride=2, padding=1),
|
| 334 |
+
)
|
| 335 |
+
self.conv2d1 = nn.Conv2d(5, 7, kernel_size=3, padding=1, bias=True)
|
| 336 |
+
self.af1 = nn.ReLU()
|
| 337 |
+
self.conv2d2 = nn.Conv2d(7, 11, kernel_size=3, padding=1, bias=True)
|
| 338 |
+
self.avg_pool = nn.AdaptiveAvgPool2d((2, 2))
|
| 339 |
+
self.flatten = nn.Flatten()
|
| 340 |
+
self.fc = nn.Linear(44, 13, bias=True)
|
| 341 |
+
|
| 342 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 343 |
+
x = self.seq(x)
|
| 344 |
+
x = self.conv2d1(x)
|
| 345 |
+
x = F.max_pool2d(x, kernel_size=2, stride=2, padding=1)
|
| 346 |
+
x = self.af1(x)
|
| 347 |
+
x = self.conv2d2(x)
|
| 348 |
+
x = self.avg_pool(x)
|
| 349 |
+
x = self.flatten(x)
|
| 350 |
+
x = self.fc(x)
|
| 351 |
+
return x
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
class LSTMLinearModel(nn.Module):
|
| 355 |
+
"""Container module with an encoder, a recurrent module, and a linear."""
|
| 356 |
+
|
| 357 |
+
def __init__(
|
| 358 |
+
self, input_dim: int, hidden_dim: int, output_dim: int, num_layers: int
|
| 359 |
+
) -> None:
|
| 360 |
+
super().__init__()
|
| 361 |
+
self.lstm = nn.LSTM(input_dim, hidden_dim, num_layers)
|
| 362 |
+
self.linear = nn.Linear(hidden_dim, output_dim)
|
| 363 |
+
|
| 364 |
+
def forward(self, input: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
|
| 365 |
+
output, _hidden = self.lstm(input)
|
| 366 |
+
decoded = self.linear(output)
|
| 367 |
+
return decoded, output
|
| 368 |
+
|
| 369 |
+
|
| 370 |
+
class LSTMLayerNormLinearModel(nn.Module):
|
| 371 |
+
"""Container module with an LSTM, a LayerNorm, and a linear."""
|
| 372 |
+
|
| 373 |
+
def __init__(
|
| 374 |
+
self, input_dim: int, hidden_dim: int, output_dim: int, num_layers: int
|
| 375 |
+
) -> None:
|
| 376 |
+
super().__init__()
|
| 377 |
+
self.lstm = nn.LSTM(input_dim, hidden_dim, num_layers)
|
| 378 |
+
self.norm = nn.LayerNorm(hidden_dim)
|
| 379 |
+
self.linear = nn.Linear(hidden_dim, output_dim)
|
| 380 |
+
|
| 381 |
+
def forward(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
|
| 382 |
+
x, state = self.lstm(x)
|
| 383 |
+
x = self.norm(x)
|
| 384 |
+
x = self.linear(x)
|
| 385 |
+
return x, state
|
pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/common_quantization.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/common_quantized.py
ADDED
|
@@ -0,0 +1,588 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: ignore-errors
|
| 2 |
+
|
| 3 |
+
r"""Importing this file includes common utility methods for checking quantized
|
| 4 |
+
tensors and modules.
|
| 5 |
+
"""
|
| 6 |
+
import numpy as np
|
| 7 |
+
import torch
|
| 8 |
+
from torch import Tensor
|
| 9 |
+
from contextlib import contextmanager
|
| 10 |
+
from torch.testing._internal.common_utils import TEST_WITH_TSAN, IS_PPC, IS_MACOS, IS_WINDOWS
|
| 11 |
+
|
| 12 |
+
supported_qengines = torch.backends.quantized.supported_engines
|
| 13 |
+
# Note: We currently do not run QNNPACK tests on WINDOWS and MACOS as it is flaky. Issue #29326
|
| 14 |
+
# QNNPACK is not supported on PPC
|
| 15 |
+
if 'qnnpack' in supported_qengines and any([IS_PPC, TEST_WITH_TSAN, IS_MACOS, IS_WINDOWS]):
|
| 16 |
+
supported_qengines.remove('qnnpack')
|
| 17 |
+
|
| 18 |
+
def _conv_output_shape(input_size, kernel_size, padding, stride, dilation,
|
| 19 |
+
output_padding=0):
|
| 20 |
+
"""Computes the output shape given convolution parameters."""
|
| 21 |
+
return np.floor((input_size + 2 * padding - kernel_size - (kernel_size - 1)
|
| 22 |
+
* (dilation - 1)) / stride) + 2 * output_padding + 1
|
| 23 |
+
|
| 24 |
+
# Quantization references
|
| 25 |
+
def _quantize(x, scale, zero_point, qmin=None, qmax=None, dtype=np.uint8):
|
| 26 |
+
"""Quantizes a numpy array."""
|
| 27 |
+
if qmin is None:
|
| 28 |
+
qmin = np.iinfo(dtype).min
|
| 29 |
+
if qmax is None:
|
| 30 |
+
qmax = np.iinfo(dtype).max
|
| 31 |
+
qx = np.round(x / scale + zero_point).astype(np.int64)
|
| 32 |
+
qx = np.clip(qx, qmin, qmax)
|
| 33 |
+
qx = qx.astype(dtype)
|
| 34 |
+
return qx
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def _dequantize(qx, scale, zero_point):
|
| 38 |
+
"""Dequantizes a numpy array."""
|
| 39 |
+
x = (qx.astype(float) - zero_point) * scale
|
| 40 |
+
return x
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def _requantize(x, multiplier, zero_point, qmin=0, qmax=255, qtype=np.uint8):
|
| 44 |
+
"""Requantizes a numpy array, i.e., intermediate int32 or int16 values are
|
| 45 |
+
converted back to given type"""
|
| 46 |
+
qx = (x * multiplier).round() + zero_point
|
| 47 |
+
qx = np.clip(qx, qmin, qmax).astype(qtype)
|
| 48 |
+
return qx
|
| 49 |
+
|
| 50 |
+
def _calculate_dynamic_qparams(X, dtype, reduce_range=False, qscheme=torch.per_tensor_affine):
|
| 51 |
+
"""Calculate the dynamic quantization parameters (scale, zero_point)
|
| 52 |
+
according to the min and max element of the tensor"""
|
| 53 |
+
assert qscheme in (torch.per_tensor_affine, torch.per_tensor_symmetric)
|
| 54 |
+
if qscheme == torch.per_tensor_symmetric:
|
| 55 |
+
assert dtype == torch.qint8
|
| 56 |
+
if isinstance(X, torch.Tensor):
|
| 57 |
+
X = X.numpy()
|
| 58 |
+
if dtype == torch.qint8:
|
| 59 |
+
if reduce_range:
|
| 60 |
+
qmin, qmax = -64, 63
|
| 61 |
+
else:
|
| 62 |
+
qmin, qmax = -128, 127
|
| 63 |
+
else: # dtype == torch.quint8
|
| 64 |
+
if reduce_range:
|
| 65 |
+
qmin, qmax = 0, 127
|
| 66 |
+
else:
|
| 67 |
+
qmin, qmax = 0, 255
|
| 68 |
+
min_val = X.min()
|
| 69 |
+
max_val = X.max()
|
| 70 |
+
is_symmetric = (qscheme == torch.per_tensor_symmetric)
|
| 71 |
+
if min_val == max_val:
|
| 72 |
+
scale = 1.0
|
| 73 |
+
zero_point = 0
|
| 74 |
+
else:
|
| 75 |
+
if is_symmetric:
|
| 76 |
+
max_val = max(max_val, -min_val)
|
| 77 |
+
min_val = -max_val
|
| 78 |
+
scale = (max_val - min_val) / (qmax - qmin)
|
| 79 |
+
scale = max(scale, np.finfo(np.float32).eps)
|
| 80 |
+
zero_point = 0
|
| 81 |
+
else:
|
| 82 |
+
max_val = max(max_val, 0.0)
|
| 83 |
+
min_val = min(min_val, 0.0)
|
| 84 |
+
scale = (max_val - min_val) / (qmax - qmin)
|
| 85 |
+
scale = max(scale, np.finfo(np.float32).eps)
|
| 86 |
+
zero_point = qmin - round(min_val / scale)
|
| 87 |
+
zero_point = max(qmin, zero_point)
|
| 88 |
+
zero_point = min(qmax, zero_point)
|
| 89 |
+
return [float(scale), int(zero_point)]
|
| 90 |
+
|
| 91 |
+
def _calculate_dynamic_per_channel_qparams(X, dtype):
|
| 92 |
+
"""Calculate the dynamic quantization parameters (scale, zero_point)
|
| 93 |
+
according to the min and max element of the tensor"""
|
| 94 |
+
if isinstance(X, torch.Tensor):
|
| 95 |
+
X = X.numpy()
|
| 96 |
+
qmin, qmax = torch.iinfo(dtype).min, torch.iinfo(dtype).max
|
| 97 |
+
n_levels = qmax - qmin
|
| 98 |
+
scale = np.zeros(X.shape[0], dtype=np.float64)
|
| 99 |
+
zero_point = np.zeros(X.shape[0], dtype=np.int64)
|
| 100 |
+
for i in range(zero_point.shape[0]):
|
| 101 |
+
min_val = X.min()
|
| 102 |
+
max_val = X.max()
|
| 103 |
+
if min_val == max_val:
|
| 104 |
+
scale[i] = 1.0
|
| 105 |
+
zero_point[i] = 0
|
| 106 |
+
else:
|
| 107 |
+
max_val = max(max_val, 0.0)
|
| 108 |
+
min_val = min(min_val, 0.0)
|
| 109 |
+
scale[i] = (max_val - min_val) / n_levels
|
| 110 |
+
scale[i] = max(scale[i], np.finfo(np.float32).eps)
|
| 111 |
+
zero_point[i] = qmin - round(min_val / scale[i])
|
| 112 |
+
zero_point[i] = max(qmin, zero_point[i])
|
| 113 |
+
zero_point[i] = min(qmax, zero_point[i])
|
| 114 |
+
|
| 115 |
+
return scale, zero_point
|
| 116 |
+
|
| 117 |
+
def _snr(x, x_hat):
|
| 118 |
+
"""Calculates the signal to noise ratio and returns the signal and noise
|
| 119 |
+
power, as well as the SNR in dB.
|
| 120 |
+
If the input is a list/tuple this function is called recursively on each
|
| 121 |
+
element. The result will have the same nested structure as the inputs.
|
| 122 |
+
|
| 123 |
+
Args:
|
| 124 |
+
x, x_hat: Either a tensor or a nested list/tuple of tensors.
|
| 125 |
+
Returns:
|
| 126 |
+
signal, noise, SNR(in dB): Either floats or a nested list of floats
|
| 127 |
+
"""
|
| 128 |
+
if isinstance(x, (list, tuple)):
|
| 129 |
+
assert len(x) == len(x_hat)
|
| 130 |
+
res = [_snr(x[idx], x_hat[idx]) for idx in range(len(x))]
|
| 131 |
+
return res
|
| 132 |
+
if x_hat.is_quantized:
|
| 133 |
+
x_hat = x_hat.dequantize()
|
| 134 |
+
if x.is_quantized:
|
| 135 |
+
x = x.dequantize()
|
| 136 |
+
noise = (x - x_hat).norm()
|
| 137 |
+
if noise == 0:
|
| 138 |
+
return 0.0, float('inf'), float('inf')
|
| 139 |
+
signal = x.norm()
|
| 140 |
+
snr = signal / noise
|
| 141 |
+
snr_db = 20 * snr.log10()
|
| 142 |
+
return signal, noise, snr_db
|
| 143 |
+
|
| 144 |
+
@contextmanager
|
| 145 |
+
def override_quantized_engine(qengine):
|
| 146 |
+
previous = torch.backends.quantized.engine
|
| 147 |
+
torch.backends.quantized.engine = qengine
|
| 148 |
+
try:
|
| 149 |
+
yield
|
| 150 |
+
finally:
|
| 151 |
+
torch.backends.quantized.engine = previous
|
| 152 |
+
|
| 153 |
+
@contextmanager
|
| 154 |
+
def override_cpu_allocator_for_qnnpack(qengine_is_qnnpack):
|
| 155 |
+
try:
|
| 156 |
+
if qengine_is_qnnpack:
|
| 157 |
+
torch._C._set_default_mobile_cpu_allocator()
|
| 158 |
+
yield
|
| 159 |
+
finally:
|
| 160 |
+
if qengine_is_qnnpack:
|
| 161 |
+
torch._C._unset_default_mobile_cpu_allocator()
|
| 162 |
+
|
| 163 |
+
# TODO: Update all quantization tests to use this decorator.
|
| 164 |
+
# Currently for some of the tests it seems to have inconsistent params
|
| 165 |
+
# for fbgemm vs qnnpack.
|
| 166 |
+
def override_qengines(qfunction):
|
| 167 |
+
def test_fn(*args, **kwargs):
|
| 168 |
+
for qengine in supported_qengines:
|
| 169 |
+
with override_quantized_engine(qengine):
|
| 170 |
+
# qfunction should not return anything.
|
| 171 |
+
qfunction(*args, **kwargs)
|
| 172 |
+
return test_fn
|
| 173 |
+
|
| 174 |
+
def qengine_is_fbgemm():
|
| 175 |
+
return torch.backends.quantized.engine == 'fbgemm'
|
| 176 |
+
def qengine_is_qnnpack():
|
| 177 |
+
return torch.backends.quantized.engine == 'qnnpack'
|
| 178 |
+
def qengine_is_onednn():
|
| 179 |
+
return torch.backends.quantized.engine == 'onednn'
|
| 180 |
+
def qengine_is_x86():
|
| 181 |
+
return torch.backends.quantized.engine == 'x86'
|
| 182 |
+
|
| 183 |
+
# Helper function used to simulate per-channel fake-quant against any axis
|
| 184 |
+
def _permute_to_axis_zero(X, axis):
|
| 185 |
+
new_axis_list = list(range(X.dim()))
|
| 186 |
+
new_axis_list[axis] = 0
|
| 187 |
+
new_axis_list[0] = axis
|
| 188 |
+
y = X.permute(tuple(new_axis_list))
|
| 189 |
+
return y, new_axis_list
|
| 190 |
+
|
| 191 |
+
# Reference method for fake quantize
|
| 192 |
+
# Note: because scale/zero_point are left as float in the actual kernel, this mimics how fake_quant works for float16/64
|
| 193 |
+
def _fake_quantize_per_channel_affine_reference(X, per_channel_scale, per_channel_zero_point, axis, quant_min, quant_max):
|
| 194 |
+
dtype = X.dtype
|
| 195 |
+
X, permute_axis_list = _permute_to_axis_zero(X.to(torch.float32), axis)
|
| 196 |
+
res = torch.zeros_like(X)
|
| 197 |
+
|
| 198 |
+
for i in range(X.size()[0]):
|
| 199 |
+
res[i] = (torch.clamp(torch.round(X[i] * (1.0 / per_channel_scale[i]) +
|
| 200 |
+
per_channel_zero_point[i]), quant_min, quant_max) - per_channel_zero_point[i]) * per_channel_scale[i]
|
| 201 |
+
|
| 202 |
+
out = res.permute(tuple(permute_axis_list))
|
| 203 |
+
return out.to(dtype)
|
| 204 |
+
|
| 205 |
+
# Reference method for the gradient of the fake quantize operator
|
| 206 |
+
# Note: because scale/zero_point are left as float in the actual kernel, this mimics how fake_quant works for float16/64
|
| 207 |
+
def _fake_quantize_per_channel_affine_grad_reference(dY, X, per_channel_scale, per_channel_zero_point, axis, quant_min, quant_max):
|
| 208 |
+
dtype = X.dtype
|
| 209 |
+
X, permute_axis_list = _permute_to_axis_zero(X.to(torch.float32), axis)
|
| 210 |
+
Xq = torch.zeros_like(X)
|
| 211 |
+
for i in range(X.size()[0]):
|
| 212 |
+
Xq[i] = torch.round(X[i] * (1.0 / per_channel_scale[i]) + per_channel_zero_point[i])
|
| 213 |
+
Xq = Xq.permute(tuple(permute_axis_list))
|
| 214 |
+
mask = (Xq >= quant_min) * (Xq <= quant_max)
|
| 215 |
+
res = torch.zeros_like(dY)
|
| 216 |
+
res[mask] = dY[mask]
|
| 217 |
+
return res.to(dtype)
|
| 218 |
+
|
| 219 |
+
def to_tensor(X, device):
|
| 220 |
+
if not isinstance(X, torch.Tensor):
|
| 221 |
+
X = torch.tensor(X)
|
| 222 |
+
else:
|
| 223 |
+
X = X.detach().clone()
|
| 224 |
+
return X.to(device=torch.device(device), dtype=torch.float32)
|
| 225 |
+
|
| 226 |
+
# copy-pasted from
|
| 227 |
+
# https://github.com/pytorch/ao/blob/bc4f51da86956275da7db0da6e420c506df97820/torchao/prototype/custom_fp_utils.py#L27C1-L142C29
|
| 228 |
+
def _n_ones(n: int) -> int:
|
| 229 |
+
return (1 << n) - 1
|
| 230 |
+
|
| 231 |
+
EBITS_F32, MBITS_F32 = 8, 23
|
| 232 |
+
F32_EXP_BIAS = _n_ones(EBITS_F32 - 1)
|
| 233 |
+
|
| 234 |
+
# copy-pasted from
|
| 235 |
+
# https://github.com/pytorch/ao/blob/bc4f51da86956275da7db0da6e420c506df97820/torchao/prototype/custom_fp_utils.py#L27C1-L142C29
|
| 236 |
+
def _f32_to_floatx_unpacked(x: Tensor, ebits: int, mbits: int) -> Tensor:
|
| 237 |
+
"""Convert FP32 numbers to sub-byte floating point numbers with the given
|
| 238 |
+
number of exponent and mantissa bits.
|
| 239 |
+
|
| 240 |
+
Input: torch.Tensor of dtype torch.float
|
| 241 |
+
Output: torch.Tensor of dtype torch.uint8, where the bit encoding is stored
|
| 242 |
+
in the least significant bits. e.g.
|
| 243 |
+
fp4: bits 0-3 empty and bits 4-7 in fp4_e2m1 encoding
|
| 244 |
+
fp6: bits 0-1 empty and bits 2-7 in fp6_e2m3 or fp6_e3m2 encoding
|
| 245 |
+
|
| 246 |
+
Note: there are no special values (NaN, inf) support in this code. Values
|
| 247 |
+
outside the representable range of Floatx after rounding are clamped to the
|
| 248 |
+
maximum Floatx magnitude (sign is preserved).
|
| 249 |
+
|
| 250 |
+
Code below is an adaptation of https://fburl.com/code/ciwofcg4
|
| 251 |
+
|
| 252 |
+
Background 1: last answer in https://stackoverflow.com/q/8981913
|
| 253 |
+
Background 2: Computer Organization and Design, RISC-V edition, Chapter 3.5
|
| 254 |
+
"""
|
| 255 |
+
assert x.dtype == torch.float
|
| 256 |
+
assert 1 + ebits + mbits <= 8
|
| 257 |
+
|
| 258 |
+
# calculate constants
|
| 259 |
+
exp_bias = _n_ones(ebits - 1)
|
| 260 |
+
max_int = _n_ones(ebits + mbits)
|
| 261 |
+
sign_mask = 1 << (ebits + mbits)
|
| 262 |
+
|
| 263 |
+
# TODO document this better
|
| 264 |
+
magic_adder = _n_ones(MBITS_F32 - mbits - 1)
|
| 265 |
+
|
| 266 |
+
# all E bits and M bits are 1s
|
| 267 |
+
max_normal = 2 ** (_n_ones(ebits) - exp_bias) * (_n_ones(mbits + 1) / (2**mbits))
|
| 268 |
+
|
| 269 |
+
# E bits = 1, M bits = 0
|
| 270 |
+
min_normal = 2 ** (1 - exp_bias)
|
| 271 |
+
|
| 272 |
+
denorm_exp = (
|
| 273 |
+
# exp bias conversion between formats
|
| 274 |
+
(F32_EXP_BIAS - exp_bias)
|
| 275 |
+
# mantissa length difference between formats
|
| 276 |
+
+ (MBITS_F32 - mbits)
|
| 277 |
+
# add one to encoded exponent for denormalized numbers
|
| 278 |
+
+ 1
|
| 279 |
+
)
|
| 280 |
+
denorm_mask_int = denorm_exp << MBITS_F32
|
| 281 |
+
|
| 282 |
+
# reinterpret int32 as float32
|
| 283 |
+
denorm_mask_float = torch.tensor(denorm_mask_int, dtype=torch.int32).view(
|
| 284 |
+
torch.float32
|
| 285 |
+
)
|
| 286 |
+
|
| 287 |
+
# save the sign
|
| 288 |
+
# Note that we have torch.uint32, but some ops like cpu bit shifts
|
| 289 |
+
# do not work on it. So, we stay in int32.
|
| 290 |
+
x = x.view(torch.int32)
|
| 291 |
+
sign = x & 0x80000000
|
| 292 |
+
|
| 293 |
+
# set everything to positive, will add sign back at the end
|
| 294 |
+
x = x ^ sign
|
| 295 |
+
|
| 296 |
+
# TODO: can the branch floating point comparisons below be done without
|
| 297 |
+
# converting to float? probably but need to verify
|
| 298 |
+
x = x.view(torch.float)
|
| 299 |
+
|
| 300 |
+
# rewrite saturate/denorm/norm branches without explicit data dependent
|
| 301 |
+
# control flow, to be more compiler friendly
|
| 302 |
+
saturate_mask = x >= max_normal
|
| 303 |
+
denormal_mask = torch.logical_and(torch.logical_not(saturate_mask), x < min_normal)
|
| 304 |
+
normal_mask = torch.logical_not(torch.logical_or(saturate_mask, denormal_mask))
|
| 305 |
+
|
| 306 |
+
#
|
| 307 |
+
# branch 1: saturate to max val - handled later in the code which combines
|
| 308 |
+
# the branches
|
| 309 |
+
#
|
| 310 |
+
|
| 311 |
+
#
|
| 312 |
+
# branch 2: to conversion to denormal as well as rounding up to normal
|
| 313 |
+
#
|
| 314 |
+
denormal_x = x + denorm_mask_float
|
| 315 |
+
denormal_x = denormal_x.view(torch.int32)
|
| 316 |
+
denormal_x -= denorm_mask_int
|
| 317 |
+
denormal_x = denormal_x.to(torch.uint8)
|
| 318 |
+
|
| 319 |
+
#
|
| 320 |
+
# branch 3: stay in normal range, adjust the exponent and round
|
| 321 |
+
#
|
| 322 |
+
normal_x = x.view(torch.int32)
|
| 323 |
+
# resulting mantissa is odd
|
| 324 |
+
mant_odd = (normal_x >> (MBITS_F32 - mbits)) & 1
|
| 325 |
+
# update exponent, rounding bias part 1
|
| 326 |
+
val_to_add = ((exp_bias - F32_EXP_BIAS) << MBITS_F32) + magic_adder
|
| 327 |
+
normal_x += val_to_add
|
| 328 |
+
# rounding bias part 2
|
| 329 |
+
normal_x += mant_odd
|
| 330 |
+
# take the bits!
|
| 331 |
+
normal_x = normal_x >> (MBITS_F32 - mbits)
|
| 332 |
+
normal_x = normal_x.to(torch.uint8)
|
| 333 |
+
|
| 334 |
+
#
|
| 335 |
+
# combine the branches
|
| 336 |
+
#
|
| 337 |
+
x = torch.full_like(x, max_int, dtype=torch.uint8)
|
| 338 |
+
x = torch.where(denormal_mask, denormal_x, x)
|
| 339 |
+
x = torch.where(normal_mask, normal_x, x)
|
| 340 |
+
|
| 341 |
+
# add sign back
|
| 342 |
+
sign_lp = sign >> (MBITS_F32 + EBITS_F32 - mbits - ebits)
|
| 343 |
+
sign_lp = sign_lp.to(torch.uint8)
|
| 344 |
+
# Right shift of a negative signed integer can fill the least significant
|
| 345 |
+
# bits with either 1s or 0s, depending on the implementation. Since PyTorch
|
| 346 |
+
# doesn't have an uint32 dtype, we mask out these bits to get just the
|
| 347 |
+
# f4 sign bit
|
| 348 |
+
sign_lp = sign_lp & sign_mask
|
| 349 |
+
x = x | sign_lp
|
| 350 |
+
|
| 351 |
+
return x.to(torch.uint8)
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
# copy-pasted from
|
| 355 |
+
# https://github.com/pytorch/ao/blob/29488018d99af7f7339f06353c6b5bbeae8a1493/torchao/prototype/custom_fp_utils.py#L147
|
| 356 |
+
def _floatx_unpacked_to_f32(x: Tensor, ebits: int, mbits: int) -> Tensor:
|
| 357 |
+
"""Convert sub-byte floating point numbers with the given number of exponent
|
| 358 |
+
and mantissa bits to FP32.
|
| 359 |
+
|
| 360 |
+
Input: torch.Tensor of dtype uint8, where the bit encoding is stored
|
| 361 |
+
in the least significant bits. e.g.
|
| 362 |
+
fp4: bits 0-3 empty and bits 4-7 in fp4_e2m1 encoding
|
| 363 |
+
fp6: bits 0-1 empty and bits 2-7 in fp6_e2m3 or fp6_e3m2 encoding
|
| 364 |
+
Output: torch.Tensor of dtype fp32 with the dequantized value
|
| 365 |
+
"""
|
| 366 |
+
assert x.dtype == torch.uint8
|
| 367 |
+
assert 1 + ebits + mbits <= 8
|
| 368 |
+
|
| 369 |
+
sign_mask = 1 << (ebits + mbits)
|
| 370 |
+
exp_bias = _n_ones(ebits - 1)
|
| 371 |
+
mantissa_mask = _n_ones(mbits)
|
| 372 |
+
|
| 373 |
+
# save the sign
|
| 374 |
+
sign_lp = x & sign_mask
|
| 375 |
+
|
| 376 |
+
# set everything to positive, will add sign back at the end
|
| 377 |
+
x_pos = x ^ sign_lp
|
| 378 |
+
|
| 379 |
+
#
|
| 380 |
+
# 1. Calculate zero mask
|
| 381 |
+
#
|
| 382 |
+
zero_mask = x_pos == 0
|
| 383 |
+
|
| 384 |
+
#
|
| 385 |
+
# 2. Calculate the denormal path mask
|
| 386 |
+
#
|
| 387 |
+
denormal_mask = torch.logical_and((x_pos > 0), ((x_pos >> mbits) == 0))
|
| 388 |
+
|
| 389 |
+
#
|
| 390 |
+
# 3. Calculate the normal path
|
| 391 |
+
#
|
| 392 |
+
|
| 393 |
+
# calculate the new exponent and shift it to bits 2:9 of the result
|
| 394 |
+
exp_biased_lp = x_pos >> mbits
|
| 395 |
+
exp_biased_f32 = exp_biased_lp - exp_bias + F32_EXP_BIAS
|
| 396 |
+
exp_biased_f32 = exp_biased_f32.to(torch.int32) << MBITS_F32
|
| 397 |
+
|
| 398 |
+
# shift the mantissa to bits 10:32 of the result
|
| 399 |
+
mantissa_lp_int32 = (x_pos & mantissa_mask).to(torch.int32)
|
| 400 |
+
mantissa_f32 = mantissa_lp_int32 << (MBITS_F32 - mbits)
|
| 401 |
+
result = exp_biased_f32 | mantissa_f32
|
| 402 |
+
|
| 403 |
+
#
|
| 404 |
+
# 4. Add the zero and denormal casts to the already casted normal path
|
| 405 |
+
#
|
| 406 |
+
result[zero_mask] = 0
|
| 407 |
+
|
| 408 |
+
denormal_exp_biased = 1 - exp_bias + F32_EXP_BIAS
|
| 409 |
+
|
| 410 |
+
# fast path.
|
| 411 |
+
# without this, performance for FP4_E2M1 is slower by 2x
|
| 412 |
+
if mbits == 1:
|
| 413 |
+
result[denormal_mask] = (denormal_exp_biased - mbits) << MBITS_F32
|
| 414 |
+
|
| 415 |
+
else:
|
| 416 |
+
# iterate over all possible values of mantissa
|
| 417 |
+
# i=0, j=1
|
| 418 |
+
# i=1, j=10,11
|
| 419 |
+
# i=2, j=100,101,110,111
|
| 420 |
+
# and so on
|
| 421 |
+
for i in range(mbits):
|
| 422 |
+
for mantissa_cmp in range(1 << i, 1 << (i + 1)):
|
| 423 |
+
# left shift mantissa until it overflows (create an implicit 1)
|
| 424 |
+
# subtract exponent by the same amount
|
| 425 |
+
left_shift = mbits - i
|
| 426 |
+
mantissa_f32 = (mantissa_cmp - (1 << i)) << (
|
| 427 |
+
left_shift + MBITS_F32 - mbits
|
| 428 |
+
)
|
| 429 |
+
exp_biased_f32 = (denormal_exp_biased - left_shift) << MBITS_F32
|
| 430 |
+
|
| 431 |
+
# we can update this in-place since the values won't overlap
|
| 432 |
+
# torch.compile() may complain unsupported operand type(s) for |: 'SymInt' and 'int'
|
| 433 |
+
# thus we use + instead of | here
|
| 434 |
+
mantissa_lp_int32[mantissa_lp_int32 == mantissa_cmp] = (
|
| 435 |
+
exp_biased_f32 + mantissa_f32
|
| 436 |
+
)
|
| 437 |
+
|
| 438 |
+
result = torch.where(denormal_mask, mantissa_lp_int32, result)
|
| 439 |
+
|
| 440 |
+
# add sign back
|
| 441 |
+
sign_f32 = sign_lp.to(torch.int32) << (MBITS_F32 - mbits + EBITS_F32 - ebits)
|
| 442 |
+
result = result | sign_f32
|
| 443 |
+
|
| 444 |
+
return result.view(torch.float)
|
| 445 |
+
|
| 446 |
+
# copied from https://github.com/drisspg/transformer_nuggets/blob/main/transformer_nuggets/mx/to_blocked.py
|
| 447 |
+
def ceil_div(a, b):
|
| 448 |
+
return (a + b - 1) // b
|
| 449 |
+
|
| 450 |
+
def to_blocked(input_matrix) -> torch.Tensor:
|
| 451 |
+
"""
|
| 452 |
+
Rearrange a large matrix by breaking it into blocks and applying the rearrangement pattern.
|
| 453 |
+
|
| 454 |
+
See:
|
| 455 |
+
https://docs.nvidia.com/cuda/cublas/index.html#d-block-scaling-factors-layout
|
| 456 |
+
|
| 457 |
+
Args:
|
| 458 |
+
input_matrix: Input tensor of shape (H, W)
|
| 459 |
+
|
| 460 |
+
Returns:
|
| 461 |
+
Rearranged tensor of shape (32*ceil_div(H,128), 16*ceil_div(W,4))
|
| 462 |
+
"""
|
| 463 |
+
rows, cols = input_matrix.shape
|
| 464 |
+
n_row_blocks = ceil_div(rows, 128)
|
| 465 |
+
n_col_blocks = ceil_div(cols, 4)
|
| 466 |
+
|
| 467 |
+
# Calculate the padded shape
|
| 468 |
+
padded_rows = n_row_blocks * 128
|
| 469 |
+
padded_cols = n_col_blocks * 4
|
| 470 |
+
|
| 471 |
+
padded = input_matrix
|
| 472 |
+
# Ideally we would use torch.nn.pad but it doesn't support float8_e8m0fnu for now
|
| 473 |
+
if (rows, cols) != (padded_rows, padded_cols):
|
| 474 |
+
padded = torch.zeros((padded_rows, padded_cols), device=input_matrix.device, dtype=input_matrix.dtype)
|
| 475 |
+
padded[:rows, :cols] = input_matrix
|
| 476 |
+
|
| 477 |
+
# Rearrange the blocks
|
| 478 |
+
blocks = padded.view(n_row_blocks, 128, n_col_blocks, 4).permute(0, 2, 1, 3)
|
| 479 |
+
rearranged = blocks.reshape(-1, 4, 32, 4).transpose(1, 2).reshape(-1, 32, 16)
|
| 480 |
+
|
| 481 |
+
return rearranged.flatten()
|
| 482 |
+
|
| 483 |
+
# This function is extracted from https://github.com/pytorch/ao/blob/v0.12.0/torchao/prototype/mx_formats/mx_tensor.py#L142
|
| 484 |
+
def to_mxfp8(
|
| 485 |
+
data_hp: torch.Tensor,
|
| 486 |
+
block_size: int = 32,
|
| 487 |
+
):
|
| 488 |
+
assert data_hp.dtype in (
|
| 489 |
+
torch.bfloat16,
|
| 490 |
+
torch.float,
|
| 491 |
+
), f"{data_hp.dtype} is not supported yet"
|
| 492 |
+
assert (
|
| 493 |
+
data_hp.shape[-1] % block_size == 0
|
| 494 |
+
), f"the last dimension of shape {data_hp.shape} must be divisible by block_size {block_size}"
|
| 495 |
+
assert data_hp.is_contiguous(), "unsupported"
|
| 496 |
+
|
| 497 |
+
orig_shape = data_hp.shape
|
| 498 |
+
data_hp = data_hp.reshape(
|
| 499 |
+
*orig_shape[:-1], orig_shape[-1] // block_size, block_size
|
| 500 |
+
)
|
| 501 |
+
|
| 502 |
+
max_abs = torch.amax(torch.abs(data_hp), -1).unsqueeze(-1)
|
| 503 |
+
|
| 504 |
+
data_hp = data_hp.to(torch.float32)
|
| 505 |
+
max_abs = max_abs.to(torch.float32)
|
| 506 |
+
|
| 507 |
+
F8E4M3_MAX = torch.finfo(torch.float8_e4m3fn).max # 448.0
|
| 508 |
+
max_pos = F8E4M3_MAX
|
| 509 |
+
|
| 510 |
+
# RCEIL
|
| 511 |
+
def _to_mx_rceil(
|
| 512 |
+
data_hp: torch.Tensor,
|
| 513 |
+
max_abs: torch.Tensor,
|
| 514 |
+
max_pos: float,
|
| 515 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 516 |
+
E8M0_EXPONENT_BIAS = 127
|
| 517 |
+
descale = max_abs / max_pos
|
| 518 |
+
exponent = torch.where(
|
| 519 |
+
torch.isnan(descale),
|
| 520 |
+
0xFF, # Handle biased exponent for nan
|
| 521 |
+
# NOTE: descale < (torch.finfo(torch.float32).smallest_normal / 2) is handled through clamping
|
| 522 |
+
(
|
| 523 |
+
torch.clamp(
|
| 524 |
+
torch.ceil(torch.log2(descale)),
|
| 525 |
+
min=-E8M0_EXPONENT_BIAS,
|
| 526 |
+
max=E8M0_EXPONENT_BIAS,
|
| 527 |
+
)
|
| 528 |
+
+ E8M0_EXPONENT_BIAS
|
| 529 |
+
).to(torch.uint8),
|
| 530 |
+
)
|
| 531 |
+
|
| 532 |
+
descale_fp = torch.where(
|
| 533 |
+
exponent == 0,
|
| 534 |
+
1.0,
|
| 535 |
+
torch.exp2(E8M0_EXPONENT_BIAS - exponent.to(torch.float32)),
|
| 536 |
+
)
|
| 537 |
+
|
| 538 |
+
# scale and saturated cast the data elements to max of target dtype
|
| 539 |
+
data_lp = torch.clamp(data_hp * descale_fp, min=-1 * max_pos, max=max_pos)
|
| 540 |
+
return exponent, data_lp
|
| 541 |
+
|
| 542 |
+
scale_e8m0_biased, data_lp = _to_mx_rceil(data_hp, max_abs, max_pos)
|
| 543 |
+
|
| 544 |
+
# cast to target dtype
|
| 545 |
+
data_lp = data_lp.to(torch.float8_e4m3fn)
|
| 546 |
+
# need to reshape at the end to help inductor fuse things
|
| 547 |
+
data_lp = data_lp.reshape(orig_shape)
|
| 548 |
+
|
| 549 |
+
scale_e8m0_biased = scale_e8m0_biased.view(torch.float8_e8m0fnu)
|
| 550 |
+
scale_e8m0_biased = scale_e8m0_biased.squeeze(-1)
|
| 551 |
+
return scale_e8m0_biased, data_lp
|
| 552 |
+
|
| 553 |
+
# Source: https://github.com/pytorch/ao/blob/568c1932a16ae9f30d48da214a88dc0013e98ed8/torchao/prototype/moe_training/utils.py#L310
|
| 554 |
+
def generate_jagged_offs(E, M, multiple_of=16, dtype=torch.int32, device="cuda"):
|
| 555 |
+
"""
|
| 556 |
+
Utility function for tests and benchmarks.
|
| 557 |
+
|
| 558 |
+
Generates a tensor of length E, containing random values divisible by `multiple_of`,
|
| 559 |
+
from 0 to M, in sorted order, and where the final value in the tensor is always M.
|
| 560 |
+
Args:
|
| 561 |
+
E (int): The length of the tensor.
|
| 562 |
+
M (int): The maximum value in the tensor.
|
| 563 |
+
Returns:
|
| 564 |
+
torch.Tensor: A tensor of length E with the specified properties.
|
| 565 |
+
"""
|
| 566 |
+
import random
|
| 567 |
+
|
| 568 |
+
# Ensure M is divisible by 16
|
| 569 |
+
if M % multiple_of != 0:
|
| 570 |
+
raise ValueError(f"M must be divisible by {multiple_of}")
|
| 571 |
+
|
| 572 |
+
# Generate a list of possible values
|
| 573 |
+
possible_values = list(range(multiple_of, M + 1, multiple_of))
|
| 574 |
+
|
| 575 |
+
# If E is larger than the number of possible values, raise an error
|
| 576 |
+
if E > len(possible_values):
|
| 577 |
+
raise ValueError("E cannot be larger than the number of possible values")
|
| 578 |
+
|
| 579 |
+
# Randomly select E - 1 values from the possible values (excluding M)
|
| 580 |
+
selected_values = torch.tensor(random.sample(possible_values[:-1], E - 1))
|
| 581 |
+
|
| 582 |
+
# Append M to the selected values
|
| 583 |
+
selected_values = torch.cat((selected_values, torch.tensor([M])))
|
| 584 |
+
|
| 585 |
+
# Sort the selected values
|
| 586 |
+
selected_values, _ = torch.sort(selected_values)
|
| 587 |
+
|
| 588 |
+
return selected_values.to(dtype).to(device)
|
pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: ignore-errors
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
from copy import deepcopy
|
| 5 |
+
from torch.utils._pytree import tree_map
|
| 6 |
+
import torch.utils._pytree as pytree
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
# TODO: Move LoggingTensor here.
|
| 10 |
+
from torch.testing._internal.logging_tensor import LoggingTensor
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
# Base class for wrapper-style tensors.
|
| 14 |
+
class WrapperTensor(torch.Tensor):
|
| 15 |
+
@staticmethod
|
| 16 |
+
def __new__(cls, *args, **kwargs):
|
| 17 |
+
t, kwargs = cls.get_wrapper_properties(*args, **kwargs)
|
| 18 |
+
if "size" not in kwargs:
|
| 19 |
+
size = t.size()
|
| 20 |
+
else:
|
| 21 |
+
size = kwargs["size"]
|
| 22 |
+
del kwargs["size"]
|
| 23 |
+
if "dtype" not in kwargs:
|
| 24 |
+
kwargs["dtype"] = t.dtype
|
| 25 |
+
if "layout" not in kwargs:
|
| 26 |
+
kwargs["layout"] = t.layout
|
| 27 |
+
if "device" not in kwargs:
|
| 28 |
+
kwargs["device"] = t.device
|
| 29 |
+
if "requires_grad" not in kwargs:
|
| 30 |
+
kwargs["requires_grad"] = False
|
| 31 |
+
# Ignore memory_format and pin memory for now as I don't know how to
|
| 32 |
+
# safely access them on a Tensor (if possible??)
|
| 33 |
+
|
| 34 |
+
wrapper = torch.Tensor._make_wrapper_subclass(cls, size, **kwargs)
|
| 35 |
+
wrapper._validate_methods()
|
| 36 |
+
return wrapper
|
| 37 |
+
|
| 38 |
+
@classmethod
|
| 39 |
+
def get_wrapper_properties(cls, *args, **kwargs):
|
| 40 |
+
# Should return both an example Tensor and a dictionary of kwargs
|
| 41 |
+
# to override any of that example Tensor's properly.
|
| 42 |
+
# This is very similar to the `t.new_*(args)` API
|
| 43 |
+
raise NotImplementedError("You need to implement get_wrapper_properties")
|
| 44 |
+
|
| 45 |
+
def _validate_methods(self):
|
| 46 |
+
# Skip this if not in debug mode?
|
| 47 |
+
# Changing these on the python side is wrong as it would not be properly reflected
|
| 48 |
+
# on the c++ side
|
| 49 |
+
# This doesn't catch attributes set in the __init__
|
| 50 |
+
forbidden_overrides = ["size", "stride", "dtype", "layout", "device", "requires_grad"]
|
| 51 |
+
for el in forbidden_overrides:
|
| 52 |
+
if getattr(self.__class__, el) is not getattr(torch.Tensor, el):
|
| 53 |
+
raise RuntimeError(f"Subclass {self.__class__.__name__} is overwriting the "
|
| 54 |
+
f"property {el} but this is not allowed as such change would "
|
| 55 |
+
"not be reflected to c++ callers.")
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class WrapperTensorWithCustomSizes(WrapperTensor):
|
| 59 |
+
@classmethod
|
| 60 |
+
def get_wrapper_properties(cls, t, requires_grad=False):
|
| 61 |
+
return t, {"requires_grad": requires_grad, "dispatch_sizes_strides_policy": "sizes"}
|
| 62 |
+
|
| 63 |
+
def __init__(self, t, requires_grad=False):
|
| 64 |
+
self.t = t
|
| 65 |
+
|
| 66 |
+
@classmethod
|
| 67 |
+
def __torch_dispatch__(cls, func, types, args=(), kwargs=None):
|
| 68 |
+
if not all(issubclass(cls, t) for t in types):
|
| 69 |
+
return NotImplemented
|
| 70 |
+
|
| 71 |
+
if kwargs is None:
|
| 72 |
+
kwargs = {}
|
| 73 |
+
|
| 74 |
+
def unwrap(e):
|
| 75 |
+
return e.t if isinstance(e, WrapperTensorWithCustomSizes) else e
|
| 76 |
+
|
| 77 |
+
def wrap(e):
|
| 78 |
+
return WrapperTensorWithCustomSizes(e) if isinstance(e, torch.Tensor) else e
|
| 79 |
+
|
| 80 |
+
rs = tree_map(wrap, func(*tree_map(unwrap, args), **tree_map(unwrap, kwargs or {})))
|
| 81 |
+
return rs
|
| 82 |
+
|
| 83 |
+
def __repr__(self):
|
| 84 |
+
return super().__repr__(tensor_contents=f"t={self.t}")
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
class WrapperTensorWithCustomStrides(WrapperTensor):
|
| 88 |
+
@classmethod
|
| 89 |
+
def get_wrapper_properties(cls, t, requires_grad=False):
|
| 90 |
+
return t, {"requires_grad": requires_grad, "dispatch_sizes_strides_policy": "strides"}
|
| 91 |
+
|
| 92 |
+
def __init__(self, t, requires_grad=False):
|
| 93 |
+
self.t = t
|
| 94 |
+
|
| 95 |
+
@classmethod
|
| 96 |
+
def __torch_dispatch__(cls, func, types, args=(), kwargs=None):
|
| 97 |
+
if not all(issubclass(cls, t) for t in types):
|
| 98 |
+
return NotImplemented
|
| 99 |
+
|
| 100 |
+
if kwargs is None:
|
| 101 |
+
kwargs = {}
|
| 102 |
+
|
| 103 |
+
def unwrap(e):
|
| 104 |
+
return e.t if isinstance(e, WrapperTensorWithCustomStrides) else e
|
| 105 |
+
|
| 106 |
+
def wrap(e):
|
| 107 |
+
return WrapperTensorWithCustomStrides(e) if isinstance(e, torch.Tensor) else e
|
| 108 |
+
|
| 109 |
+
rs = tree_map(wrap, func(*tree_map(unwrap, args), **tree_map(unwrap, kwargs or {})))
|
| 110 |
+
return rs
|
| 111 |
+
|
| 112 |
+
def __repr__(self):
|
| 113 |
+
return super().__repr__(tensor_contents=f"t={self.t}")
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
class DiagTensorBelow(WrapperTensor):
|
| 117 |
+
@classmethod
|
| 118 |
+
def get_wrapper_properties(cls, diag, requires_grad=False):
|
| 119 |
+
assert diag.ndim == 1
|
| 120 |
+
return diag, {"size": diag.size() + diag.size(), "requires_grad": requires_grad}
|
| 121 |
+
|
| 122 |
+
def __init__(self, diag, requires_grad=False):
|
| 123 |
+
self.diag = diag
|
| 124 |
+
|
| 125 |
+
handled_ops = {}
|
| 126 |
+
|
| 127 |
+
@classmethod
|
| 128 |
+
def __torch_dispatch__(cls, func, types, args=(), kwargs=None):
|
| 129 |
+
if not all(issubclass(cls, t) for t in types):
|
| 130 |
+
return NotImplemented
|
| 131 |
+
|
| 132 |
+
# For everything else, call the handler:
|
| 133 |
+
fn = cls.handled_ops.get(func.__name__, None)
|
| 134 |
+
if fn:
|
| 135 |
+
return fn(*args, **(kwargs or {}))
|
| 136 |
+
else:
|
| 137 |
+
# Note that here, because we don't need to provide the autograd formulas
|
| 138 |
+
# we can have a default "fallback" that creates a plain Tensor based
|
| 139 |
+
# on the diag elements and calls the func again.
|
| 140 |
+
|
| 141 |
+
def unwrap(e):
|
| 142 |
+
return e.diag.diag() if isinstance(e, DiagTensorBelow) else e
|
| 143 |
+
|
| 144 |
+
def wrap(e):
|
| 145 |
+
if isinstance(e, torch.Tensor) and e.ndim == 1:
|
| 146 |
+
return DiagTensorBelow(e)
|
| 147 |
+
if isinstance(e, torch.Tensor) and e.ndim == 2 and e.count_nonzero() == e.diag().count_nonzero():
|
| 148 |
+
return DiagTensorBelow(e.diag())
|
| 149 |
+
return e
|
| 150 |
+
|
| 151 |
+
rs = tree_map(wrap, func(*tree_map(unwrap, args), **tree_map(unwrap, kwargs or {})))
|
| 152 |
+
return rs
|
| 153 |
+
|
| 154 |
+
def __repr__(self):
|
| 155 |
+
return super().__repr__(tensor_contents=f"diag={self.diag}")
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
class SparseTensor(WrapperTensor):
|
| 159 |
+
@classmethod
|
| 160 |
+
def get_wrapper_properties(cls, size, values, indices, requires_grad=False):
|
| 161 |
+
assert values.device == indices.device
|
| 162 |
+
return values, {"size": size, "requires_grad": requires_grad}
|
| 163 |
+
|
| 164 |
+
def __init__(self, size, values, indices, requires_grad=False):
|
| 165 |
+
self.values = values
|
| 166 |
+
self.indices = indices
|
| 167 |
+
|
| 168 |
+
def __repr__(self):
|
| 169 |
+
return super().__repr__(tensor_contents=f"values={self.values}, indices={self.indices}")
|
| 170 |
+
|
| 171 |
+
def sparse_to_dense(self):
|
| 172 |
+
res = torch.zeros(self.size(), dtype=self.values.dtype)
|
| 173 |
+
res[self.indices.unbind(1)] = self.values
|
| 174 |
+
return res
|
| 175 |
+
|
| 176 |
+
@staticmethod
|
| 177 |
+
def from_dense(t):
|
| 178 |
+
indices = t.nonzero()
|
| 179 |
+
values = t[indices.unbind(1)]
|
| 180 |
+
return SparseTensor(t.size(), values, indices)
|
| 181 |
+
|
| 182 |
+
@classmethod
|
| 183 |
+
def __torch_dispatch__(cls, func, types, args=(), kwargs=None):
|
| 184 |
+
func_name = f"{func.__module__}.{func.__name__}"
|
| 185 |
+
|
| 186 |
+
res = cls._try_call_special_impl(func_name, args, kwargs)
|
| 187 |
+
if res is not NotImplemented:
|
| 188 |
+
return res
|
| 189 |
+
|
| 190 |
+
# Otherwise, use a default implementation that construct dense
|
| 191 |
+
# tensors and use that to compute values
|
| 192 |
+
def unwrap(e):
|
| 193 |
+
return e.sparse_to_dense() if isinstance(e, SparseTensor) else e
|
| 194 |
+
|
| 195 |
+
# Wrap back all Tensors into our custom class
|
| 196 |
+
def wrap(e):
|
| 197 |
+
# Check for zeros and use that to get indices
|
| 198 |
+
return SparseTensor.from_dense(e) if isinstance(e, torch.Tensor) else e
|
| 199 |
+
|
| 200 |
+
rs = tree_map(wrap, func(*tree_map(unwrap, args), **tree_map(unwrap, kwargs or {})))
|
| 201 |
+
return rs
|
| 202 |
+
|
| 203 |
+
# To show how things happen later
|
| 204 |
+
def __rmul__(self, other):
|
| 205 |
+
return super().__rmul__(other)
|
| 206 |
+
|
| 207 |
+
_SPECIAL_IMPLS = {}
|
| 208 |
+
|
| 209 |
+
@classmethod
|
| 210 |
+
def _try_call_special_impl(cls, func, args, kwargs):
|
| 211 |
+
if func not in cls._SPECIAL_IMPLS:
|
| 212 |
+
return NotImplemented
|
| 213 |
+
return cls._SPECIAL_IMPLS[func](args, kwargs)
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
# Example non-wrapper subclass that stores extra state.
|
| 217 |
+
class NonWrapperTensor(torch.Tensor):
|
| 218 |
+
def __new__(cls, data):
|
| 219 |
+
t = torch.Tensor._make_subclass(cls, data)
|
| 220 |
+
t.extra_state = {
|
| 221 |
+
'last_func_called': None
|
| 222 |
+
}
|
| 223 |
+
return t
|
| 224 |
+
|
| 225 |
+
@classmethod
|
| 226 |
+
def __torch_function__(cls, func, types, args=(), kwargs=None):
|
| 227 |
+
result = super().__torch_function__(func, types, args, kwargs)
|
| 228 |
+
|
| 229 |
+
if isinstance(result, cls):
|
| 230 |
+
# Do something with the extra state. For the example here, just store the name of the
|
| 231 |
+
# last function called (skip for deepcopy so the copy has the same extra state).
|
| 232 |
+
if func is torch.Tensor.__deepcopy__:
|
| 233 |
+
result.extra_state = deepcopy(args[0].extra_state)
|
| 234 |
+
else:
|
| 235 |
+
result.extra_state = {
|
| 236 |
+
'last_func_called': func.__name__,
|
| 237 |
+
}
|
| 238 |
+
|
| 239 |
+
return result
|
| 240 |
+
|
| 241 |
+
# new_empty() must be defined for deepcopy to work
|
| 242 |
+
def new_empty(self, shape):
|
| 243 |
+
return type(self)(torch.empty(shape))
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
# Class used to store info about subclass tensors used in testing.
|
| 247 |
+
class SubclassInfo:
|
| 248 |
+
|
| 249 |
+
__slots__ = ['name', 'create_fn', 'closed_under_ops']
|
| 250 |
+
|
| 251 |
+
def __init__(self, name, create_fn, closed_under_ops=True):
|
| 252 |
+
self.name = name
|
| 253 |
+
self.create_fn = create_fn # create_fn(shape) -> tensor instance
|
| 254 |
+
self.closed_under_ops = closed_under_ops
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
# Helper function to create a subclass of the given class and possibly cache sizes / strides.
|
| 258 |
+
def _create_and_access_shape(cls, shape):
|
| 259 |
+
sub = cls(torch.randn(shape))
|
| 260 |
+
# NB: Wrapper subclasses with custom dispatched sizes / strides cache this info
|
| 261 |
+
# on the first call via non-serializable PyCapsules. We purposefully trigger cache
|
| 262 |
+
# population here for serialization / deepcopy tests to verify that the presence of this
|
| 263 |
+
# cache info doesn't cause problems.
|
| 264 |
+
sub.size()
|
| 265 |
+
sub.stride()
|
| 266 |
+
return sub
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
subclass_db = {
|
| 270 |
+
torch.Tensor: SubclassInfo(
|
| 271 |
+
'base_tensor', create_fn=torch.randn
|
| 272 |
+
),
|
| 273 |
+
NonWrapperTensor: SubclassInfo(
|
| 274 |
+
'non_wrapper_tensor',
|
| 275 |
+
create_fn=lambda shape: NonWrapperTensor(torch.randn(shape))
|
| 276 |
+
),
|
| 277 |
+
LoggingTensor: SubclassInfo(
|
| 278 |
+
'logging_tensor',
|
| 279 |
+
create_fn=lambda shape: LoggingTensor(torch.randn(shape))
|
| 280 |
+
),
|
| 281 |
+
SparseTensor: SubclassInfo(
|
| 282 |
+
'sparse_tensor',
|
| 283 |
+
create_fn=lambda shape: SparseTensor.from_dense(torch.randn(shape).relu())
|
| 284 |
+
),
|
| 285 |
+
DiagTensorBelow: SubclassInfo(
|
| 286 |
+
'diag_tensor_below',
|
| 287 |
+
create_fn=lambda shape: DiagTensorBelow(torch.randn(shape)),
|
| 288 |
+
closed_under_ops=False # sparse semantics
|
| 289 |
+
),
|
| 290 |
+
WrapperTensorWithCustomSizes: SubclassInfo(
|
| 291 |
+
'wrapper_with_custom_sizes',
|
| 292 |
+
create_fn=lambda shape: _create_and_access_shape(WrapperTensorWithCustomSizes, shape),
|
| 293 |
+
closed_under_ops=False,
|
| 294 |
+
),
|
| 295 |
+
WrapperTensorWithCustomStrides: SubclassInfo(
|
| 296 |
+
'wrapper_with_custom_strides',
|
| 297 |
+
create_fn=lambda shape: _create_and_access_shape(WrapperTensorWithCustomStrides, shape),
|
| 298 |
+
closed_under_ops=False,
|
| 299 |
+
),
|
| 300 |
+
}
|
| 301 |
+
|
| 302 |
+
class SubclassWithTensorFactory(torch.Tensor):
|
| 303 |
+
@staticmethod
|
| 304 |
+
def __new__(cls, src):
|
| 305 |
+
shape = src.shape
|
| 306 |
+
kwargs = {}
|
| 307 |
+
kwargs["strides"] = src.stride()
|
| 308 |
+
kwargs["storage_offset"] = src.storage_offset()
|
| 309 |
+
kwargs["device"] = src.device
|
| 310 |
+
kwargs["layout"] = src.layout
|
| 311 |
+
kwargs["requires_grad"] = src.requires_grad
|
| 312 |
+
kwargs["dtype"] = src.dtype
|
| 313 |
+
out = torch.Tensor._make_wrapper_subclass(cls, shape, **kwargs)
|
| 314 |
+
return out
|
| 315 |
+
|
| 316 |
+
def __init__(self, src):
|
| 317 |
+
self.src = src
|
| 318 |
+
|
| 319 |
+
def __repr__(self):
|
| 320 |
+
return f"{self.__class__.__name__}"
|
| 321 |
+
|
| 322 |
+
def __tensor_flatten__(self):
|
| 323 |
+
return ["src"], None
|
| 324 |
+
|
| 325 |
+
@classmethod
|
| 326 |
+
def __tensor_unflatten__(cls, inner_tensors, meta, outer_size, outer_stride):
|
| 327 |
+
src = inner_tensors["src"]
|
| 328 |
+
return cls(src)
|
| 329 |
+
|
| 330 |
+
@classmethod
|
| 331 |
+
def __torch_dispatch__(cls, func, types, args, kwargs):
|
| 332 |
+
if kwargs is None:
|
| 333 |
+
kwargs = {}
|
| 334 |
+
|
| 335 |
+
def _fn(x):
|
| 336 |
+
return x.src * torch.ones(x.src.shape) if x.src.dtype == torch.float32 else x.src
|
| 337 |
+
|
| 338 |
+
_args = pytree.tree_map_only(cls, _fn, args)
|
| 339 |
+
_kwargs = pytree.tree_map_only(cls, _fn, kwargs)
|
| 340 |
+
|
| 341 |
+
_out = func(*_args, **_kwargs)
|
| 342 |
+
|
| 343 |
+
_out_flat, _out_spec = pytree.tree_flatten(_out)
|
| 344 |
+
|
| 345 |
+
out_flat = [cls(o) if isinstance(o, torch.Tensor) else o for o in _out_flat]
|
| 346 |
+
return pytree.tree_unflatten(out_flat, _out_spec)
|
pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/common_utils.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/composite_compliance.py
ADDED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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: ignore-errors
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
from torch import Tensor
|
| 5 |
+
import itertools
|
| 6 |
+
|
| 7 |
+
from torch.utils._python_dispatch import TorchDispatchMode
|
| 8 |
+
from torch.utils._pytree import tree_map, tree_flatten, tree_unflatten
|
| 9 |
+
from torch.utils import _pytree as pytree
|
| 10 |
+
from functools import partial
|
| 11 |
+
from torch.utils._mode_utils import no_dispatch, all_same_mode
|
| 12 |
+
import torch.autograd.forward_ad as fwAD
|
| 13 |
+
from typing import Callable
|
| 14 |
+
import re
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def check_attr_consistency(wrapper_tensor, metadata_name, metadata_accessor):
|
| 18 |
+
elem = wrapper_tensor.elem
|
| 19 |
+
metadata_wrapper_tensor = metadata_accessor(wrapper_tensor)
|
| 20 |
+
metadata_elem = metadata_accessor(elem)
|
| 21 |
+
if metadata_wrapper_tensor == metadata_elem:
|
| 22 |
+
return
|
| 23 |
+
raise RuntimeError(
|
| 24 |
+
f"This operator is not Composite Compliant: the "
|
| 25 |
+
f"{metadata_name} of the tensor was modified directly without "
|
| 26 |
+
f"going through the PyTorch dispatcher.")
|
| 27 |
+
|
| 28 |
+
def check_metadata_consistency(wrapper_tensor, CCT):
|
| 29 |
+
# CCT: CompositeCompliantTensor class which is generated using generate_cct
|
| 30 |
+
if not isinstance(wrapper_tensor, CCT):
|
| 31 |
+
return
|
| 32 |
+
things_to_check = {
|
| 33 |
+
'shape': Tensor.size,
|
| 34 |
+
'dtype': lambda x: x.dtype,
|
| 35 |
+
'device': lambda x: x.device,
|
| 36 |
+
'numel': Tensor.numel,
|
| 37 |
+
'stride': Tensor.stride,
|
| 38 |
+
'storage_offset': Tensor.storage_offset,
|
| 39 |
+
}
|
| 40 |
+
for metadata_name, metadata_accessor in things_to_check.items():
|
| 41 |
+
check_attr_consistency(wrapper_tensor, metadata_name, metadata_accessor)
|
| 42 |
+
|
| 43 |
+
def is_view_fn(func):
|
| 44 |
+
return func.overloadpacket.__name__ in {
|
| 45 |
+
'as_strided',
|
| 46 |
+
'detach',
|
| 47 |
+
'diagonal',
|
| 48 |
+
'expand',
|
| 49 |
+
'expand_as',
|
| 50 |
+
'movedim',
|
| 51 |
+
'narrow',
|
| 52 |
+
'permute',
|
| 53 |
+
'select',
|
| 54 |
+
'squeeze',
|
| 55 |
+
'transpose',
|
| 56 |
+
't',
|
| 57 |
+
'real',
|
| 58 |
+
'imag',
|
| 59 |
+
'view_as_real',
|
| 60 |
+
'view_as_complex',
|
| 61 |
+
'unflatten',
|
| 62 |
+
'unfold',
|
| 63 |
+
'unsqueeze',
|
| 64 |
+
'view',
|
| 65 |
+
'view_as',
|
| 66 |
+
'unbind',
|
| 67 |
+
'split',
|
| 68 |
+
'split_with_sizes',
|
| 69 |
+
'vsplit',
|
| 70 |
+
'hsplit',
|
| 71 |
+
'tensor_split',
|
| 72 |
+
'chunk',
|
| 73 |
+
'swapaxes',
|
| 74 |
+
'slice',
|
| 75 |
+
'_reshape_alias',
|
| 76 |
+
'_unsafe_view',
|
| 77 |
+
'_conj',
|
| 78 |
+
'alias',
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
# manually populated from native_functions that have inplace_view: True.
|
| 82 |
+
# In the future we will probably be able to grab that list directly
|
| 83 |
+
def is_inplace_view_fn(func):
|
| 84 |
+
return func.overloadpacket.__name__ in {
|
| 85 |
+
'as_strided_',
|
| 86 |
+
'detach_',
|
| 87 |
+
'squeeze_',
|
| 88 |
+
'swapaxes_',
|
| 89 |
+
'swapdims_',
|
| 90 |
+
't_',
|
| 91 |
+
'transpose_',
|
| 92 |
+
'unsqueeze_',
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
# Introspection please save us
|
| 97 |
+
def is_inplace(func):
|
| 98 |
+
name = func.overloadpacket.__name__
|
| 99 |
+
if re.match('__i.+__', name):
|
| 100 |
+
return True
|
| 101 |
+
if re.match('__.+__', name):
|
| 102 |
+
return False
|
| 103 |
+
return name[-1] == '_'
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def generate_cct_and_mode(autograd_view_consistency=True):
|
| 107 |
+
# This function returns a new class CompositeCompliantTensor
|
| 108 |
+
# The two arguments control the behaviour described below.
|
| 109 |
+
|
| 110 |
+
# autograd_view_consistency:
|
| 111 |
+
# If True, alias result using `set_` if func returns a view
|
| 112 |
+
# (See Note [Alias Result]).
|
| 113 |
+
# Since Forward AD doesn't work with `set_`
|
| 114 |
+
# we disable it by setting alias to False.
|
| 115 |
+
|
| 116 |
+
class CompositeCompliantTensor(torch.Tensor):
|
| 117 |
+
elem: torch.Tensor
|
| 118 |
+
|
| 119 |
+
__slots__ = ['elem']
|
| 120 |
+
|
| 121 |
+
@staticmethod
|
| 122 |
+
def __new__(cls, elem, mode, *args, **kwargs):
|
| 123 |
+
assert type(elem) is not cls, \
|
| 124 |
+
"Wrapping a CompositeCompliantTensor in a CompositeCompliantTensor is not supported"
|
| 125 |
+
|
| 126 |
+
# The storage of CompositeCompliantTensor should never be used directly
|
| 127 |
+
# by a Composite operation; if the Composite
|
| 128 |
+
# operator attempts to read from the storage without dispatching then it'll
|
| 129 |
+
# raise a RuntimeError due to it being a meta storage.
|
| 130 |
+
r = torch.Tensor._make_wrapper_subclass(
|
| 131 |
+
cls, elem.size(),
|
| 132 |
+
dtype=elem.dtype, layout=elem.layout,
|
| 133 |
+
device=elem.device, requires_grad=elem.requires_grad,
|
| 134 |
+
strides=elem.stride(), storage_offset=elem.storage_offset())
|
| 135 |
+
|
| 136 |
+
if elem.requires_grad:
|
| 137 |
+
# CompositeCompliantTensor steals the "requires_grad"-ness.
|
| 138 |
+
# Why a new copy of `elem`? Because sometimes OpInfo shares inputs between tests...
|
| 139 |
+
tmp = torch.empty(
|
| 140 |
+
(),
|
| 141 |
+
dtype=elem.dtype,
|
| 142 |
+
device=elem.device,
|
| 143 |
+
layout=elem.layout,
|
| 144 |
+
requires_grad=False,
|
| 145 |
+
)
|
| 146 |
+
# Use set_ rather than empty_strided() + copy_ so that we can preserve
|
| 147 |
+
# things like storage_offset.
|
| 148 |
+
tmp.set_(
|
| 149 |
+
source=elem.untyped_storage().clone(),
|
| 150 |
+
storage_offset=elem.storage_offset(),
|
| 151 |
+
size=elem.size(),
|
| 152 |
+
stride=elem.stride(),
|
| 153 |
+
)
|
| 154 |
+
r.elem = tmp
|
| 155 |
+
else:
|
| 156 |
+
r.elem = elem
|
| 157 |
+
|
| 158 |
+
assert r.stride() == r.elem.stride()
|
| 159 |
+
|
| 160 |
+
# Propagate conjugate bits to the wrapper tensor
|
| 161 |
+
# Ref: https://github.com/albanD/subclass_zoo/issues/24
|
| 162 |
+
# Ref: https://github.com/albanD/subclass_zoo/issues/21
|
| 163 |
+
torch._C._set_conj(r, r.elem.is_conj())
|
| 164 |
+
torch._C._set_neg(r, r.elem.is_neg())
|
| 165 |
+
|
| 166 |
+
r.mode = mode
|
| 167 |
+
return r
|
| 168 |
+
|
| 169 |
+
def __repr__(self):
|
| 170 |
+
return f"CompositeCompliantTensor({self.elem})"
|
| 171 |
+
|
| 172 |
+
@classmethod
|
| 173 |
+
def __torch_dispatch__(cls, func, types, args=(), kwargs=None):
|
| 174 |
+
all_args = pytree.arg_tree_leaves(*args, **(kwargs or {}))
|
| 175 |
+
modes = tuple(e.mode for e in all_args if isinstance(e, CompositeCompliantTensor))
|
| 176 |
+
if not all_same_mode(modes):
|
| 177 |
+
raise RuntimeError("Multiple CompositeCompliantTensorModes NYI")
|
| 178 |
+
with modes[0]:
|
| 179 |
+
return func(*args, **kwargs)
|
| 180 |
+
|
| 181 |
+
class CompositeCompliantTensorMode(TorchDispatchMode):
|
| 182 |
+
def __torch_dispatch__(self, func, types, args=(), kwargs=None):
|
| 183 |
+
def unwrap(e):
|
| 184 |
+
return e.elem if isinstance(e, CompositeCompliantTensor) else e
|
| 185 |
+
|
| 186 |
+
def wrap(e):
|
| 187 |
+
return CompositeCompliantTensor(e, self) if isinstance(e, torch.Tensor) else e
|
| 188 |
+
|
| 189 |
+
if func == torch.ops.aten._local_scalar_dense.default:
|
| 190 |
+
raise RuntimeError(
|
| 191 |
+
".item() is not allowed to be called inside of composite "
|
| 192 |
+
"functions in the PyTorch library because not all backends "
|
| 193 |
+
"and/or Tensor subclasses (e.g. vmap, ProxyTensor) support them.")
|
| 194 |
+
|
| 195 |
+
if func.overloadpacket.__name__ in ('set_', 'resize_'):
|
| 196 |
+
raise RuntimeError(
|
| 197 |
+
f"{func.__name__} is not allowed to be called inside of "
|
| 198 |
+
f"Composite operators.")
|
| 199 |
+
|
| 200 |
+
if is_inplace(func):
|
| 201 |
+
# NB: We are making an assumption that if the function is in-place,
|
| 202 |
+
# then the first argument is being written to. Introspection please save us!
|
| 203 |
+
mutated_argument = args[0]
|
| 204 |
+
if not isinstance(mutated_argument, CompositeCompliantTensor) and \
|
| 205 |
+
any(isinstance(a, CompositeCompliantTensor) for a in args[1:]):
|
| 206 |
+
raise RuntimeError(
|
| 207 |
+
'Not composite compliant: performing in-place operation '
|
| 208 |
+
f'{func.__name__} where the Tensor being written to is '
|
| 209 |
+
'regular Tensor but the other tensors are Tensor Subclasses. '
|
| 210 |
+
'Please try to avoid this in-place operation.')
|
| 211 |
+
|
| 212 |
+
unwrapped_args = tree_map(unwrap, args)
|
| 213 |
+
unwrapped_kwargs = tree_map(unwrap, kwargs)
|
| 214 |
+
unwrapped_rs = func(*unwrapped_args, **unwrapped_kwargs)
|
| 215 |
+
rs = tree_map(wrap, unwrapped_rs)
|
| 216 |
+
|
| 217 |
+
if is_view_fn(func) and autograd_view_consistency:
|
| 218 |
+
# Note [Alias Result]
|
| 219 |
+
# Autograd asserts that for B = A.view_fn(...), B and A's storages
|
| 220 |
+
# are the same. Here we try to make B alias A to avoid those asserts.
|
| 221 |
+
# See https://github.com/pytorch/pytorch/issues/65339 for more information
|
| 222 |
+
# about the issue.
|
| 223 |
+
with no_dispatch():
|
| 224 |
+
# Idea: this is a weird way of getting a storage that aliases the input.
|
| 225 |
+
# This is a workaround for #65339.
|
| 226 |
+
# 1. under no_dispatch, all of the wrapper tensors look like regular
|
| 227 |
+
# tensors with special storage (the storage is nullptr and
|
| 228 |
+
# advertises CPU/CUDA device.
|
| 229 |
+
# 2. we run func, which ends up running the view operation
|
| 230 |
+
# 3. All view operations reuse the input's storage and return
|
| 231 |
+
# result Tensor(s) with new sizes/strides/offset that alias
|
| 232 |
+
# the input.
|
| 233 |
+
# 4. we set the storage (and sizes/strides/offset) of the wrapper
|
| 234 |
+
# tensor results to be that of the tensors that alias the input
|
| 235 |
+
result = func(*args, **kwargs)
|
| 236 |
+
if isinstance(result, (tuple, list)):
|
| 237 |
+
for a, b in zip(rs, result):
|
| 238 |
+
a.set_(b)
|
| 239 |
+
else:
|
| 240 |
+
rs.set_(result)
|
| 241 |
+
|
| 242 |
+
# Some operations are allowed to in-place modify the metadata of the
|
| 243 |
+
# inputs. The only ones are the "inplace view functions"; when we
|
| 244 |
+
# run into these, we manually modify the metadata of the input.
|
| 245 |
+
with no_dispatch():
|
| 246 |
+
if is_inplace_view_fn(func):
|
| 247 |
+
func(*args, **kwargs)
|
| 248 |
+
|
| 249 |
+
# For each CompositeCompliantTensor t, we check that t and t.elem
|
| 250 |
+
# have consistent metadata. If they don't have consistent metadata,
|
| 251 |
+
# that means the operator did something fishy.
|
| 252 |
+
check = partial(check_metadata_consistency, CCT=CompositeCompliantTensor)
|
| 253 |
+
pytree.tree_map_(check, args)
|
| 254 |
+
pytree.tree_map_(check, kwargs)
|
| 255 |
+
pytree.tree_map_(check, rs)
|
| 256 |
+
return rs
|
| 257 |
+
|
| 258 |
+
return CompositeCompliantTensor, CompositeCompliantTensorMode()
|
| 259 |
+
|
| 260 |
+
def is_tensorlist(lst):
|
| 261 |
+
if not isinstance(lst, list) and not isinstance(lst, tuple):
|
| 262 |
+
return False
|
| 263 |
+
if len(lst) == 0:
|
| 264 |
+
return False
|
| 265 |
+
all_tensors = all(isinstance(elt, torch.Tensor) for elt in lst)
|
| 266 |
+
if all_tensors:
|
| 267 |
+
return True
|
| 268 |
+
exists_one_tensor = all(isinstance(elt, torch.Tensor) for elt in lst)
|
| 269 |
+
if exists_one_tensor:
|
| 270 |
+
raise RuntimeError('This test assumes that PyTorch APIs cannot take '
|
| 271 |
+
'mixed lists of Tensor and other things')
|
| 272 |
+
return False
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
def maybe_map(fn, should_map, arg):
|
| 276 |
+
return fn(arg) if should_map else arg
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
def wrap(arg, CCT, cct_mode):
|
| 280 |
+
# CCT: CompositeCompliantTensor class which is generated using generate_cct_and_mode
|
| 281 |
+
if isinstance(arg, torch.Tensor):
|
| 282 |
+
return CCT(arg, cct_mode)
|
| 283 |
+
if is_tensorlist(arg):
|
| 284 |
+
return [CCT(a, cct_mode) for a in arg]
|
| 285 |
+
raise RuntimeError("wrap assumes that the input can be wrapped")
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
# Given a list of flat arguments, some of which may be Tensors, return all
|
| 289 |
+
# possible ways some of the arguments could be CompositeCompliantTensors (CCT).
|
| 290 |
+
# For example, given Tensors A, B, C and flat_args = [A, 1, B],
|
| 291 |
+
# We would return the following 4 options:
|
| 292 |
+
# [CCT(A), 1, CCT(B)]
|
| 293 |
+
# [CCT(A), 1, B]
|
| 294 |
+
# [A, 1, CCT(B)]
|
| 295 |
+
# [A, 1, B]
|
| 296 |
+
# NB: Yes, this is exponential. No, we don't care too much because PyTorch ops
|
| 297 |
+
# don't accept that many input Tensors.
|
| 298 |
+
def generate_subclass_choices(flat_args, CCT, cct_mode):
|
| 299 |
+
# CCT: CompositeCompliantTensor class which is generated using generate_cct_and_mode
|
| 300 |
+
is_tensor_likes = [isinstance(arg, torch.Tensor) or is_tensorlist(arg) for arg in flat_args]
|
| 301 |
+
subclass_options = [[False, True] if is_tensor_like else [False] for is_tensor_like in is_tensor_likes]
|
| 302 |
+
|
| 303 |
+
for which_args_are_wrapped in itertools.product(*subclass_options):
|
| 304 |
+
|
| 305 |
+
result = [maybe_map(partial(wrap, CCT=CCT, cct_mode=cct_mode), should_wrap_arg, arg)
|
| 306 |
+
for should_wrap_arg, arg in zip(which_args_are_wrapped, flat_args)]
|
| 307 |
+
yield result, which_args_are_wrapped
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
# For an operation f(*args, **kwargs), each Tensor argument may either be
|
| 311 |
+
# a regular Tensor or a Tensor Subclass. This iterator iterates through
|
| 312 |
+
# all of those options.
|
| 313 |
+
def generate_subclass_choices_args_kwargs(args, kwargs, CCT, cct_mode):
|
| 314 |
+
# CCT: CompositeCompliantTensor class which is generated using generate_cct_and_mode
|
| 315 |
+
flat_kwargs, spec = tree_flatten(kwargs)
|
| 316 |
+
flat_args_kwargs = list(args) + list(flat_kwargs)
|
| 317 |
+
for choice, debug_metadata in generate_subclass_choices(flat_args_kwargs, CCT, cct_mode):
|
| 318 |
+
new_args = choice[:len(args)]
|
| 319 |
+
new_kwargs = tree_unflatten(choice[len(args):], spec)
|
| 320 |
+
which_args_are_wrapped = debug_metadata[:len(args)]
|
| 321 |
+
which_kwargs_are_wrapped = tree_unflatten(debug_metadata[len(args):], spec)
|
| 322 |
+
yield new_args, new_kwargs, which_args_are_wrapped, which_kwargs_are_wrapped
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
def raise_composite_compliance_error(err, additional_info=''):
|
| 326 |
+
raise RuntimeError(
|
| 327 |
+
"Composite compliance check failed with "
|
| 328 |
+
"the above error.\n"
|
| 329 |
+
f"{additional_info}"
|
| 330 |
+
"If you are adding an OpInfo of an "
|
| 331 |
+
"existing operator, please feel free to skip this test "
|
| 332 |
+
"because the problem was pre-existing and file an issue. "
|
| 333 |
+
"Otherwise, if you added a new operator, please read "
|
| 334 |
+
"through the Composite Compliance section in "
|
| 335 |
+
"aten/src/ATen/native/README.md for how to resolve this. "
|
| 336 |
+
) from err
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
# This test checks ALL possible permutations of calling `op` with arguments
|
| 340 |
+
# that are individually either a regular Tensor or a Tensor subclass.
|
| 341 |
+
#
|
| 342 |
+
# The general strategy is to wrap some Tensor args and kwargs in
|
| 343 |
+
# CompositeCompliantTensor wrappers and call the operation.
|
| 344 |
+
|
| 345 |
+
# If some composite operation does any non-compliant behavior,
|
| 346 |
+
# CompositeCompliantTensor will raise an error.
|
| 347 |
+
def check_all_permutations(op, args, kwargs, assert_equal_fn):
|
| 348 |
+
CCT, cct_mode = generate_cct_and_mode()
|
| 349 |
+
expected = op(*args, **kwargs)
|
| 350 |
+
for choice in generate_subclass_choices_args_kwargs(args, kwargs, CCT, cct_mode):
|
| 351 |
+
new_args, new_kwargs, which_args_are_wrapped, which_kwargs_are_wrapped = choice
|
| 352 |
+
|
| 353 |
+
try:
|
| 354 |
+
actual = op(*new_args, **new_kwargs)
|
| 355 |
+
# NOTE: [What errors are Composite Compliance trying to catch?]
|
| 356 |
+
#
|
| 357 |
+
# There's two things we want to catch:
|
| 358 |
+
# - errors that would raise within the torch_dispatch impl
|
| 359 |
+
# - data_ptr accesses
|
| 360 |
+
# The first is easy to filter for (we could make the error a different
|
| 361 |
+
# error class), the second is always going to be a RuntimeError due to
|
| 362 |
+
# how it is implemented (if you try to access the data_ptr of the
|
| 363 |
+
# wrapper Tensor, it raises you some internal RuntimeError).
|
| 364 |
+
#
|
| 365 |
+
# So the most general thing to catch here was RuntimeError. If you
|
| 366 |
+
# are here and debugging why your test failed, it's plausible that
|
| 367 |
+
# the operator itself is broken and that there are other tests failing.
|
| 368 |
+
except RuntimeError as err:
|
| 369 |
+
raise_composite_compliance_error(
|
| 370 |
+
err,
|
| 371 |
+
f"- wrapped_args: {which_args_are_wrapped}\n"
|
| 372 |
+
f"- wrapped_kwargs: {which_kwargs_are_wrapped}\n"
|
| 373 |
+
)
|
| 374 |
+
|
| 375 |
+
def unwrap(e):
|
| 376 |
+
return e.elem if isinstance(e, CCT) else e
|
| 377 |
+
|
| 378 |
+
assert_equal_fn(tree_map(unwrap, actual), expected)
|
| 379 |
+
|
| 380 |
+
# Checks via the usage of torch dispatch mode certain anti-patterns that
|
| 381 |
+
# are not composite compliant.
|
| 382 |
+
#
|
| 383 |
+
# In particular, the anti-pattern we are trying to prevent is a user
|
| 384 |
+
# creating an empty tensor and then resize_-ing it. Torch Dispatch Mode helps
|
| 385 |
+
# here because all factory functions will create tensors that are
|
| 386 |
+
# CompositeCompliantTensor.
|
| 387 |
+
#
|
| 388 |
+
# The general strategy is to wrap all Tensor args and kwargs in
|
| 389 |
+
# CompositeCompliantTensor wrappers. If an operator that is
|
| 390 |
+
# Composite does any non-compliant behavior,
|
| 391 |
+
# CompositeCompliantTensor will raise an error.
|
| 392 |
+
def check_with_mode(op, args, kwargs, assert_equal_fn):
|
| 393 |
+
CCT, cct_mode = generate_cct_and_mode()
|
| 394 |
+
|
| 395 |
+
def wrap(e):
|
| 396 |
+
return CCT(e, cct_mode) if isinstance(e, torch.Tensor) else e
|
| 397 |
+
|
| 398 |
+
expected = op(*args, **kwargs)
|
| 399 |
+
|
| 400 |
+
args = tree_map(wrap, args)
|
| 401 |
+
kwargs = tree_map(wrap, kwargs)
|
| 402 |
+
try:
|
| 403 |
+
with cct_mode:
|
| 404 |
+
actual = op(*args, **kwargs)
|
| 405 |
+
# see NOTE: [What errors are Composite Compliance trying to catch?]
|
| 406 |
+
except RuntimeError as err:
|
| 407 |
+
raise_composite_compliance_error(err)
|
| 408 |
+
|
| 409 |
+
def unwrap(e):
|
| 410 |
+
return e.elem if isinstance(e, CCT) else e
|
| 411 |
+
|
| 412 |
+
assert_equal_fn(tree_map(unwrap, actual), expected)
|
| 413 |
+
|
| 414 |
+
def gather_leaf_tensors(args, kwargs):
|
| 415 |
+
leaf_tensors = []
|
| 416 |
+
args, _args_spec = tree_flatten(args)
|
| 417 |
+
kwargs, _kwargs_spec = tree_flatten(kwargs)
|
| 418 |
+
args = args + kwargs
|
| 419 |
+
for arg in args:
|
| 420 |
+
if not isinstance(arg, torch.Tensor):
|
| 421 |
+
continue
|
| 422 |
+
if arg.requires_grad:
|
| 423 |
+
leaf_tensors.append(arg)
|
| 424 |
+
return leaf_tensors
|
| 425 |
+
|
| 426 |
+
|
| 427 |
+
def compute_expected_grads(op, args, kwargs, output_process_fn_grad=None, gradcheck_wrapper=None):
|
| 428 |
+
if gradcheck_wrapper is None:
|
| 429 |
+
results = op(*args, **kwargs)
|
| 430 |
+
else:
|
| 431 |
+
results = gradcheck_wrapper(op, *args, **kwargs)
|
| 432 |
+
|
| 433 |
+
if output_process_fn_grad is not None:
|
| 434 |
+
results = output_process_fn_grad(results)
|
| 435 |
+
|
| 436 |
+
flat_results = pytree.tree_leaves(results)
|
| 437 |
+
flat_results = [r for r in flat_results if isinstance(r, torch.Tensor)]
|
| 438 |
+
flat_diff_results = [r for r in flat_results if r.requires_grad]
|
| 439 |
+
assert len(flat_diff_results) > 0
|
| 440 |
+
|
| 441 |
+
grads = [torch.ones(r.shape, device=r.device, dtype=r.dtype) for r in flat_diff_results]
|
| 442 |
+
leaf_tensors = gather_leaf_tensors(args, kwargs)
|
| 443 |
+
assert len(leaf_tensors) > 0
|
| 444 |
+
return torch.autograd.grad(flat_diff_results, leaf_tensors,
|
| 445 |
+
grads, allow_unused=True, retain_graph=True)
|
| 446 |
+
|
| 447 |
+
|
| 448 |
+
# Checks if the backward formula is composite compliant by testing
|
| 449 |
+
# all possible permutations of {inputs, grad_outputs} being
|
| 450 |
+
# CompositeCompliantTensor or regular Tensors.
|
| 451 |
+
#
|
| 452 |
+
# NB: it is important that op is accepted as a Callable and not an OpInfo,
|
| 453 |
+
# this means we can apply check_backward_formula to things that aren't OpInfos
|
| 454 |
+
# while debugging.
|
| 455 |
+
def check_backward_formula(op: Callable, args, kwargs,
|
| 456 |
+
output_process_fn_grad=None,
|
| 457 |
+
gradcheck_wrapper=None, assert_equal_fn=None):
|
| 458 |
+
CCT, cct_mode = generate_cct_and_mode()
|
| 459 |
+
|
| 460 |
+
expected = compute_expected_grads(op, args, kwargs, output_process_fn_grad, gradcheck_wrapper)
|
| 461 |
+
|
| 462 |
+
for choice in generate_subclass_choices_args_kwargs(args, kwargs, CCT, cct_mode):
|
| 463 |
+
new_args, new_kwargs, which_args_are_wrapped, which_kwargs_are_wrapped = choice
|
| 464 |
+
leaf_tensors = gather_leaf_tensors(new_args, new_kwargs)
|
| 465 |
+
assert len(leaf_tensors) > 0
|
| 466 |
+
|
| 467 |
+
try:
|
| 468 |
+
if gradcheck_wrapper is None:
|
| 469 |
+
results = op(*new_args, **new_kwargs)
|
| 470 |
+
else:
|
| 471 |
+
results = gradcheck_wrapper(op, *new_args, **new_kwargs)
|
| 472 |
+
if output_process_fn_grad is not None:
|
| 473 |
+
results = output_process_fn_grad(results)
|
| 474 |
+
# see NOTE: [What errors are Composite Compliance trying to catch?]
|
| 475 |
+
except RuntimeError as err:
|
| 476 |
+
raise_composite_compliance_error(
|
| 477 |
+
err,
|
| 478 |
+
f"- wrapped_args: {which_args_are_wrapped}\n"
|
| 479 |
+
f"- wrapped_kwargs: {which_kwargs_are_wrapped}\n"
|
| 480 |
+
)
|
| 481 |
+
|
| 482 |
+
flat_results = pytree.tree_leaves(results)
|
| 483 |
+
flat_results = [r for r in flat_results if isinstance(r, torch.Tensor)]
|
| 484 |
+
flat_diff_results = [r for r in flat_results if r.requires_grad]
|
| 485 |
+
assert len(flat_diff_results) > 0
|
| 486 |
+
|
| 487 |
+
# NB: ones, not ones_like, so we get a regular Tensor here
|
| 488 |
+
grads = [torch.ones(r.shape, device=r.device, dtype=r.dtype)
|
| 489 |
+
for r in flat_diff_results]
|
| 490 |
+
for flat_new_grads, which_grad_is_batched in generate_subclass_choices(grads, CCT, cct_mode):
|
| 491 |
+
try:
|
| 492 |
+
actual = torch.autograd.grad(flat_diff_results, leaf_tensors, flat_new_grads,
|
| 493 |
+
allow_unused=True, retain_graph=True)
|
| 494 |
+
# see NOTE: [What errors are Composite Compliance trying to catch?]
|
| 495 |
+
except RuntimeError as err:
|
| 496 |
+
raise_composite_compliance_error(
|
| 497 |
+
err,
|
| 498 |
+
f"- wrapped_args: {which_args_are_wrapped}\n"
|
| 499 |
+
f"- wrapped_kwargs: {which_kwargs_are_wrapped}\n"
|
| 500 |
+
f"- wrapped_grads: {which_grad_is_batched}\n"
|
| 501 |
+
)
|
| 502 |
+
|
| 503 |
+
def unwrap(e):
|
| 504 |
+
return e.elem if isinstance(e, CCT) else e
|
| 505 |
+
|
| 506 |
+
assert_equal_fn(tuple(map(unwrap, actual)), expected, equal_nan=True)
|
| 507 |
+
|
| 508 |
+
# Checks if the forward AD formula is composite compliant by testing
|
| 509 |
+
# all possible permutations of {primals, tangents} being
|
| 510 |
+
# CompositeCompliantTensor or regular Tensors.
|
| 511 |
+
#
|
| 512 |
+
# NB: it is important that op is accepted as a Callable and not an OpInfo,
|
| 513 |
+
# this means we can apply check_forward_ad_formula to things that aren't OpInfos
|
| 514 |
+
# while debugging.
|
| 515 |
+
def check_forward_ad_formula(op: Callable, args, kwargs, gradcheck_wrapper=None, assert_equal_fn=None):
|
| 516 |
+
CCT, cct_mode = generate_cct_and_mode(autograd_view_consistency=False)
|
| 517 |
+
|
| 518 |
+
def maybe_tangent(t):
|
| 519 |
+
assert type(t) is not CCT
|
| 520 |
+
# Generate `tangent` tensor
|
| 521 |
+
# if given object is a Tensor and requires grad is set.
|
| 522 |
+
if isinstance(t, torch.Tensor) and t.requires_grad:
|
| 523 |
+
return torch.randn_like(t)
|
| 524 |
+
elif is_tensorlist(t):
|
| 525 |
+
return [torch.randn_like(e) if e.requires_grad else None for e in t]
|
| 526 |
+
return None
|
| 527 |
+
|
| 528 |
+
tangent_args = tuple(maybe_tangent(arg) for arg in args)
|
| 529 |
+
flat_kwargs, spec = tree_flatten(kwargs)
|
| 530 |
+
flat_tangent_kwargs = tuple(maybe_tangent(arg) for arg in flat_kwargs)
|
| 531 |
+
tangent_kwargs = tree_unflatten(flat_tangent_kwargs, spec)
|
| 532 |
+
|
| 533 |
+
with fwAD.dual_level():
|
| 534 |
+
def maybe_make_dual(dual):
|
| 535 |
+
# Returns dual tensor if primal is a tensor/tensor subclass
|
| 536 |
+
# with requires_grad set.
|
| 537 |
+
primal, tangent = dual
|
| 538 |
+
if isinstance(primal, torch.Tensor) and primal.requires_grad:
|
| 539 |
+
return fwAD.make_dual(primal.detach(), tangent)
|
| 540 |
+
elif is_tensorlist(primal):
|
| 541 |
+
return tuple(fwAD.make_dual(pri.detach(), tang) if tang is not None else pri
|
| 542 |
+
for pri, tang in zip(primal, tangent))
|
| 543 |
+
return primal
|
| 544 |
+
|
| 545 |
+
def compute_expected_grad(args, tangent_args, kwargs, tangent_kwargs):
|
| 546 |
+
op_args = tuple(map(maybe_make_dual, zip(args, tangent_args)))
|
| 547 |
+
op_kwargs = {k: maybe_make_dual((v, tangent_kwargs[k])) for k, v in kwargs.items()}
|
| 548 |
+
|
| 549 |
+
if gradcheck_wrapper is None:
|
| 550 |
+
return op(*op_args, **op_kwargs)
|
| 551 |
+
return gradcheck_wrapper(op, *op_args, **op_kwargs)
|
| 552 |
+
|
| 553 |
+
expected = compute_expected_grad(args, tangent_args, kwargs, tangent_kwargs)
|
| 554 |
+
expected = tree_map(fwAD.unpack_dual, expected)
|
| 555 |
+
expected_primals = tree_map(
|
| 556 |
+
lambda x: x.primal,
|
| 557 |
+
expected,
|
| 558 |
+
is_leaf=lambda x: type(x) is fwAD.UnpackedDualTensor,
|
| 559 |
+
)
|
| 560 |
+
expected_tangents = tree_map(
|
| 561 |
+
lambda x: x.tangent,
|
| 562 |
+
expected,
|
| 563 |
+
is_leaf=lambda x: type(x) is fwAD.UnpackedDualTensor,
|
| 564 |
+
)
|
| 565 |
+
|
| 566 |
+
# Permutations of arg and kwargs in CCT.
|
| 567 |
+
for choice in generate_subclass_choices_args_kwargs(args, kwargs, CCT, cct_mode):
|
| 568 |
+
new_args, new_kwargs, which_args_are_wrapped, which_kwargs_are_wrapped = choice
|
| 569 |
+
|
| 570 |
+
# Permutations tangent arg and tangent kwargs in CCT.
|
| 571 |
+
for tang_choice in generate_subclass_choices_args_kwargs(tangent_args, tangent_kwargs, CCT, cct_mode):
|
| 572 |
+
new_tang_args, new_tang_kwargs, \
|
| 573 |
+
which_tang_args_are_wrapped, which_tang_kwargs_are_wrapped = tang_choice
|
| 574 |
+
|
| 575 |
+
op_args = tuple(map(maybe_make_dual, zip(new_args, new_tang_args)))
|
| 576 |
+
op_kwargs = {k: maybe_make_dual((v, new_tang_kwargs[k])) for k, v in new_kwargs.items()}
|
| 577 |
+
|
| 578 |
+
try:
|
| 579 |
+
if gradcheck_wrapper is None:
|
| 580 |
+
actual = op(*op_args, **op_kwargs)
|
| 581 |
+
else:
|
| 582 |
+
actual = gradcheck_wrapper(op, *op_args, **op_kwargs)
|
| 583 |
+
# see NOTE: [What errors are Composite Compliance trying to catch?]
|
| 584 |
+
except RuntimeError as err:
|
| 585 |
+
raise_composite_compliance_error(
|
| 586 |
+
err,
|
| 587 |
+
f"- wrapped_args: {which_args_are_wrapped}\n"
|
| 588 |
+
f"- wrapped_kwargs: {which_kwargs_are_wrapped}\n"
|
| 589 |
+
f"- wrapped_tangent_args: {which_tang_args_are_wrapped}\n"
|
| 590 |
+
f"- wrapped_tangent_kwargs: {which_tang_kwargs_are_wrapped}\n"
|
| 591 |
+
)
|
| 592 |
+
|
| 593 |
+
def unwrap(e):
|
| 594 |
+
return e.elem if isinstance(e, CCT) else e
|
| 595 |
+
|
| 596 |
+
actual = tree_map(fwAD.unpack_dual, actual)
|
| 597 |
+
actual_primals = tree_map(
|
| 598 |
+
lambda x: unwrap(x.primal),
|
| 599 |
+
actual,
|
| 600 |
+
is_leaf=lambda x: type(x) is fwAD.UnpackedDualTensor,
|
| 601 |
+
)
|
| 602 |
+
actual_tangents = tree_map(
|
| 603 |
+
lambda x: unwrap(x.tangent),
|
| 604 |
+
actual,
|
| 605 |
+
is_leaf=lambda x: type(x) is fwAD.UnpackedDualTensor,
|
| 606 |
+
)
|
| 607 |
+
assert_equal_fn(actual_primals, expected_primals, equal_nan=True)
|
| 608 |
+
assert_equal_fn(actual_tangents, expected_tangents, equal_nan=True)
|
pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/custom_op_db.py
ADDED
|
@@ -0,0 +1,585 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import torch
|
| 3 |
+
import functools
|
| 4 |
+
from torch.testing import make_tensor
|
| 5 |
+
from torch.testing._internal.opinfo.core import (
|
| 6 |
+
OpInfo,
|
| 7 |
+
SampleInput,
|
| 8 |
+
)
|
| 9 |
+
from torch.testing._internal.common_dtype import all_types_and
|
| 10 |
+
import numpy as np
|
| 11 |
+
from torch.testing._internal.autograd_function_db import (
|
| 12 |
+
sample_inputs_numpy_cube,
|
| 13 |
+
sample_inputs_numpy_mul,
|
| 14 |
+
sample_inputs_numpy_mul_scalar,
|
| 15 |
+
sample_inputs_numpy_sort,
|
| 16 |
+
sample_inputs_numpy_take,
|
| 17 |
+
)
|
| 18 |
+
from torch import Tensor
|
| 19 |
+
from torch.types import Number
|
| 20 |
+
from typing import * # noqa: F403
|
| 21 |
+
|
| 22 |
+
# Note: [custom op db]
|
| 23 |
+
#
|
| 24 |
+
# This is a collection of custom operator test cases written as OpInfos
|
| 25 |
+
# so they can easily be consumed by OpInfo-based tests to check if subsystems
|
| 26 |
+
# support them correctly.
|
| 27 |
+
|
| 28 |
+
def to_numpy(tensor):
|
| 29 |
+
return tensor.cpu().numpy()
|
| 30 |
+
|
| 31 |
+
@torch.library.custom_op("_torch_testing::numpy_cube", mutates_args=())
|
| 32 |
+
def numpy_cube(x: Tensor) -> tuple[Tensor, Tensor]:
|
| 33 |
+
x_np = to_numpy(x)
|
| 34 |
+
dx = torch.tensor(3 * x_np ** 2, device=x.device)
|
| 35 |
+
return torch.tensor(x_np ** 3, device=x.device), dx
|
| 36 |
+
|
| 37 |
+
@numpy_cube.register_fake
|
| 38 |
+
def _(x):
|
| 39 |
+
return x.clone(), x.clone()
|
| 40 |
+
|
| 41 |
+
def numpy_cube_setup_context(ctx, inputs, output):
|
| 42 |
+
x, = inputs
|
| 43 |
+
_cube, dx = output
|
| 44 |
+
ctx.save_for_backward(x, dx)
|
| 45 |
+
|
| 46 |
+
def numpy_cube_backward(ctx, grad_out, grad_dx):
|
| 47 |
+
x, dx = ctx.saved_tensors
|
| 48 |
+
grad_x = numpy_mul(grad_out, dx) + 6 * numpy_mul(grad_dx, x)
|
| 49 |
+
return grad_x
|
| 50 |
+
|
| 51 |
+
numpy_cube.register_autograd(numpy_cube_backward, setup_context=numpy_cube_setup_context)
|
| 52 |
+
|
| 53 |
+
def numpy_cube_vmap(info, in_dims, x):
|
| 54 |
+
result = numpy_cube(x)
|
| 55 |
+
return result, (in_dims[0], in_dims[0])
|
| 56 |
+
|
| 57 |
+
numpy_cube.register_vmap(numpy_cube_vmap)
|
| 58 |
+
|
| 59 |
+
@torch.library.custom_op("_torch_testing::numpy_mul", mutates_args=())
|
| 60 |
+
def numpy_mul(x: Tensor, y: Tensor) -> Tensor:
|
| 61 |
+
return torch.tensor(to_numpy(x) * to_numpy(y), device=x.device)
|
| 62 |
+
|
| 63 |
+
@numpy_mul.register_fake
|
| 64 |
+
def _(x, y):
|
| 65 |
+
assert x.device == y.device
|
| 66 |
+
return (x * y).contiguous()
|
| 67 |
+
|
| 68 |
+
def numpy_mul_setup_context(ctx, inputs, output):
|
| 69 |
+
ctx.save_for_backward(*inputs)
|
| 70 |
+
|
| 71 |
+
def numpy_mul_backward(ctx, grad_out):
|
| 72 |
+
x, y = ctx.saved_tensors
|
| 73 |
+
grad_x = grad_out * y if ctx.needs_input_grad[0] else None
|
| 74 |
+
grad_y = grad_out * x if ctx.needs_input_grad[1] else None
|
| 75 |
+
return grad_x, grad_y
|
| 76 |
+
|
| 77 |
+
numpy_mul.register_autograd(numpy_mul_backward, setup_context=numpy_mul_setup_context)
|
| 78 |
+
|
| 79 |
+
def numpy_mul_vmap(info, in_dims, x, y):
|
| 80 |
+
x_bdim, y_bdim = in_dims
|
| 81 |
+
x = x.movedim(x_bdim, -1) if x_bdim is not None else x.unsqueeze(-1)
|
| 82 |
+
y = y.movedim(y_bdim, -1) if y_bdim is not None else y.unsqueeze(-1)
|
| 83 |
+
result = x * y
|
| 84 |
+
result = result.movedim(-1, 0)
|
| 85 |
+
return result, 0
|
| 86 |
+
|
| 87 |
+
numpy_mul.register_vmap(numpy_mul_vmap)
|
| 88 |
+
|
| 89 |
+
@torch.library.custom_op("_torch_testing::numpy_mul_scalar", mutates_args=())
|
| 90 |
+
def numpy_mul_scalar(x: Tensor, *, scalar: float) -> Tensor:
|
| 91 |
+
return torch.tensor(to_numpy(x) * scalar, device=x.device)
|
| 92 |
+
|
| 93 |
+
@numpy_mul_scalar.register_fake
|
| 94 |
+
def _(x, *, scalar):
|
| 95 |
+
return (x * scalar).contiguous()
|
| 96 |
+
|
| 97 |
+
def numpy_mul_scalar_setup_context(ctx, inputs, keyword_only_inputs, output):
|
| 98 |
+
ctx.scalar = keyword_only_inputs["scalar"]
|
| 99 |
+
|
| 100 |
+
def numpy_mul_scalar_backward(ctx, grad_out):
|
| 101 |
+
grad_x = grad_out * ctx.scalar
|
| 102 |
+
return grad_x
|
| 103 |
+
|
| 104 |
+
numpy_mul_scalar.register_autograd(numpy_mul_scalar_backward, setup_context=numpy_mul_scalar_setup_context)
|
| 105 |
+
|
| 106 |
+
def numpy_mul_scalar_vmap(info, in_dims, x, *, scalar):
|
| 107 |
+
x_bdim, = in_dims
|
| 108 |
+
x = x.movedim(x_bdim, -1) if x_bdim is not None else x.unsqueeze(-1)
|
| 109 |
+
result = x * scalar
|
| 110 |
+
result = result.movedim(-1, 0)
|
| 111 |
+
return result, 0
|
| 112 |
+
|
| 113 |
+
numpy_mul_scalar.register_vmap(numpy_mul_scalar_vmap)
|
| 114 |
+
|
| 115 |
+
@torch.library.custom_op("_torch_testing::numpy_sort", mutates_args=())
|
| 116 |
+
def numpy_sort(x: Tensor, dim: int) -> tuple[Tensor, Tensor, Tensor]:
|
| 117 |
+
device = x.device
|
| 118 |
+
x = to_numpy(x)
|
| 119 |
+
ind = np.argsort(x, axis=dim)
|
| 120 |
+
ind_inv = np.argsort(ind, axis=dim)
|
| 121 |
+
result = np.take_along_axis(x, ind, axis=dim)
|
| 122 |
+
return (
|
| 123 |
+
torch.tensor(result, device=device),
|
| 124 |
+
torch.tensor(ind, device=device),
|
| 125 |
+
torch.tensor(ind_inv, device=device),
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
@numpy_sort.register_fake
|
| 129 |
+
def _(x, dim):
|
| 130 |
+
return torch.empty_like(x), torch.empty_like(x, dtype=torch.long), torch.empty_like(x, dtype=torch.long)
|
| 131 |
+
|
| 132 |
+
def numpy_sort_setup_context(ctx, inputs, output):
|
| 133 |
+
_out, ind, ind_inv = output
|
| 134 |
+
ctx.dim = inputs[1]
|
| 135 |
+
ctx.save_for_backward(ind, ind_inv)
|
| 136 |
+
ctx.mark_non_differentiable(ind, ind_inv)
|
| 137 |
+
|
| 138 |
+
def numpy_sort_backward(ctx, grad_out, grad_ind, grad_ind_inv):
|
| 139 |
+
ind, ind_inv = ctx.saved_tensors
|
| 140 |
+
return numpy_take(grad_out, ind_inv, ind, ctx.dim), None
|
| 141 |
+
|
| 142 |
+
numpy_sort.register_autograd(numpy_sort_backward, setup_context=numpy_sort_setup_context)
|
| 143 |
+
|
| 144 |
+
def numpy_sort_vmap(info, in_dims, x, dim):
|
| 145 |
+
x_bdim, _ = in_dims
|
| 146 |
+
x = x.movedim(x_bdim, 0)
|
| 147 |
+
dim = dim if dim >= 0 else dim + x.dim() - 1
|
| 148 |
+
result = numpy_sort(x, dim + 1)
|
| 149 |
+
return result, (0, 0, 0)
|
| 150 |
+
|
| 151 |
+
numpy_sort.register_vmap(numpy_sort_vmap)
|
| 152 |
+
|
| 153 |
+
@torch.library.custom_op("_torch_testing::numpy_take", mutates_args=())
|
| 154 |
+
def numpy_take(x: Tensor, ind: Tensor, ind_inv: Tensor, dim: int) -> Tensor:
|
| 155 |
+
device = x.device
|
| 156 |
+
x = to_numpy(x)
|
| 157 |
+
ind = to_numpy(ind)
|
| 158 |
+
return torch.tensor(np.take_along_axis(x, ind, dim), device=device)
|
| 159 |
+
|
| 160 |
+
@numpy_take.register_fake
|
| 161 |
+
def _(x, ind, ind_inv, dim):
|
| 162 |
+
assert x.device == ind.device
|
| 163 |
+
assert x.device == ind_inv.device
|
| 164 |
+
assert ind.dtype == torch.long
|
| 165 |
+
assert ind_inv.dtype == torch.long
|
| 166 |
+
return torch.empty_like(x)
|
| 167 |
+
|
| 168 |
+
def numpy_take_setup_context(ctx, inputs, output):
|
| 169 |
+
_x, ind, ind_inv, dim = inputs
|
| 170 |
+
ctx.dim = dim
|
| 171 |
+
ctx.save_for_backward(ind, ind_inv)
|
| 172 |
+
|
| 173 |
+
def numpy_take_backward(ctx, grad_out):
|
| 174 |
+
ind, ind_inv = ctx.saved_tensors
|
| 175 |
+
grad_x = numpy_take(grad_out, ind_inv, ind, ctx.dim)
|
| 176 |
+
return grad_x, None, None, None
|
| 177 |
+
|
| 178 |
+
numpy_take.register_autograd(numpy_take_backward, setup_context=numpy_take_setup_context)
|
| 179 |
+
|
| 180 |
+
def numpy_take_vmap(info, in_dims, x, ind, ind_inv, dim):
|
| 181 |
+
x_bdim, ind_bdim, ind_inv_bdim, _ = in_dims
|
| 182 |
+
|
| 183 |
+
# wrap dim
|
| 184 |
+
logical_dim = x.dim() if x_bdim is None else x_bdim - 1
|
| 185 |
+
dim = dim if dim >= 0 else dim + logical_dim
|
| 186 |
+
|
| 187 |
+
def expand_bdim(x, x_bdim):
|
| 188 |
+
if x_bdim is None:
|
| 189 |
+
return x.expand(info.batch_size, *x.shape)
|
| 190 |
+
return x.movedim(x_bdim, 0)
|
| 191 |
+
|
| 192 |
+
x = expand_bdim(x, x_bdim)
|
| 193 |
+
ind = expand_bdim(ind, ind_bdim)
|
| 194 |
+
ind_inv = expand_bdim(ind_inv, ind_inv_bdim)
|
| 195 |
+
|
| 196 |
+
return numpy_take(x, ind, ind_inv, dim + 1), 0
|
| 197 |
+
|
| 198 |
+
numpy_take.register_vmap(numpy_take_vmap)
|
| 199 |
+
|
| 200 |
+
@torch.library.custom_op("_torch_testing::numpy_nonzero", mutates_args=())
|
| 201 |
+
def numpy_nonzero(x: Tensor) -> Tensor:
|
| 202 |
+
x_np = to_numpy(x)
|
| 203 |
+
res = np.stack(np.nonzero(x_np), axis=1)
|
| 204 |
+
if res.shape[0] <= 1:
|
| 205 |
+
raise RuntimeError("not supported")
|
| 206 |
+
return torch.tensor(res, device=x.device)
|
| 207 |
+
|
| 208 |
+
@numpy_nonzero.register_fake
|
| 209 |
+
def _(x):
|
| 210 |
+
ctx = torch._custom_op.impl.get_ctx()
|
| 211 |
+
i0 = ctx.create_unbacked_symint()
|
| 212 |
+
shape = [i0, x.dim()]
|
| 213 |
+
result = x.new_empty(shape, dtype=torch.long)
|
| 214 |
+
return result
|
| 215 |
+
|
| 216 |
+
def sample_inputs_numpy_nonzero(opinfo, device, dtype, requires_grad, **kwargs):
|
| 217 |
+
make_arg = functools.partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
|
| 218 |
+
shape = 10
|
| 219 |
+
result = make_arg(shape, low=0.9, high=2)
|
| 220 |
+
mask = make_tensor(shape, low=0, high=2, device=device, dtype=torch.long)
|
| 221 |
+
with torch.no_grad():
|
| 222 |
+
result *= mask
|
| 223 |
+
|
| 224 |
+
yield SampleInput(result, args=())
|
| 225 |
+
|
| 226 |
+
def numpy_nonzero_vmap(info, in_dims, x):
|
| 227 |
+
raise NotImplementedError("Operator is data-dependent and cannot be vmapped.")
|
| 228 |
+
|
| 229 |
+
numpy_nonzero.register_vmap(numpy_nonzero_vmap)
|
| 230 |
+
|
| 231 |
+
@torch.library.custom_op("_torch_testing::numpy_view_copy", mutates_args=())
|
| 232 |
+
def numpy_view_copy(x: Tensor, shape: Sequence[int]) -> Tensor:
|
| 233 |
+
return torch.tensor(np.copy(to_numpy(x).reshape(shape)), device=x.device)
|
| 234 |
+
|
| 235 |
+
@numpy_view_copy.register_fake
|
| 236 |
+
def _(x, shape) -> Tensor:
|
| 237 |
+
return x.clone().view(shape).clone()
|
| 238 |
+
|
| 239 |
+
def numpy_view_copy_setup_context(ctx, inputs, output) -> None:
|
| 240 |
+
ctx.x_shape = inputs[0].shape
|
| 241 |
+
|
| 242 |
+
def numpy_view_copy_backward(ctx, grad_out):
|
| 243 |
+
return torch.ops._torch_testing.numpy_view_copy(grad_out, ctx.x_shape), None
|
| 244 |
+
|
| 245 |
+
numpy_view_copy.register_autograd(numpy_view_copy_backward, setup_context=numpy_view_copy_setup_context)
|
| 246 |
+
|
| 247 |
+
def numpy_view_copy_vmap(info, in_dims, x, shape):
|
| 248 |
+
x_bdim, _ = in_dims
|
| 249 |
+
x = x.movedim(x_bdim, 0)
|
| 250 |
+
x_shape = x.shape[0]
|
| 251 |
+
batch_shape = (x_shape, *shape)
|
| 252 |
+
result = numpy_view_copy(x, batch_shape)
|
| 253 |
+
return result, 0
|
| 254 |
+
|
| 255 |
+
numpy_view_copy.register_vmap(numpy_view_copy_vmap)
|
| 256 |
+
|
| 257 |
+
def sample_inputs_numpy_view_copy(opinfo, device, dtype, requires_grad, **kwargs):
|
| 258 |
+
make_arg = functools.partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
|
| 259 |
+
result = make_arg(2, 3, 4, low=0.9, high=2)
|
| 260 |
+
yield SampleInput(result, args=([2, 12],))
|
| 261 |
+
|
| 262 |
+
@torch.library.custom_op('_torch_testing::numpy_cat', mutates_args=())
|
| 263 |
+
def numpy_cat(xs: Sequence[Tensor], dim: int) -> Tensor:
|
| 264 |
+
assert len(xs) > 0
|
| 265 |
+
assert all(x.device == xs[0].device for x in xs)
|
| 266 |
+
assert all(x.dtype == xs[0].dtype for x in xs)
|
| 267 |
+
np_xs = [to_numpy(x) for x in xs]
|
| 268 |
+
np_out = np.concatenate(np_xs, axis=dim)
|
| 269 |
+
return torch.tensor(np_out, device=xs[0].device)
|
| 270 |
+
|
| 271 |
+
@numpy_cat.register_fake
|
| 272 |
+
def _(xs, dim):
|
| 273 |
+
assert len(xs) > 0
|
| 274 |
+
assert all(x.device == xs[0].device for x in xs)
|
| 275 |
+
assert all(x.dtype == xs[0].dtype for x in xs)
|
| 276 |
+
return torch.cat(xs, dim=dim)
|
| 277 |
+
|
| 278 |
+
def numpy_cat_setup_context(ctx, inputs, output):
|
| 279 |
+
xs, dim = inputs
|
| 280 |
+
ctx.dim_sizes = [x.shape[dim] for x in xs]
|
| 281 |
+
ctx.dim = dim
|
| 282 |
+
|
| 283 |
+
def numpy_cat_backward(ctx, grad_out):
|
| 284 |
+
dim_sizes = ctx.dim_sizes
|
| 285 |
+
dim = ctx.dim
|
| 286 |
+
|
| 287 |
+
splits = list(np.cumsum(dim_sizes)[:-1])
|
| 288 |
+
grad_xs = torch.ops._torch_testing.numpy_split_copy(grad_out, splits, dim)
|
| 289 |
+
return grad_xs, None
|
| 290 |
+
|
| 291 |
+
numpy_cat.register_autograd(numpy_cat_backward, setup_context=numpy_cat_setup_context)
|
| 292 |
+
|
| 293 |
+
def numpy_cat_vmap(info, in_dims, x, dim):
|
| 294 |
+
x_bdim, = in_dims
|
| 295 |
+
result = numpy_cat(x, dim)
|
| 296 |
+
return result, x_bdim
|
| 297 |
+
|
| 298 |
+
numpy_cat.register_vmap(numpy_cat_vmap)
|
| 299 |
+
|
| 300 |
+
def sample_inputs_numpy_cat(opinfo, device, dtype, requires_grad, **kwargs):
|
| 301 |
+
make_arg = functools.partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
|
| 302 |
+
r0 = make_arg(2, 3, 4, low=0.9, high=2)
|
| 303 |
+
r1 = make_arg(4, 3, 4, low=0.9, high=2)
|
| 304 |
+
r2 = make_arg(5, 3, 4, low=0.9, high=2)
|
| 305 |
+
yield SampleInput([r0, r1, r2], args=(0,))
|
| 306 |
+
|
| 307 |
+
@torch.library.custom_op('_torch_testing::numpy_split_copy', mutates_args=())
|
| 308 |
+
def numpy_split_copy(x: Tensor, splits: Sequence[int], dim: int) -> List[Tensor]:
|
| 309 |
+
x_np = to_numpy(x)
|
| 310 |
+
arrs = np.split(x_np, splits, axis=dim)
|
| 311 |
+
return [torch.tensor(arr, device=x.device, dtype=x.dtype) for arr in arrs]
|
| 312 |
+
|
| 313 |
+
@numpy_split_copy.register_fake
|
| 314 |
+
def _(x, splits, dim):
|
| 315 |
+
return [xi.clone() for xi in torch.tensor_split(x, splits, dim)]
|
| 316 |
+
|
| 317 |
+
def numpy_split_copy_setup_context(ctx, inputs, output):
|
| 318 |
+
_, _, dim = inputs
|
| 319 |
+
ctx.dim = dim
|
| 320 |
+
|
| 321 |
+
def numpy_split_copy_backward(ctx, grad_out):
|
| 322 |
+
result = torch.ops._torch_testing.numpy_cat(grad_out, dim=ctx.dim)
|
| 323 |
+
return result, None, None
|
| 324 |
+
|
| 325 |
+
numpy_split_copy.register_autograd(numpy_split_copy_backward, setup_context=numpy_split_copy_setup_context)
|
| 326 |
+
|
| 327 |
+
def numpy_split_copy_vmap(info, in_dims, x, splits, dim):
|
| 328 |
+
x_bdim, _ , _ = in_dims
|
| 329 |
+
x = x.movedim(x_bdim, 0)
|
| 330 |
+
result = numpy_split_copy(x, splits, dim + 1)
|
| 331 |
+
return result, 0
|
| 332 |
+
|
| 333 |
+
numpy_split_copy.register_vmap(numpy_split_copy_vmap)
|
| 334 |
+
|
| 335 |
+
def sample_inputs_numpy_split_copy(opinfo, device, dtype, requires_grad, **kwargs):
|
| 336 |
+
make_arg = functools.partial(make_tensor, device=device, dtype=dtype, requires_grad=requires_grad)
|
| 337 |
+
x = make_arg(2, 9, low=0.9, high=2)
|
| 338 |
+
yield SampleInput(x, args=([1, 3, 6], 1))
|
| 339 |
+
|
| 340 |
+
@torch.library.custom_op('_torch_testing::numpy_split_copy_with_int', mutates_args=())
|
| 341 |
+
def numpy_split_copy_with_int(x: Tensor, splits: Sequence[int], dim: int) -> tuple[List[Tensor], int]:
|
| 342 |
+
x_np = to_numpy(x)
|
| 343 |
+
arrs = np.split(x_np, splits, axis=dim)
|
| 344 |
+
return [torch.tensor(arr, device=x.device, dtype=x.dtype) for arr in arrs], len(splits)
|
| 345 |
+
|
| 346 |
+
@numpy_split_copy_with_int.register_fake
|
| 347 |
+
def _(x, splits, dim):
|
| 348 |
+
return [xi.clone() for xi in torch.tensor_split(x, splits, dim)], len(splits)
|
| 349 |
+
|
| 350 |
+
def numpy_split_copy_with_int_setup_context(ctx, inputs, output):
|
| 351 |
+
_, _, dim = inputs
|
| 352 |
+
ctx.dim = dim
|
| 353 |
+
|
| 354 |
+
def numpy_split_copy_with_int_backward(ctx, grad_out, _):
|
| 355 |
+
return torch.ops._torch_testing.numpy_cat(grad_out, dim=ctx.dim), None, None
|
| 356 |
+
|
| 357 |
+
numpy_split_copy_with_int.register_autograd(
|
| 358 |
+
numpy_split_copy_with_int_backward,
|
| 359 |
+
setup_context=numpy_split_copy_with_int_setup_context)
|
| 360 |
+
|
| 361 |
+
def numpy_split_copy_with_int_vmap(info, in_dims, x, splits, dim):
|
| 362 |
+
x_bdim, _ , _ = in_dims
|
| 363 |
+
x = x.movedim(x_bdim, 0)
|
| 364 |
+
result, len_split = numpy_split_copy_with_int(x, splits, dim + 1)
|
| 365 |
+
return (result, len_split), ([0 for _ in range(len(result))], None)
|
| 366 |
+
|
| 367 |
+
numpy_split_copy_with_int.register_vmap(numpy_split_copy_with_int_vmap)
|
| 368 |
+
|
| 369 |
+
@torch.library.custom_op("_torch_testing::numpy_nms", mutates_args=())
|
| 370 |
+
def numpy_nms(boxes: Tensor, scores: Tensor, iou_threshold: Number) -> Tensor:
|
| 371 |
+
# Adapted from Ross Girshick's fast-rcnn implementation at
|
| 372 |
+
# https://github.com/rbgirshick/fast-rcnn/blob/master/lib/utils/nms.py
|
| 373 |
+
assert boxes.device == scores.device
|
| 374 |
+
device = boxes.device
|
| 375 |
+
|
| 376 |
+
boxes = to_numpy(boxes)
|
| 377 |
+
scores = to_numpy(scores)
|
| 378 |
+
|
| 379 |
+
N = boxes.shape[0]
|
| 380 |
+
assert boxes.shape == (N, 4)
|
| 381 |
+
assert scores.shape == (N,)
|
| 382 |
+
|
| 383 |
+
x1 = boxes[:, 0]
|
| 384 |
+
y1 = boxes[:, 1]
|
| 385 |
+
x2 = boxes[:, 2]
|
| 386 |
+
y2 = boxes[:, 3]
|
| 387 |
+
|
| 388 |
+
areas = (x2 - x1 + 1) * (y2 - y1 + 1)
|
| 389 |
+
order = scores.argsort()[::-1]
|
| 390 |
+
|
| 391 |
+
keep = []
|
| 392 |
+
while order.size > 0:
|
| 393 |
+
i = order[0]
|
| 394 |
+
keep.append(i)
|
| 395 |
+
xx1 = np.maximum(x1[i], x1[order[1:]])
|
| 396 |
+
yy1 = np.maximum(y1[i], y1[order[1:]])
|
| 397 |
+
xx2 = np.minimum(x2[i], x2[order[1:]])
|
| 398 |
+
yy2 = np.minimum(y2[i], y2[order[1:]])
|
| 399 |
+
|
| 400 |
+
w = np.maximum(0.0, xx2 - xx1 + 1)
|
| 401 |
+
h = np.maximum(0.0, yy2 - yy1 + 1)
|
| 402 |
+
inter = w * h
|
| 403 |
+
ovr = inter / (areas[i] + areas[order[1:]] - inter)
|
| 404 |
+
|
| 405 |
+
inds = np.where(ovr <= iou_threshold)[0]
|
| 406 |
+
order = order[inds + 1]
|
| 407 |
+
|
| 408 |
+
result = torch.tensor(np.stack(keep), device=device)
|
| 409 |
+
# Needed for data-dependent condition :(
|
| 410 |
+
assert result.size(0) >= 2
|
| 411 |
+
return result
|
| 412 |
+
|
| 413 |
+
@numpy_nms.register_fake
|
| 414 |
+
def _(boxes, scores, iou_threshold):
|
| 415 |
+
assert boxes.device == scores.device
|
| 416 |
+
N = boxes.shape[0]
|
| 417 |
+
assert boxes.shape == (N, 4)
|
| 418 |
+
assert scores.shape == (N,)
|
| 419 |
+
|
| 420 |
+
ctx = torch._custom_op.impl.get_ctx()
|
| 421 |
+
i0 = ctx.create_unbacked_symint()
|
| 422 |
+
result = boxes.new_empty([i0], dtype=torch.int64)
|
| 423 |
+
return result
|
| 424 |
+
|
| 425 |
+
def numpy_nms_vmap(info, in_dims, boxes, scores, iou_threshold):
|
| 426 |
+
raise NotImplementedError("Operator is data-dependent and cannot be vmapped.")
|
| 427 |
+
|
| 428 |
+
numpy_nms.register_vmap(numpy_nms_vmap)
|
| 429 |
+
|
| 430 |
+
def sample_inputs_numpy_nms(opinfo, device, dtype, requires_grad, **kwargs):
|
| 431 |
+
make_arg = functools.partial(make_tensor, device=device, dtype=dtype)
|
| 432 |
+
N = 64
|
| 433 |
+
xs = make_arg([N], low=0, high=28)
|
| 434 |
+
dx = make_arg([N], low=0, high=4)
|
| 435 |
+
ys = make_arg([N], low=0, high=28)
|
| 436 |
+
dy = make_arg([N], low=0, high=4)
|
| 437 |
+
boxes = torch.stack([xs, ys, xs + dx, ys + dy], dim=1).requires_grad_(requires_grad)
|
| 438 |
+
scores = make_arg([N], low=0, high=1, requires_grad=requires_grad)
|
| 439 |
+
iou_threshold = make_arg([], low=0, high=1).item()
|
| 440 |
+
|
| 441 |
+
yield SampleInput(boxes, args=(scores, iou_threshold))
|
| 442 |
+
|
| 443 |
+
custom_op_db = [
|
| 444 |
+
OpInfo(
|
| 445 |
+
'NumpyCubeCustomOp',
|
| 446 |
+
op=numpy_cube._opoverload,
|
| 447 |
+
sample_inputs_func=sample_inputs_numpy_cube,
|
| 448 |
+
dtypes=all_types_and(torch.bool, torch.half),
|
| 449 |
+
supports_out=False,
|
| 450 |
+
),
|
| 451 |
+
OpInfo(
|
| 452 |
+
'NumpyMulCustomOp',
|
| 453 |
+
op=numpy_mul._opoverload,
|
| 454 |
+
sample_inputs_func=sample_inputs_numpy_mul,
|
| 455 |
+
dtypes=all_types_and(torch.bool, torch.half),
|
| 456 |
+
supports_out=False,
|
| 457 |
+
),
|
| 458 |
+
OpInfo(
|
| 459 |
+
'NumpyMulScalarCustomOp',
|
| 460 |
+
op=numpy_mul_scalar._opoverload,
|
| 461 |
+
sample_inputs_func=sample_inputs_numpy_mul_scalar,
|
| 462 |
+
dtypes=all_types_and(torch.bool, torch.half),
|
| 463 |
+
supports_out=False,
|
| 464 |
+
),
|
| 465 |
+
OpInfo(
|
| 466 |
+
'NumpySortCustomOp',
|
| 467 |
+
op=numpy_sort._opoverload,
|
| 468 |
+
sample_inputs_func=sample_inputs_numpy_sort,
|
| 469 |
+
dtypes=all_types_and(torch.bool, torch.half),
|
| 470 |
+
supports_out=False,
|
| 471 |
+
),
|
| 472 |
+
OpInfo(
|
| 473 |
+
'NumpyTakeCustomOp',
|
| 474 |
+
op=numpy_take._opoverload,
|
| 475 |
+
sample_inputs_func=sample_inputs_numpy_take,
|
| 476 |
+
dtypes=all_types_and(torch.bool, torch.half),
|
| 477 |
+
supports_out=False,
|
| 478 |
+
),
|
| 479 |
+
OpInfo(
|
| 480 |
+
'NumpyNonzeroCustomOp',
|
| 481 |
+
op=numpy_nonzero._opoverload,
|
| 482 |
+
sample_inputs_func=sample_inputs_numpy_nonzero,
|
| 483 |
+
dtypes=all_types_and(torch.bool, torch.half),
|
| 484 |
+
supports_autograd=False,
|
| 485 |
+
supports_out=False,
|
| 486 |
+
),
|
| 487 |
+
OpInfo(
|
| 488 |
+
'NumpyNMSCustomOp',
|
| 489 |
+
op=torch.ops._torch_testing.numpy_nms,
|
| 490 |
+
sample_inputs_func=sample_inputs_numpy_nms,
|
| 491 |
+
dtypes=all_types_and(torch.bool, torch.half),
|
| 492 |
+
supports_autograd=False,
|
| 493 |
+
supports_out=False,
|
| 494 |
+
),
|
| 495 |
+
OpInfo(
|
| 496 |
+
'NumpyViewCopyCustomOp',
|
| 497 |
+
op=torch.ops._torch_testing.numpy_view_copy,
|
| 498 |
+
sample_inputs_func=sample_inputs_numpy_view_copy,
|
| 499 |
+
dtypes=all_types_and(torch.bool, torch.half),
|
| 500 |
+
supports_autograd=True,
|
| 501 |
+
supports_out=False,
|
| 502 |
+
),
|
| 503 |
+
OpInfo(
|
| 504 |
+
'NumpyCatCustomOp',
|
| 505 |
+
op=torch.ops._torch_testing.numpy_cat,
|
| 506 |
+
sample_inputs_func=sample_inputs_numpy_cat,
|
| 507 |
+
dtypes=all_types_and(torch.bool, torch.half),
|
| 508 |
+
supports_autograd=True,
|
| 509 |
+
check_batched_grad=False,
|
| 510 |
+
check_batched_gradgrad=False,
|
| 511 |
+
supports_out=False,
|
| 512 |
+
),
|
| 513 |
+
OpInfo(
|
| 514 |
+
'NumpySplitCopyCustomOp',
|
| 515 |
+
op=torch.ops._torch_testing.numpy_split_copy,
|
| 516 |
+
sample_inputs_func=sample_inputs_numpy_split_copy,
|
| 517 |
+
dtypes=all_types_and(torch.bool, torch.half),
|
| 518 |
+
supports_autograd=True,
|
| 519 |
+
check_batched_grad=False,
|
| 520 |
+
check_batched_gradgrad=False,
|
| 521 |
+
supports_out=False,
|
| 522 |
+
),
|
| 523 |
+
OpInfo(
|
| 524 |
+
'NumpySplitCopyWithIntCustomOp',
|
| 525 |
+
op=torch.ops._torch_testing.numpy_split_copy_with_int,
|
| 526 |
+
sample_inputs_func=sample_inputs_numpy_split_copy,
|
| 527 |
+
dtypes=all_types_and(torch.bool, torch.half),
|
| 528 |
+
gradcheck_wrapper=lambda op, *args, **kwargs: op(*args, **kwargs)[0],
|
| 529 |
+
supports_autograd=True,
|
| 530 |
+
check_batched_grad=False,
|
| 531 |
+
check_batched_gradgrad=False,
|
| 532 |
+
supports_out=False,
|
| 533 |
+
),
|
| 534 |
+
]
|
| 535 |
+
|
| 536 |
+
|
| 537 |
+
# ==============================================================
|
| 538 |
+
# some mechanical test cases
|
| 539 |
+
# ==============================================================
|
| 540 |
+
|
| 541 |
+
lib = torch.library.Library("_torch_testing", "FRAGMENT") # noqa: TOR901
|
| 542 |
+
|
| 543 |
+
lib.define("source0(Tensor x) -> Tensor")
|
| 544 |
+
|
| 545 |
+
@torch.library.register_fake("_torch_testing::source0", lib=lib)
|
| 546 |
+
def _(x):
|
| 547 |
+
return x.clone()
|
| 548 |
+
|
| 549 |
+
lib.define("source1(Tensor x) -> Tensor")
|
| 550 |
+
|
| 551 |
+
def source1_fake(x):
|
| 552 |
+
return x.clone()
|
| 553 |
+
|
| 554 |
+
torch.library.register_fake("_torch_testing::source1", source1_fake, lib=lib)
|
| 555 |
+
|
| 556 |
+
lib.define("source2(Tensor x) -> Tensor")
|
| 557 |
+
|
| 558 |
+
@torch.library.register_fake("_torch_testing::source2", lib=lib)
|
| 559 |
+
def _(x):
|
| 560 |
+
return x.clone()
|
| 561 |
+
|
| 562 |
+
lib.define("source3(Tensor x) -> Tensor")
|
| 563 |
+
|
| 564 |
+
def source3_fake(x):
|
| 565 |
+
return x.clone()
|
| 566 |
+
|
| 567 |
+
torch.library.register_fake("_torch_testing::source3", source3_fake, lib=lib)
|
| 568 |
+
|
| 569 |
+
|
| 570 |
+
@torch.library.custom_op("_torch_testing::source4", mutates_args=())
|
| 571 |
+
def source4(x: Tensor) -> Tensor:
|
| 572 |
+
return x.clone()
|
| 573 |
+
|
| 574 |
+
@source4.register_fake
|
| 575 |
+
def _(x):
|
| 576 |
+
return x.clone()
|
| 577 |
+
|
| 578 |
+
@torch.library.custom_op("_torch_testing::source5", mutates_args=())
|
| 579 |
+
def source5(x: Tensor) -> Tensor:
|
| 580 |
+
return x.clone()
|
| 581 |
+
|
| 582 |
+
def source5_fake(x):
|
| 583 |
+
return x.clone()
|
| 584 |
+
|
| 585 |
+
source5.register_fake(source5_fake)
|
pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/custom_tensor.py
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: ignore-errors
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
from collections import namedtuple
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
import torch.utils._pytree as pytree
|
| 8 |
+
from torch.utils._python_dispatch import return_and_correct_aliasing
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
FancyNamedTuple = namedtuple("FancyNamedTuple", ["foo", "bar"])
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
# A simple tensor subclass that holds a tensor with custom metadata and custom method
|
| 15 |
+
class ConstantExtraMetadataTensor(torch.Tensor):
|
| 16 |
+
@staticmethod
|
| 17 |
+
def __new__(cls, elem):
|
| 18 |
+
shape = elem.shape
|
| 19 |
+
kwargs = {}
|
| 20 |
+
kwargs["strides"] = elem.stride()
|
| 21 |
+
kwargs["storage_offset"] = elem.storage_offset()
|
| 22 |
+
kwargs["device"] = elem.device
|
| 23 |
+
kwargs["layout"] = elem.layout
|
| 24 |
+
kwargs["requires_grad"] = elem.requires_grad
|
| 25 |
+
kwargs["dtype"] = elem.dtype
|
| 26 |
+
return torch.Tensor._make_wrapper_subclass(cls, shape, **kwargs)
|
| 27 |
+
|
| 28 |
+
def __init__(self, elem):
|
| 29 |
+
self.elem = elem
|
| 30 |
+
self.constant_attribute = 4
|
| 31 |
+
|
| 32 |
+
def __repr__(self):
|
| 33 |
+
inner_repr = repr(self.elem)
|
| 34 |
+
return f"CustomTensor({inner_repr})"
|
| 35 |
+
|
| 36 |
+
def get_complicated_metadata(self):
|
| 37 |
+
return FancyNamedTuple(self.constant_attribute, self.constant_attribute)
|
| 38 |
+
|
| 39 |
+
def __tensor_flatten__(self):
|
| 40 |
+
return ["elem"], self.constant_attribute
|
| 41 |
+
|
| 42 |
+
def add_constant(self, a):
|
| 43 |
+
self.constant_attribute += a
|
| 44 |
+
|
| 45 |
+
@staticmethod
|
| 46 |
+
def __tensor_unflatten__(inner_tensors, meta, outer_size, outer_stride):
|
| 47 |
+
assert meta is not None
|
| 48 |
+
elem = inner_tensors["elem"]
|
| 49 |
+
out = ConstantExtraMetadataTensor(elem)
|
| 50 |
+
out.constant_attribute = meta
|
| 51 |
+
return out
|
| 52 |
+
|
| 53 |
+
@classmethod
|
| 54 |
+
def __torch_dispatch__(cls, func, types, args, kwargs):
|
| 55 |
+
if kwargs is None:
|
| 56 |
+
kwargs = {}
|
| 57 |
+
args_inner = pytree.tree_map_only(
|
| 58 |
+
ConstantExtraMetadataTensor, lambda x: x.elem, args
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
kwargs_inner = pytree.tree_map_only(
|
| 62 |
+
ConstantExtraMetadataTensor, lambda x: x.elem, kwargs
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
out_inner = func(*args_inner, **kwargs_inner)
|
| 66 |
+
out_inner_flat, spec = pytree.tree_flatten(out_inner)
|
| 67 |
+
# for aten ops that return non-tensors, just assume that
|
| 68 |
+
# our cust inner tensors return the same value
|
| 69 |
+
out_flat = [
|
| 70 |
+
ConstantExtraMetadataTensor(o_inner)
|
| 71 |
+
if isinstance(o_inner, torch.Tensor)
|
| 72 |
+
else o_inner
|
| 73 |
+
for o_inner in out_inner_flat
|
| 74 |
+
]
|
| 75 |
+
out = pytree.tree_unflatten(out_flat, spec)
|
| 76 |
+
return return_and_correct_aliasing(func, args, kwargs, out)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
# A simple tensor subclass that always returns plain tensor during __torch_dispatch__
|
| 80 |
+
# It is similar to TwoTensor and is used to simulate torchao quantized tensors
|
| 81 |
+
class CustomTensorPlainOut(torch.Tensor):
|
| 82 |
+
@staticmethod
|
| 83 |
+
def __new__(cls, elem1, elem2):
|
| 84 |
+
shape = elem1.shape
|
| 85 |
+
kwargs = {}
|
| 86 |
+
kwargs["strides"] = elem1.stride()
|
| 87 |
+
kwargs["storage_offset"] = elem1.storage_offset()
|
| 88 |
+
kwargs["device"] = elem1.device
|
| 89 |
+
kwargs["layout"] = elem1.layout
|
| 90 |
+
kwargs["requires_grad"] = elem1.requires_grad
|
| 91 |
+
kwargs["dtype"] = elem1.dtype
|
| 92 |
+
return torch.Tensor._make_wrapper_subclass(cls, shape, **kwargs)
|
| 93 |
+
|
| 94 |
+
def __init__(self, elem1, elem2):
|
| 95 |
+
self.elem1 = elem1
|
| 96 |
+
self.elem2 = elem2
|
| 97 |
+
|
| 98 |
+
def get_elem(self):
|
| 99 |
+
return self.elem1
|
| 100 |
+
|
| 101 |
+
def __repr__(self):
|
| 102 |
+
inner_repr_1 = repr(self.elem1)
|
| 103 |
+
inner_repr_2 = repr(self.elem2)
|
| 104 |
+
return f"CustomTensorPlainOut({inner_repr_1}, {inner_repr_2})"
|
| 105 |
+
|
| 106 |
+
def __tensor_flatten__(self):
|
| 107 |
+
return ["elem1", "elem2"], None
|
| 108 |
+
|
| 109 |
+
@staticmethod
|
| 110 |
+
def __tensor_unflatten__(inner_tensors, meta, outer_size, outer_stride):
|
| 111 |
+
elem1 = inner_tensors["elem1"]
|
| 112 |
+
elem2 = inner_tensors["elem2"]
|
| 113 |
+
out = CustomTensorPlainOut(elem1, elem2)
|
| 114 |
+
return out
|
| 115 |
+
|
| 116 |
+
@classmethod
|
| 117 |
+
def __torch_dispatch__(cls, func, types, args, kwargs):
|
| 118 |
+
# Don't use this tensor with view ops
|
| 119 |
+
if kwargs is None:
|
| 120 |
+
kwargs = {}
|
| 121 |
+
args_inner_1 = pytree.tree_map_only(
|
| 122 |
+
CustomTensorPlainOut, lambda x: x.elem1, args
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
kwargs_inner_1 = pytree.tree_map_only(
|
| 126 |
+
CustomTensorPlainOut, lambda x: x.elem1, kwargs
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
args_inner_2 = pytree.tree_map_only(
|
| 130 |
+
CustomTensorPlainOut, lambda x: x.elem2, args
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
kwargs_inner_2 = pytree.tree_map_only(
|
| 134 |
+
CustomTensorPlainOut, lambda x: x.elem2, kwargs
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
out_inner_1 = func(*args_inner_1, **kwargs_inner_1)
|
| 138 |
+
out_inner_2 = func(*args_inner_2, **kwargs_inner_2)
|
| 139 |
+
|
| 140 |
+
out_inner_flat_1, spec = pytree.tree_flatten(out_inner_1)
|
| 141 |
+
out_inner_flat_2, spec = pytree.tree_flatten(out_inner_2)
|
| 142 |
+
|
| 143 |
+
if func.is_view:
|
| 144 |
+
new_out = pytree.tree_unflatten(
|
| 145 |
+
(
|
| 146 |
+
CustomTensorPlainOut(tensor1, tensor2)
|
| 147 |
+
for tensor1, tensor2 in zip(out_inner_flat_1, out_inner_flat_2)
|
| 148 |
+
),
|
| 149 |
+
spec,
|
| 150 |
+
)
|
| 151 |
+
return return_and_correct_aliasing(func, args, kwargs, new_out)
|
| 152 |
+
|
| 153 |
+
out_new = (
|
| 154 |
+
out_inner_flat_1[ix] + out_inner_flat_2[ix]
|
| 155 |
+
for ix in range(len(out_inner_flat_1))
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
return pytree.tree_unflatten(out_new, spec)
|
pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/data/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
# mypy: ignore-errors
|
pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/data/network1.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: ignore-errors
|
| 2 |
+
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class Net(nn.Module):
|
| 7 |
+
|
| 8 |
+
def __init__(self) -> None:
|
| 9 |
+
super().__init__()
|
| 10 |
+
self.linear = nn.Linear(10, 20)
|
pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/data/network2.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: ignore-errors
|
| 2 |
+
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class Net(nn.Module):
|
| 7 |
+
|
| 8 |
+
def __init__(self) -> None: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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: ignore-errors
|
| 2 |
+
|
| 3 |
+
import re
|
| 4 |
+
import sys
|
| 5 |
+
import time
|
| 6 |
+
from functools import partial, wraps
|
| 7 |
+
|
| 8 |
+
import torch.distributed as dist
|
| 9 |
+
import torch.distributed.rpc as rpc
|
| 10 |
+
from torch.distributed.rpc import _rref_context_get_debug_info
|
| 11 |
+
from torch.testing._internal.common_utils import FILE_SCHEMA, TEST_WITH_TSAN
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
if not dist.is_available():
|
| 15 |
+
print("c10d not available, skipping tests", file=sys.stderr)
|
| 16 |
+
sys.exit(0)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
INIT_METHOD_TEMPLATE = FILE_SCHEMA + "{file_name}"
|
| 20 |
+
|
| 21 |
+
def dist_init(
|
| 22 |
+
old_test_method=None,
|
| 23 |
+
setup_rpc: bool = True,
|
| 24 |
+
clean_shutdown: bool = True,
|
| 25 |
+
faulty_messages=None,
|
| 26 |
+
messages_to_delay=None,
|
| 27 |
+
):
|
| 28 |
+
"""
|
| 29 |
+
We use this decorator for setting up and tearing down state since
|
| 30 |
+
MultiProcessTestCase runs each `test*` method in a separate process and
|
| 31 |
+
each process just runs the `test*` method without actually calling
|
| 32 |
+
'setUp' and 'tearDown' methods of unittest.
|
| 33 |
+
|
| 34 |
+
Note: pass the string representation of MessageTypes that should be used
|
| 35 |
+
with the faulty agent's send function. By default, all retriable messages
|
| 36 |
+
("RREF_FORK_REQUEST", "RREF_CHILD_ACCEPT", "RREF_USER_DELETE",
|
| 37 |
+
"CLEANUP_AUTOGRAD_CONTEXT_REQ") will use the faulty send (this default is
|
| 38 |
+
set from faulty_rpc_agent_test_fixture.py).
|
| 39 |
+
"""
|
| 40 |
+
# If we use dist_init without arguments (ex: @dist_init), old_test_method is
|
| 41 |
+
# appropriately set and we return the wrapper appropriately. On the other
|
| 42 |
+
# hand if dist_init has arguments (ex: @dist_init(clean_shutdown=False)),
|
| 43 |
+
# old_test_method is None and we return a functools.partial which is the real
|
| 44 |
+
# decorator that is used and as a result we recursively call dist_init with
|
| 45 |
+
# old_test_method and the rest of the arguments appropriately set.
|
| 46 |
+
if old_test_method is None:
|
| 47 |
+
return partial(
|
| 48 |
+
dist_init,
|
| 49 |
+
setup_rpc=setup_rpc,
|
| 50 |
+
clean_shutdown=clean_shutdown,
|
| 51 |
+
faulty_messages=faulty_messages,
|
| 52 |
+
messages_to_delay=messages_to_delay,
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
@wraps(old_test_method)
|
| 56 |
+
def new_test_method(self, *arg, **kwargs):
|
| 57 |
+
# Setting _ignore_rref_leak to make sure OwnerRRefs are properly deleted
|
| 58 |
+
# in tests.
|
| 59 |
+
import torch.distributed.rpc.api as api
|
| 60 |
+
|
| 61 |
+
api._ignore_rref_leak = False
|
| 62 |
+
self.worker_id = self.rank
|
| 63 |
+
self.setup_fault_injection(faulty_messages, messages_to_delay)
|
| 64 |
+
|
| 65 |
+
rpc_backend_options = self.rpc_backend_options
|
| 66 |
+
if setup_rpc:
|
| 67 |
+
if TEST_WITH_TSAN:
|
| 68 |
+
# TSAN runs much slower.
|
| 69 |
+
rpc_backend_options.rpc_timeout = rpc.constants.DEFAULT_RPC_TIMEOUT_SEC * 5
|
| 70 |
+
rpc.constants.DEFAULT_SHUTDOWN_TIMEOUT = 60
|
| 71 |
+
|
| 72 |
+
rpc.init_rpc(
|
| 73 |
+
name=f"worker{self.rank:d}",
|
| 74 |
+
backend=self.rpc_backend,
|
| 75 |
+
rank=self.rank,
|
| 76 |
+
world_size=self.world_size,
|
| 77 |
+
rpc_backend_options=rpc_backend_options,
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
return_value = old_test_method(self, *arg, **kwargs)
|
| 81 |
+
|
| 82 |
+
if setup_rpc:
|
| 83 |
+
rpc.shutdown(graceful=clean_shutdown)
|
| 84 |
+
|
| 85 |
+
return return_value
|
| 86 |
+
|
| 87 |
+
return new_test_method
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def noop() -> None:
|
| 91 |
+
pass
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def wait_until_node_failure(rank: int, expected_error_regex: str = ".*") -> str:
|
| 95 |
+
"""
|
| 96 |
+
Loops until an RPC to the given rank fails. This is used to
|
| 97 |
+
indicate that the node has failed in unit tests.
|
| 98 |
+
Args:
|
| 99 |
+
rank (int): Rank of the node expected to fail
|
| 100 |
+
expected_error_regex (optional, str): Regex of exception message expected. Useful to ensure a specific failure
|
| 101 |
+
occurs, not just any.
|
| 102 |
+
"""
|
| 103 |
+
while True:
|
| 104 |
+
try:
|
| 105 |
+
rpc.rpc_sync(f"worker{rank}", noop, args=())
|
| 106 |
+
time.sleep(0.1)
|
| 107 |
+
except Exception as e:
|
| 108 |
+
if re.search(pattern=expected_error_regex, string=str(e)):
|
| 109 |
+
return str(e)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def wait_until_pending_futures_and_users_flushed(timeout: int = 20) -> None:
|
| 113 |
+
"""
|
| 114 |
+
The RRef protocol holds forkIds of rrefs in a map until those forks are
|
| 115 |
+
confirmed by the owner. The message confirming the fork may arrive after
|
| 116 |
+
our tests check whether this map is empty, which leads to failures and
|
| 117 |
+
flaky tests. to_here also does not guarantee that we have finished
|
| 118 |
+
processind the owner's confirmation message for the RRef. This function
|
| 119 |
+
loops until the map is empty, which means the messages have been received
|
| 120 |
+
as processed. Call this function before asserting the map returned by
|
| 121 |
+
_get_debug_info is empty.
|
| 122 |
+
"""
|
| 123 |
+
start = time.time()
|
| 124 |
+
while True:
|
| 125 |
+
debug_info = _rref_context_get_debug_info()
|
| 126 |
+
num_pending_futures = int(debug_info["num_pending_futures"])
|
| 127 |
+
num_pending_users = int(debug_info["num_pending_users"])
|
| 128 |
+
if num_pending_futures == 0 and num_pending_users == 0:
|
| 129 |
+
break
|
| 130 |
+
time.sleep(0.1)
|
| 131 |
+
if time.time() - start > timeout:
|
| 132 |
+
raise ValueError(
|
| 133 |
+
f"Timed out waiting to flush pending futures and users, "
|
| 134 |
+
f"had {num_pending_futures} pending futures and {num_pending_users} pending users"
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def get_num_owners_and_forks() -> tuple[str, str]:
|
| 139 |
+
"""
|
| 140 |
+
Retrieves number of OwnerRRefs and forks on this node from
|
| 141 |
+
_rref_context_get_debug_info.
|
| 142 |
+
"""
|
| 143 |
+
rref_dbg_info = _rref_context_get_debug_info()
|
| 144 |
+
num_owners = rref_dbg_info["num_owner_rrefs"]
|
| 145 |
+
num_forks = rref_dbg_info["num_forks"]
|
| 146 |
+
return num_owners, num_forks
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def wait_until_owners_and_forks_on_rank(
|
| 150 |
+
num_owners: int, num_forks: int, rank: int, timeout: int = 20
|
| 151 |
+
) -> None:
|
| 152 |
+
"""
|
| 153 |
+
Waits until timeout for num_forks and num_owners to exist on the rank. Used
|
| 154 |
+
to ensure proper deletion of RRefs in tests.
|
| 155 |
+
"""
|
| 156 |
+
start = time.time()
|
| 157 |
+
while True:
|
| 158 |
+
num_owners_on_rank, num_forks_on_rank = rpc.rpc_sync(
|
| 159 |
+
worker_name(rank), get_num_owners_and_forks, args=(), timeout=5
|
| 160 |
+
)
|
| 161 |
+
num_owners_on_rank = int(num_owners_on_rank)
|
| 162 |
+
num_forks_on_rank = int(num_forks_on_rank)
|
| 163 |
+
if num_owners_on_rank == num_owners and num_forks_on_rank == num_forks:
|
| 164 |
+
return
|
| 165 |
+
time.sleep(1)
|
| 166 |
+
if time.time() - start > timeout:
|
| 167 |
+
raise ValueError(
|
| 168 |
+
f"Timed out waiting {timeout} sec for {num_owners} owners and {num_forks} forks on rank,"
|
| 169 |
+
f" had {num_owners_on_rank} owners and {num_forks_on_rank} forks"
|
| 170 |
+
)
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def initialize_pg(init_method, rank: int, world_size: int) -> None:
|
| 174 |
+
# This is for tests using `dist.barrier`.
|
| 175 |
+
if not dist.is_initialized():
|
| 176 |
+
dist.init_process_group(
|
| 177 |
+
backend="gloo",
|
| 178 |
+
init_method=init_method,
|
| 179 |
+
rank=rank,
|
| 180 |
+
world_size=world_size,
|
| 181 |
+
)
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def worker_name(rank: int) -> str:
|
| 185 |
+
return f"worker{rank}"
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def get_function_event(function_events, partial_event_name):
|
| 189 |
+
"""
|
| 190 |
+
Returns the first event that matches partial_event_name in the provided
|
| 191 |
+
function_events. These function_events should be the output of
|
| 192 |
+
torch.autograd.profiler.function_events().
|
| 193 |
+
|
| 194 |
+
Args:
|
| 195 |
+
function_events: function_events returned by the profiler.
|
| 196 |
+
event_name (str): partial key that the event was profiled with.
|
| 197 |
+
"""
|
| 198 |
+
event = [event for event in function_events if partial_event_name in event.name][0] # noqa: RUF015
|
| 199 |
+
return event
|
pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/distributed/__init__.py
ADDED
|
File without changes
|
pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/distributed/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (246 Bytes). View file
|
|
|
pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/distributed/__pycache__/fake_pg.cpython-311.pyc
ADDED
|
Binary file (1.79 kB). View file
|
|
|
pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/distributed/_shard/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/distributed/_shard/sharded_tensor/__init__.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
|
| 3 |
+
import sys
|
| 4 |
+
from functools import partial, wraps
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
import torch.distributed as dist
|
| 8 |
+
from torch.distributed import rpc
|
| 9 |
+
from torch.testing._internal.common_distributed import (
|
| 10 |
+
MultiProcessTestCase,
|
| 11 |
+
TEST_SKIPS,
|
| 12 |
+
tp_transports,
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
TEST_GPU_NUM = 4
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class ShardedTensorTestBase(MultiProcessTestCase):
|
| 20 |
+
@property
|
| 21 |
+
def world_size(self):
|
| 22 |
+
return TEST_GPU_NUM
|
| 23 |
+
|
| 24 |
+
def init_pg(self, backend="nccl"):
|
| 25 |
+
if backend not in ["nccl", "gloo", "mpi", "hccl"]:
|
| 26 |
+
raise RuntimeError(f"Backend {backend} not supported!")
|
| 27 |
+
|
| 28 |
+
dist.init_process_group(
|
| 29 |
+
backend=backend,
|
| 30 |
+
world_size=self.world_size,
|
| 31 |
+
rank=self.rank,
|
| 32 |
+
init_method=f"file://{self.file_name}",
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
# set device for nccl pg for collectives
|
| 36 |
+
if backend == "nccl":
|
| 37 |
+
torch.cuda.set_device(self.rank)
|
| 38 |
+
|
| 39 |
+
def init_rpc(self):
|
| 40 |
+
rpc_backend_options = rpc.TensorPipeRpcBackendOptions(
|
| 41 |
+
_transports=tp_transports()
|
| 42 |
+
)
|
| 43 |
+
rpc_backend_options.init_method = f"file://{self.file_name}"
|
| 44 |
+
for rank in range(self.world_size):
|
| 45 |
+
rpc_backend_options.set_device_map(
|
| 46 |
+
f"worker{rank}", {rank: self.rank, self.rank: rank}
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
rpc.init_rpc(
|
| 50 |
+
name=f"worker{self.rank:d}",
|
| 51 |
+
rank=self.rank,
|
| 52 |
+
world_size=self.world_size,
|
| 53 |
+
rpc_backend_options=rpc_backend_options,
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
def init_comms(self, init_rpc=True, backend="nccl"):
|
| 57 |
+
if init_rpc:
|
| 58 |
+
self.init_rpc()
|
| 59 |
+
self.init_pg(backend=backend)
|
| 60 |
+
|
| 61 |
+
def destroy_comms(self, destroy_rpc=True):
|
| 62 |
+
# Wait for all ranks to reach here before starting shutdown.
|
| 63 |
+
dist.barrier()
|
| 64 |
+
|
| 65 |
+
if destroy_rpc:
|
| 66 |
+
rpc.shutdown()
|
| 67 |
+
dist.destroy_process_group()
|
| 68 |
+
|
| 69 |
+
def setUp(self) -> None:
|
| 70 |
+
super().setUp()
|
| 71 |
+
self._spawn_processes()
|
| 72 |
+
|
| 73 |
+
def assert_sharded_tensor_equal(self, st1, st2):
|
| 74 |
+
st1_local_shards = st1.local_shards()
|
| 75 |
+
st2_local_shards = st2.local_shards()
|
| 76 |
+
self.assertEqual(len(st1_local_shards), len(st2_local_shards))
|
| 77 |
+
for i, st1_local_shard in enumerate(st1_local_shards):
|
| 78 |
+
self.assertEqual(st1_local_shard.tensor, st2_local_shards[i].tensor)
|
| 79 |
+
self.assertEqual(st1_local_shard.metadata, st2_local_shards[i].metadata)
|
| 80 |
+
|
| 81 |
+
self.assertEqual(st1.metadata(), st2.metadata())
|
| 82 |
+
self.assertEqual(st1.sharding_spec(), st2.sharding_spec())
|
| 83 |
+
self.assertEqual(len(st1.remote_shards()), len(st2.remote_shards()))
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
# wrapper to initialize comms (processgroup + rpc)
|
| 87 |
+
def with_comms(func=None, init_rpc=True, backend="nccl"):
|
| 88 |
+
if func is None:
|
| 89 |
+
return partial(
|
| 90 |
+
with_comms,
|
| 91 |
+
init_rpc=init_rpc,
|
| 92 |
+
backend=backend,
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
@wraps(func)
|
| 96 |
+
def wrapper(self, *args, **kwargs):
|
| 97 |
+
if backend == "nccl" and torch.cuda.device_count() < self.world_size:
|
| 98 |
+
sys.exit(TEST_SKIPS[f"multi-gpu-{self.world_size}"].exit_code)
|
| 99 |
+
self.init_comms(init_rpc=init_rpc, backend=backend)
|
| 100 |
+
func(self, *args, **kwargs)
|
| 101 |
+
self.destroy_comms(destroy_rpc=init_rpc)
|
| 102 |
+
|
| 103 |
+
return wrapper
|
pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/distributed/_shard/sharded_tensor/_test_ops_common.py
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
|
| 3 |
+
import builtins
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
from torch.distributed._shard.sharding_spec import (
|
| 7 |
+
ChunkShardingSpec,
|
| 8 |
+
EnumerableShardingSpec,
|
| 9 |
+
ShardMetadata,
|
| 10 |
+
)
|
| 11 |
+
from torch.distributed._shard.sharding_spec._internals import (
|
| 12 |
+
get_chunked_dim_size,
|
| 13 |
+
get_split_size,
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def generate_chunk_sharding_specs_for_test(sharding_dim):
|
| 18 |
+
return [
|
| 19 |
+
ChunkShardingSpec(
|
| 20 |
+
dim=sharding_dim,
|
| 21 |
+
placements=[
|
| 22 |
+
"rank:0/cuda:0",
|
| 23 |
+
"rank:1/cuda:1",
|
| 24 |
+
"rank:2/cuda:2",
|
| 25 |
+
"rank:3/cuda:3",
|
| 26 |
+
],
|
| 27 |
+
),
|
| 28 |
+
# Test different ordering. (Case 1)
|
| 29 |
+
ChunkShardingSpec(
|
| 30 |
+
dim=sharding_dim,
|
| 31 |
+
placements=[
|
| 32 |
+
"rank:2/cuda:2",
|
| 33 |
+
"rank:3/cuda:3",
|
| 34 |
+
"rank:0/cuda:0",
|
| 35 |
+
"rank:1/cuda:1",
|
| 36 |
+
],
|
| 37 |
+
),
|
| 38 |
+
# Test different ordering. (Case 2)
|
| 39 |
+
ChunkShardingSpec(
|
| 40 |
+
dim=sharding_dim,
|
| 41 |
+
placements=[
|
| 42 |
+
"rank:3/cuda:3",
|
| 43 |
+
"rank:0/cuda:0",
|
| 44 |
+
"rank:1/cuda:1",
|
| 45 |
+
"rank:2/cuda:2",
|
| 46 |
+
],
|
| 47 |
+
),
|
| 48 |
+
]
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def generate_enumerable_sharding_specs_for_test():
|
| 52 |
+
return [
|
| 53 |
+
EnumerableShardingSpec(
|
| 54 |
+
[
|
| 55 |
+
ShardMetadata(
|
| 56 |
+
shard_offsets=[0, 0],
|
| 57 |
+
shard_sizes=[5, 5],
|
| 58 |
+
placement="rank:0/cuda:0",
|
| 59 |
+
),
|
| 60 |
+
ShardMetadata(
|
| 61 |
+
shard_offsets=[5, 0],
|
| 62 |
+
shard_sizes=[5, 5],
|
| 63 |
+
placement="rank:1/cuda:1",
|
| 64 |
+
),
|
| 65 |
+
ShardMetadata(
|
| 66 |
+
shard_offsets=[0, 5],
|
| 67 |
+
shard_sizes=[5, 5],
|
| 68 |
+
placement="rank:2/cuda:2",
|
| 69 |
+
),
|
| 70 |
+
ShardMetadata(
|
| 71 |
+
shard_offsets=[5, 5],
|
| 72 |
+
shard_sizes=[5, 5],
|
| 73 |
+
placement="rank:3/cuda:3",
|
| 74 |
+
),
|
| 75 |
+
]
|
| 76 |
+
)
|
| 77 |
+
]
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def generate_local_weight_sharding_params_for_test(
|
| 81 |
+
local_weight, sharded_dim, gpu_num, spec, rank
|
| 82 |
+
):
|
| 83 |
+
"""
|
| 84 |
+
Shard the local weight based the given spec, so we can compare against
|
| 85 |
+
the one from sharded tensor.
|
| 86 |
+
|
| 87 |
+
Args:
|
| 88 |
+
local_weight: weight matrix to be sharded.
|
| 89 |
+
sharded_dim: The dimension which we shard on.
|
| 90 |
+
gpu_num: number of ranks.
|
| 91 |
+
spec: sharding spec.
|
| 92 |
+
rank: # of cuda process.
|
| 93 |
+
|
| 94 |
+
Returns:
|
| 95 |
+
start_pos: start position of sharded weight on the given rank.
|
| 96 |
+
chunk_size: chunk size of sharded weight on the given rank.
|
| 97 |
+
"""
|
| 98 |
+
sharding_dim_size = local_weight.size(sharded_dim)
|
| 99 |
+
split_size = get_split_size(sharding_dim_size, gpu_num)
|
| 100 |
+
current_offsets = 0
|
| 101 |
+
start_pos = current_offsets
|
| 102 |
+
for idx, placement in enumerate(spec.placements):
|
| 103 |
+
chunk_size = get_chunked_dim_size(sharding_dim_size, split_size, idx)
|
| 104 |
+
if rank == placement.rank():
|
| 105 |
+
start_pos = current_offsets
|
| 106 |
+
break
|
| 107 |
+
current_offsets += chunk_size
|
| 108 |
+
return start_pos, chunk_size
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def clone_module_parameter(module, param_name):
|
| 112 |
+
"""
|
| 113 |
+
Clone a parameter from a given existing module.
|
| 114 |
+
|
| 115 |
+
Args:
|
| 116 |
+
module (:class:`torch.nn.Module`): Module whose parameter needs to be cloned.
|
| 117 |
+
param_name (str): Name of the parameter of ``module`` that needs to be cloned.
|
| 118 |
+
|
| 119 |
+
Returns: cloned tensor as :class:`torch.nn.Parameter`.
|
| 120 |
+
"""
|
| 121 |
+
tensor = getattr(module, param_name)
|
| 122 |
+
return torch.nn.Parameter(tensor.detach().clone())
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def gen_binary_op_func(python_op, inplace=False):
|
| 126 |
+
src_lines = ["def f(lhs, rhs):"]
|
| 127 |
+
if "torch" in python_op:
|
| 128 |
+
src_lines.append(f" return {python_op}(lhs, rhs)\n")
|
| 129 |
+
elif inplace:
|
| 130 |
+
src_lines.append(f" lhs {python_op}= rhs\n return lhs\n")
|
| 131 |
+
else:
|
| 132 |
+
src_lines.append(f" return lhs {python_op} rhs\n")
|
| 133 |
+
|
| 134 |
+
code_str = "\n".join(src_lines)
|
| 135 |
+
g = {"torch": torch}
|
| 136 |
+
builtins.exec(code_str, g)
|
| 137 |
+
return g["f"]
|
pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/distributed/_shard/sharded_tensor/_test_st_common.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
|
| 3 |
+
import copy
|
| 4 |
+
import random
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
from torch.distributed._shard import sharded_tensor
|
| 8 |
+
from torch.distributed._shard.sharding_spec import ChunkShardingSpec
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
PLACEMENTS = [
|
| 12 |
+
"rank:0/cuda:0",
|
| 13 |
+
"rank:1/cuda:1",
|
| 14 |
+
"rank:2/cuda:2",
|
| 15 |
+
"rank:3/cuda:3",
|
| 16 |
+
]
|
| 17 |
+
|
| 18 |
+
DEFAULT_GPU_NUM = 4
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _chunk_sharding_specs_list_for_test(sharding_dims, seed=0):
|
| 22 |
+
spec_list = []
|
| 23 |
+
for i in range(len(sharding_dims)):
|
| 24 |
+
random.Random(seed + i).shuffle(PLACEMENTS)
|
| 25 |
+
spec_list.append(
|
| 26 |
+
ChunkShardingSpec(
|
| 27 |
+
dim=sharding_dims[i],
|
| 28 |
+
placements=copy.deepcopy(PLACEMENTS),
|
| 29 |
+
)
|
| 30 |
+
)
|
| 31 |
+
return spec_list
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class MyShardedModel2(torch.nn.Module):
|
| 35 |
+
def __init__(self, spec=None, group=None, init_rrefs=True) -> None:
|
| 36 |
+
super().__init__()
|
| 37 |
+
if spec is not None:
|
| 38 |
+
self.sharded_tensor2 = sharded_tensor.rand(
|
| 39 |
+
spec, 10, 20, process_group=group, init_rrefs=init_rrefs
|
| 40 |
+
)
|
| 41 |
+
else:
|
| 42 |
+
self.sharded_tensor2 = None
|
| 43 |
+
self.random_tensor2 = torch.nn.Parameter(torch.rand(2, 2))
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class MyShardedModel1(torch.nn.Module):
|
| 47 |
+
def __init__(self, spec=None, group=None, init_rrefs=True) -> None:
|
| 48 |
+
super().__init__()
|
| 49 |
+
if spec is not None:
|
| 50 |
+
self.sharded_tensor1 = sharded_tensor.rand(
|
| 51 |
+
spec, 10, 20, process_group=group, init_rrefs=init_rrefs
|
| 52 |
+
)
|
| 53 |
+
else:
|
| 54 |
+
self.sharded_tensor1 = None
|
| 55 |
+
self.random_tensor1 = torch.nn.Parameter(torch.rand(2, 2))
|
| 56 |
+
self.submodule = MyShardedModel2(spec, group, init_rrefs)
|
pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/distributed/_shard/test_common.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn as nn
|
| 5 |
+
from torch.distributed._shard.sharded_tensor import ShardedTensor
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class SimpleMegatronLM(nn.Module):
|
| 9 |
+
def __init__(self, linear_size, rank=None, dtype=torch.float32):
|
| 10 |
+
super().__init__()
|
| 11 |
+
self.fc1 = nn.Linear(*linear_size[0], dtype=dtype)
|
| 12 |
+
self.gelu = nn.GELU()
|
| 13 |
+
self.fc2 = nn.Linear(*linear_size[1], dtype=dtype)
|
| 14 |
+
if rank is not None:
|
| 15 |
+
self.fc1.cuda(rank)
|
| 16 |
+
self.fc2.cuda(rank)
|
| 17 |
+
|
| 18 |
+
def forward(self, inp):
|
| 19 |
+
return self.fc2(self.gelu(self.fc1(inp)))
|
| 20 |
+
|
| 21 |
+
def get_weights(self):
|
| 22 |
+
if isinstance(self.fc1.weight, ShardedTensor):
|
| 23 |
+
weight1 = self.fc1.weight.local_tensor()
|
| 24 |
+
else:
|
| 25 |
+
weight1 = self.fc1.weight
|
| 26 |
+
|
| 27 |
+
if isinstance(self.fc2.weight, ShardedTensor):
|
| 28 |
+
weight2 = self.fc2.weight.local_tensor()
|
| 29 |
+
else:
|
| 30 |
+
weight2 = self.fc2.weight
|
| 31 |
+
|
| 32 |
+
return (weight1, weight2)
|
| 33 |
+
|
| 34 |
+
def get_biases(self):
|
| 35 |
+
return (self.fc1.bias, self.fc2.bias)
|
| 36 |
+
|
| 37 |
+
def get_weight_grads(self):
|
| 38 |
+
return (self.fc1.weight.grad, self.fc2.weight.grad)
|
| 39 |
+
|
| 40 |
+
def get_bias_grads(self):
|
| 41 |
+
return (self.fc1.bias.grad, self.fc2.bias.grad)
|
pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/distributed/_tensor/__init__.py
ADDED
|
File without changes
|
pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/distributed/_tensor/common_dtensor.py
ADDED
|
@@ -0,0 +1,683 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
|
| 3 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates
|
| 4 |
+
|
| 5 |
+
import itertools
|
| 6 |
+
import sys
|
| 7 |
+
from collections.abc import Iterator, Sequence
|
| 8 |
+
from dataclasses import dataclass
|
| 9 |
+
from functools import partial, wraps
|
| 10 |
+
from typing import Any, Callable, cast, Optional, TypeVar, Union
|
| 11 |
+
|
| 12 |
+
import torch
|
| 13 |
+
import torch.distributed as dist
|
| 14 |
+
import torch.nn as nn
|
| 15 |
+
import torch.nn.functional as F
|
| 16 |
+
from torch._utils import _get_device_module
|
| 17 |
+
from torch.distributed.tensor import (
|
| 18 |
+
DeviceMesh,
|
| 19 |
+
distribute_tensor,
|
| 20 |
+
DTensor,
|
| 21 |
+
init_device_mesh,
|
| 22 |
+
Placement,
|
| 23 |
+
Replicate,
|
| 24 |
+
Shard,
|
| 25 |
+
)
|
| 26 |
+
from torch.distributed.tensor.parallel import (
|
| 27 |
+
ColwiseParallel,
|
| 28 |
+
parallelize_module,
|
| 29 |
+
PrepareModuleInput,
|
| 30 |
+
RowwiseParallel,
|
| 31 |
+
SequenceParallel,
|
| 32 |
+
)
|
| 33 |
+
from torch.testing._internal.common_distributed import (
|
| 34 |
+
MultiProcContinuousTest,
|
| 35 |
+
MultiProcessTestCase,
|
| 36 |
+
MultiThreadedTestCase,
|
| 37 |
+
run_subtests,
|
| 38 |
+
skip_if_lt_x_gpu,
|
| 39 |
+
TEST_SKIPS,
|
| 40 |
+
)
|
| 41 |
+
from torch.testing._internal.common_utils import TEST_CUDA, TEST_HPU, TEST_XPU
|
| 42 |
+
from torch.utils._pytree import tree_flatten, tree_unflatten, TreeSpec
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
DEVICE_COUNT: int
|
| 46 |
+
|
| 47 |
+
if TEST_CUDA:
|
| 48 |
+
DEVICE_TYPE = "cuda"
|
| 49 |
+
PG_BACKEND = "nccl"
|
| 50 |
+
DEVICE_COUNT = _get_device_module("cuda").device_count()
|
| 51 |
+
elif TEST_HPU:
|
| 52 |
+
DEVICE_TYPE = "hpu"
|
| 53 |
+
PG_BACKEND = "hccl"
|
| 54 |
+
DEVICE_COUNT = _get_device_module("hpu").device_count()
|
| 55 |
+
elif TEST_XPU:
|
| 56 |
+
DEVICE_TYPE = "xpu"
|
| 57 |
+
PG_BACKEND = "xccl"
|
| 58 |
+
DEVICE_COUNT = _get_device_module("xpu").device_count()
|
| 59 |
+
else:
|
| 60 |
+
DEVICE_TYPE = "cpu"
|
| 61 |
+
PG_BACKEND = "gloo"
|
| 62 |
+
|
| 63 |
+
NUM_DEVICES = 4
|
| 64 |
+
|
| 65 |
+
# We use this as a proxy for "multiple GPUs exist"
|
| 66 |
+
if (TEST_CUDA or TEST_XPU or TEST_HPU) and DEVICE_COUNT > 1:
|
| 67 |
+
# when we actually have multiple GPUs, relax the requirement to smaller counts.
|
| 68 |
+
NUM_DEVICES = min(NUM_DEVICES, DEVICE_COUNT)
|
| 69 |
+
|
| 70 |
+
T = TypeVar("T")
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
# simple RMSNorm layer for testing
|
| 74 |
+
class RMSNormPython(torch.nn.Module):
|
| 75 |
+
def __init__(self, dim: int, eps: float = 1e-6):
|
| 76 |
+
super().__init__()
|
| 77 |
+
self.eps = eps
|
| 78 |
+
self.weight = torch.nn.Parameter(torch.ones(dim))
|
| 79 |
+
|
| 80 |
+
def _norm(self, x):
|
| 81 |
+
return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
|
| 82 |
+
|
| 83 |
+
def forward(self, x):
|
| 84 |
+
output = self._norm(x)
|
| 85 |
+
return output * self.weight
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
class MLPModule(nn.Module):
|
| 89 |
+
def __init__(self, device, bias: bool = True):
|
| 90 |
+
super().__init__()
|
| 91 |
+
torch.manual_seed(5)
|
| 92 |
+
self.net1 = nn.Linear(10, 16, bias=bias, device=device)
|
| 93 |
+
self.relu = nn.ReLU()
|
| 94 |
+
self.net2 = nn.Linear(16, 10, bias=bias, device=device)
|
| 95 |
+
|
| 96 |
+
def forward(self, x):
|
| 97 |
+
return self.net2(self.relu(self.net1(x)))
|
| 98 |
+
|
| 99 |
+
def reset_parameters(self):
|
| 100 |
+
self.net1.reset_parameters()
|
| 101 |
+
self.net2.reset_parameters()
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
class MLPStacked(nn.Module):
|
| 105 |
+
def __init__(self, device, n_layers: int = 2):
|
| 106 |
+
super().__init__()
|
| 107 |
+
self.layers = nn.ModuleList([MLPModule(device) for i in range(n_layers)])
|
| 108 |
+
|
| 109 |
+
def forward(self, x):
|
| 110 |
+
for layer in self.layers:
|
| 111 |
+
x = layer(x)
|
| 112 |
+
return x
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
@dataclass
|
| 116 |
+
class ModelArgs:
|
| 117 |
+
n_layers: int = 2
|
| 118 |
+
vocab_size: int = 8
|
| 119 |
+
max_seq_len: int = 16
|
| 120 |
+
dim: int = 16
|
| 121 |
+
n_heads: int = 4
|
| 122 |
+
dropout_p: float = 0.1
|
| 123 |
+
use_attn_mask: bool = True
|
| 124 |
+
weight_tying: bool = True
|
| 125 |
+
checkpoint_activations: bool = False
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
class Attention(nn.Module):
|
| 129 |
+
def __init__(self, args: ModelArgs):
|
| 130 |
+
super().__init__()
|
| 131 |
+
assert args.dim % args.n_heads == 0
|
| 132 |
+
self.head_dim = args.dim // args.n_heads
|
| 133 |
+
self.n_heads = args.n_heads
|
| 134 |
+
self.dropout_p = args.dropout_p
|
| 135 |
+
self.resid_dropout = nn.Dropout(args.dropout_p)
|
| 136 |
+
self.use_attn_mask = args.use_attn_mask
|
| 137 |
+
|
| 138 |
+
self.wq = nn.Linear(args.dim, args.dim, bias=False)
|
| 139 |
+
self.wk = nn.Linear(args.dim, args.dim, bias=False)
|
| 140 |
+
self.wv = nn.Linear(args.dim, args.dim, bias=False)
|
| 141 |
+
self.wo = nn.Linear(args.dim, args.dim, bias=False)
|
| 142 |
+
|
| 143 |
+
def forward(self, x):
|
| 144 |
+
bsz, seq_len, _ = x.size()
|
| 145 |
+
queries, keys, values = self.wq(x), self.wk(x), self.wv(x)
|
| 146 |
+
queries = queries.view(bsz, seq_len, self.n_heads, self.head_dim)
|
| 147 |
+
keys = keys.view(bsz, seq_len, self.n_heads, self.head_dim)
|
| 148 |
+
values = values.view(bsz, seq_len, self.n_heads, self.head_dim)
|
| 149 |
+
|
| 150 |
+
queries = queries.transpose(1, 2) # (bsz, n_heads, seq_len, head_dim)
|
| 151 |
+
keys = keys.transpose(1, 2) # (bsz, n_heads, seq_len, head_dim)
|
| 152 |
+
values = values.transpose(1, 2) # (bsz, n_heads, seq_len, head_dim)
|
| 153 |
+
|
| 154 |
+
output = F.scaled_dot_product_attention(
|
| 155 |
+
queries,
|
| 156 |
+
keys,
|
| 157 |
+
values,
|
| 158 |
+
None,
|
| 159 |
+
self.dropout_p if self.training else 0,
|
| 160 |
+
self.use_attn_mask,
|
| 161 |
+
)
|
| 162 |
+
output = output.transpose(1, 2).contiguous().view(bsz, seq_len, -1)
|
| 163 |
+
return self.resid_dropout(self.wo(output))
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
class FeedForward(nn.Module):
|
| 167 |
+
def __init__(self, dim, hidden_dim, dropout_p):
|
| 168 |
+
super().__init__()
|
| 169 |
+
self.w1 = nn.Linear(dim, hidden_dim)
|
| 170 |
+
self.gelu = nn.GELU()
|
| 171 |
+
self.w2 = nn.Linear(hidden_dim, dim)
|
| 172 |
+
self.resid_dropout = nn.Dropout(dropout_p)
|
| 173 |
+
|
| 174 |
+
def forward(self, x):
|
| 175 |
+
return self.resid_dropout(self.w2(self.gelu(self.w1(x))))
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
class TransformerBlock(nn.Module):
|
| 179 |
+
def __init__(self, args: ModelArgs):
|
| 180 |
+
super().__init__()
|
| 181 |
+
self.attention_norm = nn.LayerNorm(args.dim)
|
| 182 |
+
self.attention = Attention(args)
|
| 183 |
+
self.ffn_norm = nn.LayerNorm(args.dim)
|
| 184 |
+
self.feed_forward = FeedForward(
|
| 185 |
+
args.dim, hidden_dim=4 * args.dim, dropout_p=args.dropout_p
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
def forward(self, x):
|
| 189 |
+
h = x + self.attention(self.attention_norm(x))
|
| 190 |
+
out = h + self.feed_forward(self.ffn_norm(h))
|
| 191 |
+
return out
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
# A toy transformer model, partly inspired by the nanoGPT model:
|
| 195 |
+
# https://github.com/karpathy/nanoGPT.
|
| 196 |
+
class Transformer(nn.Module):
|
| 197 |
+
def __init__(self, args: ModelArgs):
|
| 198 |
+
super().__init__()
|
| 199 |
+
assert args.vocab_size is not None
|
| 200 |
+
assert args.max_seq_len is not None
|
| 201 |
+
self.model_args = args
|
| 202 |
+
self.max_seq_len = args.max_seq_len
|
| 203 |
+
self.tok_embeddings = nn.Embedding(args.vocab_size, args.dim)
|
| 204 |
+
self.pos_embeddings = nn.Embedding(args.max_seq_len, args.dim)
|
| 205 |
+
self.dropout = nn.Dropout(args.dropout_p)
|
| 206 |
+
self.layers = nn.ModuleList()
|
| 207 |
+
for _ in range(args.n_layers):
|
| 208 |
+
self.layers.append(TransformerBlock(args))
|
| 209 |
+
self.norm = nn.LayerNorm(args.dim)
|
| 210 |
+
self.output = nn.Linear(args.dim, args.vocab_size, bias=False)
|
| 211 |
+
if args.weight_tying:
|
| 212 |
+
self.output.weight = self.tok_embeddings.weight
|
| 213 |
+
self.checkpoint_activations = args.checkpoint_activations
|
| 214 |
+
|
| 215 |
+
def forward(self, tokens):
|
| 216 |
+
_bsz, seq_len = tokens.size()
|
| 217 |
+
assert seq_len <= self.max_seq_len
|
| 218 |
+
h = self.tok_embeddings(tokens)
|
| 219 |
+
pos = torch.arange(0, seq_len, device=tokens.device)
|
| 220 |
+
p = self.pos_embeddings(pos) # positional embeddings of shape (seq_len, dim)
|
| 221 |
+
h = h + p
|
| 222 |
+
h = self.dropout(h)
|
| 223 |
+
for layer in self.layers:
|
| 224 |
+
if self.checkpoint_activations:
|
| 225 |
+
h = torch.utils.checkpoint.checkpoint(layer, h, use_reentrant=False)
|
| 226 |
+
else:
|
| 227 |
+
h = layer(h)
|
| 228 |
+
h = self.norm(h)
|
| 229 |
+
output = self.output(h).float()
|
| 230 |
+
return output
|
| 231 |
+
|
| 232 |
+
@staticmethod
|
| 233 |
+
def parallelize(
|
| 234 |
+
module: "Transformer",
|
| 235 |
+
device_mesh: DeviceMesh,
|
| 236 |
+
use_seq_parallel: bool,
|
| 237 |
+
local_output_for_attn: bool = False,
|
| 238 |
+
) -> nn.Module:
|
| 239 |
+
assert isinstance(module, Transformer), f"Requires Transformer but got {module}"
|
| 240 |
+
# Parallelize the root submodules.
|
| 241 |
+
if use_seq_parallel:
|
| 242 |
+
root_plan = {
|
| 243 |
+
"tok_embeddings": RowwiseParallel(
|
| 244 |
+
input_layouts=Replicate(), output_layouts=Shard(1)
|
| 245 |
+
),
|
| 246 |
+
"pos_embeddings": RowwiseParallel(
|
| 247 |
+
input_layouts=Replicate(), output_layouts=Shard(0)
|
| 248 |
+
),
|
| 249 |
+
"norm": SequenceParallel(),
|
| 250 |
+
}
|
| 251 |
+
else:
|
| 252 |
+
root_plan = {
|
| 253 |
+
"tok_embeddings": RowwiseParallel(
|
| 254 |
+
input_layouts=Replicate(), output_layouts=Replicate()
|
| 255 |
+
),
|
| 256 |
+
"pos_embeddings": RowwiseParallel(
|
| 257 |
+
input_layouts=Replicate(), output_layouts=Replicate()
|
| 258 |
+
),
|
| 259 |
+
}
|
| 260 |
+
|
| 261 |
+
module_tp = parallelize_module(module, device_mesh, root_plan)
|
| 262 |
+
# Parallelize the attention and feed forward submodules.
|
| 263 |
+
for layer in module_tp.layers:
|
| 264 |
+
layer_parallelize_plan = {}
|
| 265 |
+
if use_seq_parallel:
|
| 266 |
+
layer_parallelize_plan["attention"] = PrepareModuleInput(
|
| 267 |
+
input_layouts=Shard(1),
|
| 268 |
+
desired_input_layouts=Replicate(),
|
| 269 |
+
)
|
| 270 |
+
# shard the RMSNorms
|
| 271 |
+
layer_parallelize_plan["attention_norm"] = SequenceParallel()
|
| 272 |
+
layer_parallelize_plan["ffn_norm"] = SequenceParallel()
|
| 273 |
+
layer_parallelize_plan["attention.wq"] = ColwiseParallel(
|
| 274 |
+
use_local_output=local_output_for_attn
|
| 275 |
+
)
|
| 276 |
+
layer_parallelize_plan["attention.wk"] = ColwiseParallel(
|
| 277 |
+
use_local_output=local_output_for_attn
|
| 278 |
+
)
|
| 279 |
+
layer_parallelize_plan["attention.wv"] = ColwiseParallel(
|
| 280 |
+
use_local_output=local_output_for_attn
|
| 281 |
+
)
|
| 282 |
+
layer_parallelize_plan["attention.wo"] = (
|
| 283 |
+
RowwiseParallel(output_layouts=Shard(1))
|
| 284 |
+
if use_seq_parallel
|
| 285 |
+
else RowwiseParallel()
|
| 286 |
+
)
|
| 287 |
+
|
| 288 |
+
layer_parallelize_plan["feed_forward.w1"] = (
|
| 289 |
+
ColwiseParallel(input_layouts=Shard(1))
|
| 290 |
+
if use_seq_parallel
|
| 291 |
+
else ColwiseParallel()
|
| 292 |
+
)
|
| 293 |
+
layer_parallelize_plan["feed_forward.w2"] = (
|
| 294 |
+
RowwiseParallel(output_layouts=Shard(1))
|
| 295 |
+
if use_seq_parallel
|
| 296 |
+
else RowwiseParallel()
|
| 297 |
+
)
|
| 298 |
+
|
| 299 |
+
parallelize_module(layer, device_mesh, layer_parallelize_plan)
|
| 300 |
+
|
| 301 |
+
# Parallelize the output submodule. If weight tying is enabled, we need to
|
| 302 |
+
# make sure output.weight is sharded consistently as tok_embeddings.weight,
|
| 303 |
+
# at the cost of the all_reduce operation using RowwiseParallel.
|
| 304 |
+
output_parallelize_plan = (
|
| 305 |
+
ColwiseParallel(
|
| 306 |
+
input_layouts=Shard(1),
|
| 307 |
+
output_layouts=Replicate(),
|
| 308 |
+
)
|
| 309 |
+
if use_seq_parallel
|
| 310 |
+
else ColwiseParallel(output_layouts=Replicate())
|
| 311 |
+
)
|
| 312 |
+
parallelize_module(module_tp.output, device_mesh, output_parallelize_plan)
|
| 313 |
+
|
| 314 |
+
if local_output_for_attn:
|
| 315 |
+
for layer in module_tp.layers:
|
| 316 |
+
layer.attention.n_heads = (
|
| 317 |
+
module_tp.model_args.n_heads // device_mesh.size()
|
| 318 |
+
)
|
| 319 |
+
|
| 320 |
+
# Manually set output.weight so that parameters and gradients are shared.
|
| 321 |
+
if module_tp.model_args.weight_tying:
|
| 322 |
+
module_tp.output.weight = module_tp.tok_embeddings.weight
|
| 323 |
+
|
| 324 |
+
return module_tp
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
def skip_unless_torch_gpu(method: T) -> T:
|
| 328 |
+
"""
|
| 329 |
+
Test decorator which skips the test unless there's a GPU available to torch.
|
| 330 |
+
|
| 331 |
+
>>> # xdoctest: +SKIP
|
| 332 |
+
>>> @skip_unless_torch_gpu
|
| 333 |
+
>>> def test_some_method(self) -> None:
|
| 334 |
+
>>> ...
|
| 335 |
+
"""
|
| 336 |
+
# The builtin @skip_if_no_gpu relies on os.environ['WORLD_SIZE'] being set.
|
| 337 |
+
return cast(T, skip_if_lt_x_gpu(NUM_DEVICES)(method))
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
class DTensorContinuousTestBase(MultiProcContinuousTest):
|
| 341 |
+
@classmethod
|
| 342 |
+
def device_type(cls) -> str:
|
| 343 |
+
# if enough GPU/XPU/HPU we can use those devices, otherwise we fallback to CPU
|
| 344 |
+
if not (TEST_CUDA or TEST_XPU or TEST_HPU) or DEVICE_COUNT < cls.world_size:
|
| 345 |
+
return "cpu"
|
| 346 |
+
else:
|
| 347 |
+
return DEVICE_TYPE
|
| 348 |
+
|
| 349 |
+
@classmethod
|
| 350 |
+
def backend_str(cls) -> str:
|
| 351 |
+
backend = dist.get_default_backend_for_device(DEVICE_TYPE)
|
| 352 |
+
return backend
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
class DTensorTestBase(MultiProcessTestCase):
|
| 356 |
+
@property
|
| 357 |
+
def world_size(self) -> int:
|
| 358 |
+
return NUM_DEVICES
|
| 359 |
+
|
| 360 |
+
@property
|
| 361 |
+
def device_type(self) -> str:
|
| 362 |
+
# if enough GPU/XPU/HPU we can use those devices, otherwise we fallback to CPU
|
| 363 |
+
if not (TEST_CUDA or TEST_XPU or TEST_HPU) or DEVICE_COUNT < self.world_size:
|
| 364 |
+
return "cpu"
|
| 365 |
+
else:
|
| 366 |
+
return DEVICE_TYPE
|
| 367 |
+
|
| 368 |
+
@property
|
| 369 |
+
def backend(self) -> str:
|
| 370 |
+
backend = dist.get_default_backend_for_device(DEVICE_TYPE)
|
| 371 |
+
return backend
|
| 372 |
+
|
| 373 |
+
def build_device_mesh(self) -> DeviceMesh:
|
| 374 |
+
return init_device_mesh(self.device_type, (self.world_size,))
|
| 375 |
+
|
| 376 |
+
def init_pg(self, eager_init, backend: Optional[str] = None) -> None:
|
| 377 |
+
if "nccl" in self.backend and torch.cuda.device_count() < self.world_size:
|
| 378 |
+
sys.exit(TEST_SKIPS[f"multi-gpu-{self.world_size}"].exit_code)
|
| 379 |
+
|
| 380 |
+
if backend is None:
|
| 381 |
+
backend = self.backend
|
| 382 |
+
|
| 383 |
+
if backend not in [
|
| 384 |
+
"nccl",
|
| 385 |
+
"gloo",
|
| 386 |
+
"mpi",
|
| 387 |
+
"cpu:gloo,cuda:nccl",
|
| 388 |
+
"hccl",
|
| 389 |
+
"xccl",
|
| 390 |
+
"fake",
|
| 391 |
+
]:
|
| 392 |
+
raise RuntimeError(f"Backend {backend} not supported!")
|
| 393 |
+
|
| 394 |
+
device_id = None
|
| 395 |
+
if "nccl" in backend or "xccl" in backend:
|
| 396 |
+
# set device for nccl pg for collectives
|
| 397 |
+
# TODO: if users want to enable testing across hosts, we may need
|
| 398 |
+
# to change this part.
|
| 399 |
+
torch.accelerator.set_device_index(self.rank)
|
| 400 |
+
# we only need to set device_id for nccl backend with eager init
|
| 401 |
+
device_id = (
|
| 402 |
+
torch.device(f"{self.device_type}:{self.rank}") if eager_init else None
|
| 403 |
+
)
|
| 404 |
+
|
| 405 |
+
# For nccl backend, bind the device to the process if device_id is not None
|
| 406 |
+
# so the nccl communicator is immediately formed and we can use `ncclCommSplit`
|
| 407 |
+
# for form subgroup to avoid unnecesssary overhead.
|
| 408 |
+
dist.init_process_group(
|
| 409 |
+
backend=backend,
|
| 410 |
+
world_size=self.world_size,
|
| 411 |
+
rank=self.rank, # pyre-ignore[16]
|
| 412 |
+
init_method=f"file://{self.file_name}", # pyre-ignore[16]
|
| 413 |
+
device_id=device_id,
|
| 414 |
+
)
|
| 415 |
+
|
| 416 |
+
def destroy_pg(self, device_id: Optional[int] = None) -> None:
|
| 417 |
+
# Wait for all ranks to reach here before starting shutdown.
|
| 418 |
+
# FIXME dist.barrier deadlocks with multiple threads and NCCL: https://github.com/pytorch/pytorch/issues/95895
|
| 419 |
+
# dist.all_reduce(torch.zeros((1,), device="cuda" if TEST_CUDA else "cpu"))
|
| 420 |
+
# FIXME can't use the above all_reduce as it causes hangs on bionic and focal. It hangs:
|
| 421 |
+
# test_dtensor.py -- DTensorMeshTest.test_dtensor_device_mesh_device_conversion
|
| 422 |
+
if device_id is None:
|
| 423 |
+
device_id = (
|
| 424 |
+
torch.cuda.current_device() if self.device_type == "cuda" else self.rank
|
| 425 |
+
)
|
| 426 |
+
|
| 427 |
+
if self.device_type == "cpu" and torch._C._get_accelerator().type != "cpu":
|
| 428 |
+
# NOTE: when `device_id` is not None, barrier() will choose the accelerator
|
| 429 |
+
# of the most pripority, which means if the test specifies to use CPU for
|
| 430 |
+
# testing while CUDA is available on the host, the barrier() will use CUDA.
|
| 431 |
+
# To avoid this and better respect `self.device_type`, we add this branch to
|
| 432 |
+
# enforce barrier() to use CPU when `self.device_type` is CPU and other
|
| 433 |
+
# accelerator is also available.
|
| 434 |
+
dist.barrier()
|
| 435 |
+
else:
|
| 436 |
+
dist.barrier(device_ids=[device_id])
|
| 437 |
+
|
| 438 |
+
dist.destroy_process_group()
|
| 439 |
+
|
| 440 |
+
def setUp(self) -> None:
|
| 441 |
+
super().setUp()
|
| 442 |
+
self._spawn_processes()
|
| 443 |
+
|
| 444 |
+
def _test_op_on_dtensor(self, op_call, *args, **kwargs) -> None:
|
| 445 |
+
"""
|
| 446 |
+
This function checks ``op_call(dtensor).full_tensor() == op_call(dtensor.full_tensor())``.
|
| 447 |
+
Unlike _test_op where the DTensor sharding is generated by DTensorConverter,
|
| 448 |
+
this function takes in DTensor object directly as argument and test the equality
|
| 449 |
+
of calling op on full_tensor() and DTensor.
|
| 450 |
+
"""
|
| 451 |
+
# call full_tensor() on DTensor args/kwargs
|
| 452 |
+
args_flattened, args_spec = tree_flatten(args)
|
| 453 |
+
full_tensor_args_flattened = tuple(
|
| 454 |
+
arg.full_tensor().detach().clone() if isinstance(arg, DTensor) else arg
|
| 455 |
+
for arg in args_flattened
|
| 456 |
+
)
|
| 457 |
+
full_tensor_args = tree_unflatten(full_tensor_args_flattened, args_spec)
|
| 458 |
+
full_tensor_kwargs = {
|
| 459 |
+
k: v.full_tensor() if isinstance(v, DTensor) else v
|
| 460 |
+
for k, v in kwargs.items()
|
| 461 |
+
}
|
| 462 |
+
|
| 463 |
+
out_flattened, _ = tree_flatten(
|
| 464 |
+
op_call(*full_tensor_args, **full_tensor_kwargs)
|
| 465 |
+
)
|
| 466 |
+
d_out_flattened, _ = tree_flatten(op_call(*args, **kwargs))
|
| 467 |
+
d_out_full_tensor_flattened = [dt.full_tensor() for dt in d_out_flattened]
|
| 468 |
+
self.assertEqual(out_flattened, d_out_full_tensor_flattened)
|
| 469 |
+
|
| 470 |
+
# pyre-ignore[2]:
|
| 471 |
+
def _test_op(self, mesh: DeviceMesh, op_call, *args, **kwargs) -> None:
|
| 472 |
+
out = op_call(*args, **kwargs)
|
| 473 |
+
dtc = DTensorConverter(mesh, args, kwargs)
|
| 474 |
+
for d_args, d_kwargs in dtc:
|
| 475 |
+
# pyre can't find assertTrue anymore?
|
| 476 |
+
self.assertEqual(dtc.successful(), True)
|
| 477 |
+
d_out = op_call(*d_args, **d_kwargs)
|
| 478 |
+
self.assertEqual(d_out.full_tensor(), out)
|
| 479 |
+
|
| 480 |
+
def run_subtests(self, *args, **kwargs):
|
| 481 |
+
return run_subtests(self, *args, **kwargs)
|
| 482 |
+
|
| 483 |
+
|
| 484 |
+
TestFunc = Callable[[...], object]
|
| 485 |
+
|
| 486 |
+
|
| 487 |
+
# wrapper to initialize comms (processgroup)
|
| 488 |
+
def with_comms(
|
| 489 |
+
eager_init: Union[TestFunc, bool] = False, backend: Optional[str] = None
|
| 490 |
+
) -> TestFunc:
|
| 491 |
+
def decorator(func, eager_init: bool = False, backend: Optional[str] = None):
|
| 492 |
+
@wraps(func) # pyre-ignore[6]
|
| 493 |
+
def wrapper(
|
| 494 |
+
self,
|
| 495 |
+
*args: tuple[object],
|
| 496 |
+
**kwargs: dict[str, Any], # type: ignore[misc]
|
| 497 |
+
) -> None:
|
| 498 |
+
self.init_pg(eager_init, backend)
|
| 499 |
+
|
| 500 |
+
try:
|
| 501 |
+
func(self, *args, **kwargs) # type: ignore[misc]
|
| 502 |
+
except Exception as e:
|
| 503 |
+
dist.destroy_process_group()
|
| 504 |
+
raise e
|
| 505 |
+
|
| 506 |
+
self.destroy_pg()
|
| 507 |
+
|
| 508 |
+
return wrapper
|
| 509 |
+
|
| 510 |
+
return (
|
| 511 |
+
decorator(func=eager_init)
|
| 512 |
+
if callable(eager_init)
|
| 513 |
+
else partial(decorator, eager_init=eager_init, backend=backend)
|
| 514 |
+
)
|
| 515 |
+
|
| 516 |
+
|
| 517 |
+
class DTensorOpTestBase(MultiThreadedTestCase):
|
| 518 |
+
@property
|
| 519 |
+
def world_size(self) -> int:
|
| 520 |
+
return NUM_DEVICES
|
| 521 |
+
|
| 522 |
+
@property
|
| 523 |
+
def device_type(self) -> str:
|
| 524 |
+
return DEVICE_TYPE
|
| 525 |
+
|
| 526 |
+
def build_device_mesh(self):
|
| 527 |
+
return init_device_mesh(self.device_type, (self.world_size,))
|
| 528 |
+
|
| 529 |
+
def setUp(self) -> None:
|
| 530 |
+
super().setUp()
|
| 531 |
+
self._spawn_threads()
|
| 532 |
+
|
| 533 |
+
|
| 534 |
+
# This is a class for converting args/kwargs of an op into distributed args/kwargs
|
| 535 |
+
class DTensorConverter:
|
| 536 |
+
def __init__(
|
| 537 |
+
self,
|
| 538 |
+
mesh: DeviceMesh,
|
| 539 |
+
args: tuple[object, ...],
|
| 540 |
+
kwargs: dict[str, object],
|
| 541 |
+
) -> None:
|
| 542 |
+
self.hit = 0
|
| 543 |
+
self.miss = 0
|
| 544 |
+
self.mesh = mesh
|
| 545 |
+
self.args = args
|
| 546 |
+
self.kwargs = kwargs
|
| 547 |
+
flatten_args, flatten_args_spec = tree_flatten(args)
|
| 548 |
+
flatten_kwargs, flatten_kwargs_spec = tree_flatten(kwargs)
|
| 549 |
+
|
| 550 |
+
self.flatten_args: list[object] = flatten_args
|
| 551 |
+
self.flatten_args_spec: TreeSpec = flatten_args_spec
|
| 552 |
+
self.flatten_kwargs: list[object] = flatten_kwargs
|
| 553 |
+
self.flatten_kwargs_spec: TreeSpec = flatten_kwargs_spec
|
| 554 |
+
|
| 555 |
+
choices_for_args = [
|
| 556 |
+
self.gen_sharding_choices_for_arg(arg)
|
| 557 |
+
for arg in self.flatten_args
|
| 558 |
+
if isinstance(arg, torch.Tensor)
|
| 559 |
+
]
|
| 560 |
+
|
| 561 |
+
choices_for_args.extend(
|
| 562 |
+
self.gen_sharding_choices_for_arg(arg)
|
| 563 |
+
for arg in self.flatten_kwargs
|
| 564 |
+
if isinstance(arg, torch.Tensor)
|
| 565 |
+
)
|
| 566 |
+
|
| 567 |
+
self.sharding_combs: Iterator[Sequence[Placement]] = iter(
|
| 568 |
+
itertools.product(*choices_for_args)
|
| 569 |
+
)
|
| 570 |
+
|
| 571 |
+
def successful(self) -> bool:
|
| 572 |
+
return self.hit > 0 and self.miss == 0
|
| 573 |
+
|
| 574 |
+
def is_supported_tensor(self, t: torch.Tensor) -> bool:
|
| 575 |
+
# TODO: dist tensor need to support quantized and sparse
|
| 576 |
+
# tensors, quantized tensor might be relatively easy, but
|
| 577 |
+
# sparse tensor have special layouts that we need to possibly
|
| 578 |
+
# deal with, until we are clear about them, we don't officially
|
| 579 |
+
# support them.
|
| 580 |
+
return not any(
|
| 581 |
+
[
|
| 582 |
+
t.is_sparse_csr,
|
| 583 |
+
t.is_sparse,
|
| 584 |
+
t.is_mkldnn,
|
| 585 |
+
t.is_quantized,
|
| 586 |
+
t.is_nested,
|
| 587 |
+
torch._is_functional_tensor(t),
|
| 588 |
+
t.is_neg(),
|
| 589 |
+
t.is_conj(),
|
| 590 |
+
t.device.type in ("lazy", "meta"),
|
| 591 |
+
# We need a way to test if a tensor is batched but there
|
| 592 |
+
# is no official APi to do it
|
| 593 |
+
# torch._C._is_batched(t),
|
| 594 |
+
]
|
| 595 |
+
)
|
| 596 |
+
|
| 597 |
+
def gen_sharding_choices_for_arg(self, arg: torch.Tensor) -> Sequence[Placement]:
|
| 598 |
+
mesh_size = self.mesh.size()
|
| 599 |
+
sharding_choices: list[Placement] = [Replicate()]
|
| 600 |
+
# c10d collective does not support bool tensor
|
| 601 |
+
# for bool tensor we treat it as replicated
|
| 602 |
+
if arg.dtype != torch.bool:
|
| 603 |
+
# only generating choices with: replicate, or sharding
|
| 604 |
+
# evenly on a dimension that could be sharded
|
| 605 |
+
sharding_choices = sharding_choices + [
|
| 606 |
+
Shard(i)
|
| 607 |
+
for i, s in enumerate(arg.shape)
|
| 608 |
+
if s > 1 and s % mesh_size == 0
|
| 609 |
+
]
|
| 610 |
+
# TODO: add multi mesh choices
|
| 611 |
+
# all_choices = itertools.product(
|
| 612 |
+
# *(self.mesh.ndim * [sharding_choices])
|
| 613 |
+
# )
|
| 614 |
+
return sharding_choices
|
| 615 |
+
|
| 616 |
+
def __iter__(self) -> "DTensorConverter":
|
| 617 |
+
return self
|
| 618 |
+
|
| 619 |
+
def __next__(self) -> tuple[tuple[object, ...], dict[str, object]]:
|
| 620 |
+
try:
|
| 621 |
+
next_sharding_choices = next(self.sharding_combs)
|
| 622 |
+
idx = 0
|
| 623 |
+
|
| 624 |
+
new_args: list[object] = []
|
| 625 |
+
for arg in self.flatten_args:
|
| 626 |
+
if isinstance(arg, torch.Tensor):
|
| 627 |
+
new_args.append(
|
| 628 |
+
self.to_dist_tensor(
|
| 629 |
+
arg, self.mesh, [next_sharding_choices[idx]]
|
| 630 |
+
)
|
| 631 |
+
)
|
| 632 |
+
idx += 1
|
| 633 |
+
else:
|
| 634 |
+
new_args.append(arg)
|
| 635 |
+
|
| 636 |
+
new_kwargs: list[object] = []
|
| 637 |
+
for arg in self.flatten_kwargs:
|
| 638 |
+
if isinstance(arg, torch.Tensor):
|
| 639 |
+
new_kwargs.append(
|
| 640 |
+
self.to_dist_tensor(
|
| 641 |
+
arg, self.mesh, [next_sharding_choices[idx]]
|
| 642 |
+
)
|
| 643 |
+
)
|
| 644 |
+
idx += 1
|
| 645 |
+
else:
|
| 646 |
+
new_kwargs.append(arg)
|
| 647 |
+
|
| 648 |
+
return (
|
| 649 |
+
tree_unflatten(new_args, self.flatten_args_spec),
|
| 650 |
+
tree_unflatten(new_kwargs, self.flatten_kwargs_spec),
|
| 651 |
+
)
|
| 652 |
+
except StopIteration as e:
|
| 653 |
+
raise StopIteration from e
|
| 654 |
+
|
| 655 |
+
def to_dist_tensor(
|
| 656 |
+
self, t: torch.Tensor, mesh: DeviceMesh, placements: list[Placement]
|
| 657 |
+
) -> torch.Tensor:
|
| 658 |
+
if type(t) is torch.Tensor or type(t) is nn.Parameter:
|
| 659 |
+
if self.is_supported_tensor(t):
|
| 660 |
+
self.hit += 1
|
| 661 |
+
if t.ndim == 0:
|
| 662 |
+
# scalar tensor by default will be replicated
|
| 663 |
+
r = distribute_tensor(t, mesh, [Replicate()] * mesh.ndim)
|
| 664 |
+
else:
|
| 665 |
+
# distribute non-scalar tensors
|
| 666 |
+
r = distribute_tensor(t, mesh, placements)
|
| 667 |
+
if type(t) is nn.Parameter:
|
| 668 |
+
r = nn.Parameter( # type: ignore[assignment]
|
| 669 |
+
r, requires_grad=r.requires_grad
|
| 670 |
+
)
|
| 671 |
+
return r
|
| 672 |
+
else:
|
| 673 |
+
self.miss += 1
|
| 674 |
+
return t
|
| 675 |
+
elif torch.overrides.is_tensor_like(t):
|
| 676 |
+
# Blindly converting tensor subclasses to dist tensor can cause
|
| 677 |
+
# unpredictable problems, we explicitly disable this conversion
|
| 678 |
+
# for now (i.e. we don't support DTensor holding tensor subclass
|
| 679 |
+
# until there's a strong reason later).
|
| 680 |
+
self.miss += 1
|
| 681 |
+
return t
|
| 682 |
+
else:
|
| 683 |
+
raise RuntimeError(f"Trying to convert to DTensor, but got {type(t)}")
|
pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/distributed/checkpoint_utils.py
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
|
| 3 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates
|
| 4 |
+
|
| 5 |
+
import io
|
| 6 |
+
import logging
|
| 7 |
+
import os
|
| 8 |
+
import shutil
|
| 9 |
+
import tempfile
|
| 10 |
+
from functools import wraps
|
| 11 |
+
from typing import Any, Callable, cast, IO, Optional
|
| 12 |
+
|
| 13 |
+
# introduced as collections.abc.Buffer in Python 3.12
|
| 14 |
+
from typing_extensions import Buffer
|
| 15 |
+
|
| 16 |
+
import torch.distributed as dist
|
| 17 |
+
from torch.distributed.checkpoint._extension import (
|
| 18 |
+
ExtensionRegistry,
|
| 19 |
+
StreamTransformExtension,
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class Rot13Example(StreamTransformExtension):
|
| 24 |
+
"""
|
| 25 |
+
This is an example stream transform extension which just does rot13 on each
|
| 26 |
+
alphanumeric character of the stream. It is mainly intended as a demonstration
|
| 27 |
+
and for testing; there isn't a production use case for this.
|
| 28 |
+
"""
|
| 29 |
+
|
| 30 |
+
def __init__(self, chunk_size: int = io.DEFAULT_BUFFER_SIZE) -> None:
|
| 31 |
+
super().__init__()
|
| 32 |
+
self._chunk_size = chunk_size
|
| 33 |
+
|
| 34 |
+
@staticmethod
|
| 35 |
+
def from_descriptor(version: str) -> "Rot13Example":
|
| 36 |
+
if version.partition(".")[0] != "1":
|
| 37 |
+
raise ValueError(f"Unknown extension {version=}")
|
| 38 |
+
return Rot13Example()
|
| 39 |
+
|
| 40 |
+
@staticmethod
|
| 41 |
+
def registry_name() -> str:
|
| 42 |
+
return "stream.rot13"
|
| 43 |
+
|
| 44 |
+
def get_descriptor(self) -> str:
|
| 45 |
+
return f"{self.registry_name()}/1"
|
| 46 |
+
|
| 47 |
+
@staticmethod
|
| 48 |
+
def _rot13bytes(b: Buffer, count: int) -> None:
|
| 49 |
+
b = memoryview(b)
|
| 50 |
+
for i in range(count):
|
| 51 |
+
ch = b[i]
|
| 52 |
+
if ch >= ord("A") and ch <= ord("Z"):
|
| 53 |
+
ch += ord("a") - ord("A")
|
| 54 |
+
elif ch >= ord("a") and ch <= ord("z"):
|
| 55 |
+
ch += ord("A") - ord("a")
|
| 56 |
+
b[i] = ch
|
| 57 |
+
|
| 58 |
+
def transform_to(self, output: IO[bytes]) -> IO[bytes]:
|
| 59 |
+
class Writer(io.RawIOBase):
|
| 60 |
+
def __init__(self, output: IO[bytes]) -> None:
|
| 61 |
+
self.output = output
|
| 62 |
+
|
| 63 |
+
def writeable(self) -> bool:
|
| 64 |
+
return True
|
| 65 |
+
|
| 66 |
+
def write(self, b: Buffer) -> Optional[int]:
|
| 67 |
+
# Don't mutate the input
|
| 68 |
+
chunk = bytearray(b)
|
| 69 |
+
Rot13Example._rot13bytes(chunk, len(chunk))
|
| 70 |
+
return self.output.write(chunk)
|
| 71 |
+
|
| 72 |
+
def flush(self) -> None:
|
| 73 |
+
self.output.flush()
|
| 74 |
+
|
| 75 |
+
return cast(IO[bytes], Writer(output))
|
| 76 |
+
|
| 77 |
+
def transform_from(self, input: IO[bytes]) -> IO[bytes]:
|
| 78 |
+
class Reader(io.RawIOBase):
|
| 79 |
+
def __init__(self, input: IO[bytes]) -> None:
|
| 80 |
+
self.input = input
|
| 81 |
+
|
| 82 |
+
def readable(self) -> bool:
|
| 83 |
+
return True
|
| 84 |
+
|
| 85 |
+
def readinto(self, b: Buffer) -> Optional[int]:
|
| 86 |
+
if hasattr(self.input, "readinto"):
|
| 87 |
+
count = self.input.readinto(b)
|
| 88 |
+
else:
|
| 89 |
+
# It's possible self.input is an IO[bytes] with no readinto method.
|
| 90 |
+
# In that case, we emulate with a read and copy. In practice,
|
| 91 |
+
# all of the current concrete extensions have readinto.
|
| 92 |
+
view = memoryview(b)
|
| 93 |
+
r = self.input.read(len(view))
|
| 94 |
+
if r is None:
|
| 95 |
+
count = None
|
| 96 |
+
else:
|
| 97 |
+
count = len(r)
|
| 98 |
+
view[:count] = r
|
| 99 |
+
if count == 0 or count is None:
|
| 100 |
+
return count
|
| 101 |
+
|
| 102 |
+
Rot13Example._rot13bytes(b, count)
|
| 103 |
+
return count
|
| 104 |
+
|
| 105 |
+
def seekable(self) -> bool:
|
| 106 |
+
return self.input.seekable()
|
| 107 |
+
|
| 108 |
+
def seek(self, offset: int, whence: int = os.SEEK_SET) -> int:
|
| 109 |
+
return self.input.seek(offset, whence)
|
| 110 |
+
|
| 111 |
+
def tell(self) -> int:
|
| 112 |
+
return self.input.tell()
|
| 113 |
+
|
| 114 |
+
return cast(IO[bytes], Reader(input))
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def get_test_extension_registry() -> ExtensionRegistry:
|
| 118 |
+
registry = ExtensionRegistry()
|
| 119 |
+
registry.register(Rot13Example)
|
| 120 |
+
return registry
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def with_temp_dir(
|
| 124 |
+
func: Optional[Callable] = None,
|
| 125 |
+
) -> Optional[Callable]:
|
| 126 |
+
"""
|
| 127 |
+
Wrapper to initialize temp directory for distributed checkpoint.
|
| 128 |
+
"""
|
| 129 |
+
assert func is not None
|
| 130 |
+
|
| 131 |
+
@wraps(func)
|
| 132 |
+
def wrapper(self, *args: tuple[object], **kwargs: dict[str, Any]) -> None:
|
| 133 |
+
if dist.is_initialized():
|
| 134 |
+
# Only create temp_dir when rank is 0
|
| 135 |
+
if dist.get_rank() == 0:
|
| 136 |
+
temp_dir = tempfile.mkdtemp()
|
| 137 |
+
print(f"Using temp directory: {temp_dir}")
|
| 138 |
+
else:
|
| 139 |
+
temp_dir = ""
|
| 140 |
+
object_list = [temp_dir]
|
| 141 |
+
|
| 142 |
+
# Broadcast temp_dir to all the other ranks
|
| 143 |
+
os.sync()
|
| 144 |
+
dist.broadcast_object_list(object_list)
|
| 145 |
+
self.temp_dir = object_list[0]
|
| 146 |
+
os.sync()
|
| 147 |
+
else:
|
| 148 |
+
temp_dir = tempfile.mkdtemp()
|
| 149 |
+
print(f"No process group initialized, using temp directory: {temp_dir}")
|
| 150 |
+
self.temp_dir = temp_dir
|
| 151 |
+
|
| 152 |
+
try:
|
| 153 |
+
func(self, *args, **kwargs)
|
| 154 |
+
finally:
|
| 155 |
+
if dist.is_initialized() and dist.get_rank() == 0:
|
| 156 |
+
shutil.rmtree(self.temp_dir, ignore_errors=True)
|
| 157 |
+
else:
|
| 158 |
+
shutil.rmtree(self.temp_dir, ignore_errors=True)
|
| 159 |
+
|
| 160 |
+
return wrapper
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def with_checkpoint_logging(
|
| 164 |
+
func: Optional[Callable] = None,
|
| 165 |
+
logger_name: str = "torch.distributed.checkpoint",
|
| 166 |
+
level: int = logging.INFO,
|
| 167 |
+
) -> Optional[Callable]:
|
| 168 |
+
"""
|
| 169 |
+
Wrapper to configure checkpoint logging for distributed tests.
|
| 170 |
+
|
| 171 |
+
Args:
|
| 172 |
+
func: The test function to wrap
|
| 173 |
+
logger_name: Name of the logger to configure (default: 'torch.distributed.checkpoint')
|
| 174 |
+
level: Logging level to set (default: logging.INFO)
|
| 175 |
+
"""
|
| 176 |
+
assert func is not None
|
| 177 |
+
|
| 178 |
+
@wraps(func)
|
| 179 |
+
def wrapper(self, *args: tuple[object], **kwargs: dict[str, Any]) -> None:
|
| 180 |
+
# Get the logger and store original level
|
| 181 |
+
target_logger = logging.getLogger(logger_name)
|
| 182 |
+
original_level = target_logger.level
|
| 183 |
+
|
| 184 |
+
# Set the desired logging level
|
| 185 |
+
target_logger.setLevel(level)
|
| 186 |
+
|
| 187 |
+
try:
|
| 188 |
+
func(self, *args, **kwargs)
|
| 189 |
+
finally:
|
| 190 |
+
# Restore original logging level
|
| 191 |
+
target_logger.setLevel(original_level)
|
| 192 |
+
|
| 193 |
+
return wrapper
|
pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/distributed/common_state_dict.py
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
|
| 3 |
+
# Owner(s): ["oncall: distributed"]
|
| 4 |
+
|
| 5 |
+
import copy
|
| 6 |
+
from itertools import chain
|
| 7 |
+
from typing import Any
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
import torch.nn as nn
|
| 11 |
+
from torch.distributed._sharded_tensor import ShardedTensor
|
| 12 |
+
from torch.distributed._state_dict_utils import _gather_state_dict
|
| 13 |
+
from torch.distributed.checkpoint.state_dict import (
|
| 14 |
+
_PG,
|
| 15 |
+
_STATE,
|
| 16 |
+
set_state_dict,
|
| 17 |
+
StateDictOptions,
|
| 18 |
+
)
|
| 19 |
+
from torch.distributed.tensor import DTensor
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class VerifyStateDictMixin:
|
| 23 |
+
def _compare_tensor(self, orig_tensor, dist_tensor, offload_to_cpu=False):
|
| 24 |
+
if isinstance(dist_tensor, (DTensor, ShardedTensor)):
|
| 25 |
+
dist_tensor = _gather_state_dict({"mykey": dist_tensor}).pop("mykey")
|
| 26 |
+
|
| 27 |
+
if offload_to_cpu:
|
| 28 |
+
orig_tensor = orig_tensor.cpu()
|
| 29 |
+
dist_tensor = dist_tensor.cpu()
|
| 30 |
+
self.assertTrue(isinstance(dist_tensor, torch.Tensor))
|
| 31 |
+
self.assertTrue(torch.allclose(orig_tensor, dist_tensor))
|
| 32 |
+
|
| 33 |
+
def _verify_msd(
|
| 34 |
+
self,
|
| 35 |
+
msd: dict[str, Any],
|
| 36 |
+
dist_msd: dict[str, Any],
|
| 37 |
+
options: StateDictOptions = StateDictOptions(),
|
| 38 |
+
offload_to_cpu=False,
|
| 39 |
+
) -> None:
|
| 40 |
+
if not options.ignore_frozen_params:
|
| 41 |
+
self.assertEqual(len(msd), len(dist_msd))
|
| 42 |
+
for fqn, param in msd.items():
|
| 43 |
+
dist_param = dist_msd.get(fqn, None)
|
| 44 |
+
if not options.ignore_frozen_params:
|
| 45 |
+
self.assertIsNotNone(dist_param, f"{fqn=}")
|
| 46 |
+
try:
|
| 47 |
+
self._compare_tensor(param, dist_param, offload_to_cpu)
|
| 48 |
+
except AssertionError as e:
|
| 49 |
+
raise AssertionError(
|
| 50 |
+
f"{fqn} has mismatched value {param} {dist_param}"
|
| 51 |
+
) from e
|
| 52 |
+
elif dist_param is None:
|
| 53 |
+
self.assertFalse(param.requires_grad, f"{fqn=}")
|
| 54 |
+
|
| 55 |
+
def _verify_osd(
|
| 56 |
+
self,
|
| 57 |
+
model: nn.Module,
|
| 58 |
+
optim: torch.optim.Optimizer,
|
| 59 |
+
osd: dict[str, Any],
|
| 60 |
+
dist_osd: dict[str, Any],
|
| 61 |
+
) -> None:
|
| 62 |
+
params = list(chain.from_iterable(g["params"] for g in optim.param_groups))
|
| 63 |
+
param_pid_mapping = dict(zip(params, range(len(params))))
|
| 64 |
+
fqn_pid_mapping = {}
|
| 65 |
+
for fqn, param in model.named_parameters():
|
| 66 |
+
pid = param_pid_mapping[param]
|
| 67 |
+
fqn_pid_mapping[fqn] = pid
|
| 68 |
+
fqn_pid_mapping[pid] = fqn
|
| 69 |
+
# Check optimizer_state_dict state
|
| 70 |
+
|
| 71 |
+
self.assertEqual(len(osd[_STATE]), len(dist_osd[_STATE]))
|
| 72 |
+
for pid, states in osd[_STATE].items():
|
| 73 |
+
fqn = fqn_pid_mapping[pid]
|
| 74 |
+
dist_states = dist_osd[_STATE].get(fqn, None)
|
| 75 |
+
self.assertIsNotNone(dist_states, fqn)
|
| 76 |
+
self.assertEqual(len(states), len(dist_states))
|
| 77 |
+
for key, state in states.items():
|
| 78 |
+
dist_state = states.get(key, None)
|
| 79 |
+
self.assertIsNotNone(dist_state)
|
| 80 |
+
self._compare_tensor(state, dist_state)
|
| 81 |
+
|
| 82 |
+
# Check optimizer_state_dict param_group
|
| 83 |
+
old_dist_osd_pg = dist_osd[_PG]
|
| 84 |
+
if len(osd[_PG]) != len(dist_osd[_PG]):
|
| 85 |
+
self.assertTrue(len(dist_osd[_PG]) > len(osd[_PG]))
|
| 86 |
+
new_pg = copy.deepcopy(dist_osd[_PG][0])
|
| 87 |
+
new_pg["params"] = []
|
| 88 |
+
for dist_group in dist_osd[_PG]:
|
| 89 |
+
new_pg["params"].extend(dist_group["params"])
|
| 90 |
+
dist_osd[_PG] = [new_pg]
|
| 91 |
+
|
| 92 |
+
self.assertEqual(len(osd[_PG]), len(dist_osd[_PG]))
|
| 93 |
+
for group, dist_group in zip(osd[_PG], dist_osd[_PG]):
|
| 94 |
+
self.assertEqual(len(group), len(dist_group))
|
| 95 |
+
for key, value in group.items():
|
| 96 |
+
# Below doesn't work because param_groups can have None
|
| 97 |
+
# values.
|
| 98 |
+
# dist_value = dist_group.get(key, None)
|
| 99 |
+
# self.assertIsNotNone(dist_value, (dist_group, group))
|
| 100 |
+
dist_value = dist_group[key]
|
| 101 |
+
if key == "params":
|
| 102 |
+
fqns = [fqn_pid_mapping[pid] for pid in value]
|
| 103 |
+
self.assertEqual(sorted(fqns), sorted(dist_value))
|
| 104 |
+
else:
|
| 105 |
+
self.assertEqual(value, dist_value)
|
| 106 |
+
dist_osd[_PG] = old_dist_osd_pg
|
| 107 |
+
|
| 108 |
+
def _verify_osd_by_load(
|
| 109 |
+
self,
|
| 110 |
+
model: nn.Module,
|
| 111 |
+
optim: torch.optim.Optimizer,
|
| 112 |
+
new_optim: torch.optim.Optimizer,
|
| 113 |
+
dist_osd: dict[str, Any],
|
| 114 |
+
) -> None:
|
| 115 |
+
new_dist_osd = _gather_state_dict(dist_osd)
|
| 116 |
+
set_state_dict(
|
| 117 |
+
model,
|
| 118 |
+
optimizers=new_optim,
|
| 119 |
+
model_state_dict={},
|
| 120 |
+
optim_state_dict=new_dist_osd,
|
| 121 |
+
)
|
| 122 |
+
self.assertEqual(optim.state_dict(), new_optim.state_dict())
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
class FusionEmbedding(nn.Module):
|
| 126 |
+
def __init__(self, vocab_size: int, fusion_vocab_size: int, embed_dim: int) -> None:
|
| 127 |
+
super().__init__()
|
| 128 |
+
self.embedding = nn.Embedding(vocab_size, embed_dim)
|
| 129 |
+
self.fusion_embedding = nn.Embedding(fusion_vocab_size, embed_dim)
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
class FusionEmbeddingWithHook(nn.Module):
|
| 133 |
+
def __init__(self, vocab_size: int, fusion_vocab_size: int, embed_dim: int) -> None:
|
| 134 |
+
super().__init__()
|
| 135 |
+
self.embedding = nn.Embedding(vocab_size, embed_dim)
|
| 136 |
+
self.fusion_embedding = nn.Embedding(fusion_vocab_size, embed_dim)
|
| 137 |
+
self._register_state_dict_hook(FusionEmbeddingWithHook._state_dict_hook)
|
| 138 |
+
self._register_load_state_dict_pre_hook(
|
| 139 |
+
FusionEmbeddingWithHook._load_state_dict_hook, with_module=True
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
def _state_dict_hook(self, destination, prefix, keep_vars):
|
| 143 |
+
"""Remove "embedding" from the original embedding in the state_dict
|
| 144 |
+
name. This keeps the original state dict name for the embedding
|
| 145 |
+
from before fusing with the FusionEmbedding.
|
| 146 |
+
"""
|
| 147 |
+
key = prefix + "embedding.weight"
|
| 148 |
+
new_key = prefix + "weight"
|
| 149 |
+
destination[new_key] = destination[key]
|
| 150 |
+
del destination[key]
|
| 151 |
+
|
| 152 |
+
def _load_state_dict_hook(self, state_dict, prefix, *args, **kwargs):
|
| 153 |
+
"""Apply extra "embedding" prefix to the state_dict key to
|
| 154 |
+
account for the FusionEmbedding wrapping.
|
| 155 |
+
"""
|
| 156 |
+
if state_dict:
|
| 157 |
+
key = prefix + "weight"
|
| 158 |
+
new_key = prefix + "embedding.weight"
|
| 159 |
+
state_dict[new_key] = state_dict[key]
|
| 160 |
+
del state_dict[key]
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
class FusionEmbeddingWithModifier(FusionEmbeddingWithHook):
|
| 164 |
+
# _fqn_modifiers is a private function as a contract between DSD. When users change the state_dict
|
| 165 |
+
# keys, they need to provide a mapping from the new key to the original key. This is used to ensure
|
| 166 |
+
# consistency between the state_dict keys and fqn.
|
| 167 |
+
def _fqn_modifiers(self) -> dict[str, str]:
|
| 168 |
+
return {
|
| 169 |
+
"weight": "embedding",
|
| 170 |
+
}
|
pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/distributed/ddp_under_dist_autograd_test.py
ADDED
|
@@ -0,0 +1,746 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
| 7 |
+
import threading
|
| 8 |
+
from typing import NamedTuple
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
import torch.distributed as dist
|
| 12 |
+
import torch.distributed.autograd as dist_autograd
|
| 13 |
+
import torch.nn as nn
|
| 14 |
+
from torch.distributed import rpc
|
| 15 |
+
from torch.distributed.nn import RemoteModule
|
| 16 |
+
from torch.nn.parallel import DistributedDataParallel
|
| 17 |
+
from torch.testing._internal.common_distributed import (
|
| 18 |
+
requires_gloo,
|
| 19 |
+
requires_nccl,
|
| 20 |
+
skip_if_lt_x_gpu,
|
| 21 |
+
skip_if_rocm_multiprocess,
|
| 22 |
+
)
|
| 23 |
+
from torch.testing._internal.dist_utils import dist_init, INIT_METHOD_TEMPLATE
|
| 24 |
+
from torch.testing._internal.distributed.rpc.rpc_agent_test_fixture import (
|
| 25 |
+
RpcAgentTestFixture,
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
NUM_EM_ROW = 2
|
| 30 |
+
D_SPARSE = 3
|
| 31 |
+
D_DENSE = 2
|
| 32 |
+
D_HID = 3
|
| 33 |
+
D_OUT = 1
|
| 34 |
+
NUM_TRAINERS = 4
|
| 35 |
+
# Trainers + the master + the remote worker
|
| 36 |
+
WORLD_SIZE = NUM_TRAINERS + 2
|
| 37 |
+
TRAINER_RANKS = list(range(NUM_TRAINERS))
|
| 38 |
+
REMOTE_WORKER_RANK = TRAINER_RANKS[-1] + 1
|
| 39 |
+
MASTER_RANK = REMOTE_WORKER_RANK + 1
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class DdpMode(enum.Enum):
|
| 43 |
+
# Don't apply DDP
|
| 44 |
+
NONE = enum.auto()
|
| 45 |
+
# Apply DDP to the top level nn.Module
|
| 46 |
+
OUTSIDE = enum.auto()
|
| 47 |
+
# Embed DDP inside the top level nn.Module
|
| 48 |
+
INSIDE = enum.auto()
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def init_logger():
|
| 52 |
+
logger = logging.getLogger(__name__)
|
| 53 |
+
level = logging.DEBUG if "debug" in os.environ else logging.INFO
|
| 54 |
+
logger.setLevel(level)
|
| 55 |
+
console = logging.StreamHandler()
|
| 56 |
+
formatter = logging.Formatter(
|
| 57 |
+
"%(asctime)s %(filename)s:%(lineno)s %(levelname)s p:%(processName)s t:%(threadName)s: %(message)s"
|
| 58 |
+
)
|
| 59 |
+
console.setFormatter(formatter)
|
| 60 |
+
console.setLevel(level)
|
| 61 |
+
# add the handlers to the logger
|
| 62 |
+
logger.addHandler(console)
|
| 63 |
+
logger.propagate = False
|
| 64 |
+
return logger
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
gLogger = init_logger()
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
class FeatureSet(NamedTuple):
|
| 71 |
+
"""A feature set has 2 types of features"""
|
| 72 |
+
|
| 73 |
+
dense_features: torch.Tensor
|
| 74 |
+
sparse_features: torch.LongTensor
|
| 75 |
+
values: torch.Tensor
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def _call_method(method, rref, *args, **kwargs):
|
| 79 |
+
return method(rref.local_value(), *args, **kwargs)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def _remote_method(method, rref, *args, **kwargs):
|
| 83 |
+
args_tup = tuple([method, rref] + list(args))
|
| 84 |
+
return rpc.rpc_sync(rref.owner(), _call_method, args=args_tup, kwargs=kwargs)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def _remote_method_async(method, rref, *args, **kwargs):
|
| 88 |
+
args_tup = tuple([method, rref] + list(args))
|
| 89 |
+
return rpc.rpc_async(rref.owner(), _call_method, args=args_tup, kwargs=kwargs)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
class RemoteEM(nn.Module):
|
| 93 |
+
def __init__(self, num_embeddings: int, embedding_dim: int):
|
| 94 |
+
gLogger.info("Initing RemoteEM with %s %s", num_embeddings, embedding_dim)
|
| 95 |
+
super().__init__()
|
| 96 |
+
init_em = [0.5] * embedding_dim
|
| 97 |
+
self.em = nn.EmbeddingBag(
|
| 98 |
+
num_embeddings,
|
| 99 |
+
embedding_dim,
|
| 100 |
+
_weight=torch.tensor([init_em] * num_embeddings),
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
def forward(self, input: torch.Tensor):
|
| 104 |
+
gLogger.debug("Running RemoteEM.forward() on: %s", input)
|
| 105 |
+
return self.em(input, offsets=torch.LongTensor(range(input.shape[0])))
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
# Return a linear module with predefined parameters.
|
| 109 |
+
def getLinear(d_in, d_out):
|
| 110 |
+
l = nn.Linear(d_in, d_out, bias=False)
|
| 111 |
+
w = torch.ones((d_out, d_in))
|
| 112 |
+
w[0][0] = -1
|
| 113 |
+
w.requires_grad_()
|
| 114 |
+
l.weight.data = w
|
| 115 |
+
return l
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
class RemoteNet(nn.Module):
|
| 119 |
+
def __init__(self, d_in: int, d_out: int):
|
| 120 |
+
gLogger.info("Initing RemoteNet with %s %s", d_in, d_out)
|
| 121 |
+
super().__init__()
|
| 122 |
+
self.fc = getLinear(d_in, d_out)
|
| 123 |
+
self.relu = nn.ReLU()
|
| 124 |
+
|
| 125 |
+
def forward(self, input: torch.Tensor):
|
| 126 |
+
gLogger.debug("Running RemoteNet.forward() on: %s", input)
|
| 127 |
+
return self.relu(self.fc(input))
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
class HybridModel(nn.Module):
|
| 131 |
+
def __init__(
|
| 132 |
+
self,
|
| 133 |
+
remote_em_rref: rpc.RRef,
|
| 134 |
+
remote_net_rref: rpc.RRef,
|
| 135 |
+
process_group_for_ddp: dist.ProcessGroup = None,
|
| 136 |
+
):
|
| 137 |
+
super().__init__()
|
| 138 |
+
self.remote_em_rref = remote_em_rref
|
| 139 |
+
self.remote_net_rref = remote_net_rref
|
| 140 |
+
self.fc1 = getLinear(D_DENSE, D_DENSE)
|
| 141 |
+
self.fc2 = getLinear(D_HID, D_OUT)
|
| 142 |
+
|
| 143 |
+
self.non_ddp_params = tuple(self.fc1.parameters()) + tuple(
|
| 144 |
+
self.fc2.parameters()
|
| 145 |
+
)
|
| 146 |
+
self.ddp_params = ()
|
| 147 |
+
|
| 148 |
+
if process_group_for_ddp is not None:
|
| 149 |
+
self.non_ddp_params, self.ddp_params = (
|
| 150 |
+
tuple(self.fc1.parameters()),
|
| 151 |
+
tuple(self.fc2.parameters()),
|
| 152 |
+
)
|
| 153 |
+
gLogger.info("Use DDP for the second local net.")
|
| 154 |
+
self.fc2 = DistributedDataParallel(
|
| 155 |
+
self.fc2, check_reduction=True, process_group=process_group_for_ddp
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
gLogger.info(
|
| 159 |
+
"HybridModel has %s groups of parameters.", len(list(self.parameters()))
|
| 160 |
+
)
|
| 161 |
+
|
| 162 |
+
def forward(self, input: FeatureSet):
|
| 163 |
+
gLogger.debug("Running HybridModel.forward on %s", input)
|
| 164 |
+
sparse = _remote_method(
|
| 165 |
+
RemoteEM.forward, self.remote_em_rref, input.sparse_features
|
| 166 |
+
)
|
| 167 |
+
# The same size of mini batch.
|
| 168 |
+
assert sparse.shape[0] == input.dense_features.shape[0]
|
| 169 |
+
dense = self.fc1(input.dense_features)
|
| 170 |
+
x = torch.cat((dense, sparse), 1)
|
| 171 |
+
gLogger.debug("Concatenated feature: %s", x)
|
| 172 |
+
x = _remote_method(RemoteNet.forward, self.remote_net_rref, x)
|
| 173 |
+
return self.fc2(x)
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
class Trainer:
|
| 177 |
+
def __init__(
|
| 178 |
+
self,
|
| 179 |
+
remote_em_rref: rpc.RRef,
|
| 180 |
+
remote_net_rref: rpc.RRef,
|
| 181 |
+
ddp_mode: DdpMode,
|
| 182 |
+
rank: int,
|
| 183 |
+
):
|
| 184 |
+
self.rank = rank
|
| 185 |
+
self.trainer_group = (
|
| 186 |
+
dist.new_group(TRAINER_RANKS)
|
| 187 |
+
if ddp_mode in (DdpMode.INSIDE, DdpMode.OUTSIDE)
|
| 188 |
+
else None
|
| 189 |
+
)
|
| 190 |
+
self.remote_em_rref = remote_em_rref
|
| 191 |
+
self.remote_net_rref = remote_net_rref
|
| 192 |
+
self.hybrid_module = HybridModel(
|
| 193 |
+
self.remote_em_rref,
|
| 194 |
+
self.remote_net_rref,
|
| 195 |
+
self.trainer_group if ddp_mode in (DdpMode.INSIDE,) else None,
|
| 196 |
+
)
|
| 197 |
+
self.ddp_params, self.non_ddp_params = (
|
| 198 |
+
self.hybrid_module.ddp_params,
|
| 199 |
+
self.hybrid_module.non_ddp_params,
|
| 200 |
+
)
|
| 201 |
+
if ddp_mode == DdpMode.OUTSIDE:
|
| 202 |
+
gLogger.info("Wrapping the whole hybrid module into DDP.")
|
| 203 |
+
self.ddp_params += self.non_ddp_params
|
| 204 |
+
self.non_ddp_params = ()
|
| 205 |
+
self.hybrid_module = DistributedDataParallel(
|
| 206 |
+
self.hybrid_module,
|
| 207 |
+
check_reduction=True,
|
| 208 |
+
process_group=self.trainer_group,
|
| 209 |
+
)
|
| 210 |
+
gLogger.info(
|
| 211 |
+
"Succeeded in creating a HybridModel instance with "
|
| 212 |
+
"%s ddp params and %s other local params.",
|
| 213 |
+
len(self.ddp_params),
|
| 214 |
+
len(self.non_ddp_params),
|
| 215 |
+
)
|
| 216 |
+
|
| 217 |
+
def destroy_pg(self):
|
| 218 |
+
if self.trainer_group:
|
| 219 |
+
dist.destroy_process_group(self.trainer_group)
|
| 220 |
+
|
| 221 |
+
def train_batch(
|
| 222 |
+
self,
|
| 223 |
+
mini_batch: FeatureSet,
|
| 224 |
+
trainer_has_less_inputs: bool,
|
| 225 |
+
simulate_uneven_inputs: bool,
|
| 226 |
+
):
|
| 227 |
+
grads_dict = None
|
| 228 |
+
|
| 229 |
+
if not simulate_uneven_inputs:
|
| 230 |
+
input_batches = [mini_batch]
|
| 231 |
+
else:
|
| 232 |
+
# Split into microbatches, and trim to simulate uneven inputs.
|
| 233 |
+
dense_features = mini_batch.dense_features
|
| 234 |
+
sparse_features = mini_batch.sparse_features
|
| 235 |
+
values = mini_batch.values
|
| 236 |
+
|
| 237 |
+
dense_microbatch = torch.split(dense_features, 2)
|
| 238 |
+
sparse_microbatch = torch.split(sparse_features, 2)
|
| 239 |
+
values_microbatch = torch.split(values, 2)
|
| 240 |
+
batches = []
|
| 241 |
+
for d, s, v in zip(dense_microbatch, sparse_microbatch, values_microbatch):
|
| 242 |
+
feature_set = FeatureSet(dense_features=d, sparse_features=s, values=v)
|
| 243 |
+
batches.append(feature_set)
|
| 244 |
+
|
| 245 |
+
if trainer_has_less_inputs:
|
| 246 |
+
input_batches = batches[: len(batches) // 2]
|
| 247 |
+
gLogger.info(
|
| 248 |
+
"Trainer reduced input patches from %s "
|
| 249 |
+
"to %s to simulate uneven inputs.",
|
| 250 |
+
len(batches),
|
| 251 |
+
len(input_batches),
|
| 252 |
+
)
|
| 253 |
+
else:
|
| 254 |
+
input_batches = batches
|
| 255 |
+
|
| 256 |
+
with (
|
| 257 |
+
self.hybrid_module.join()
|
| 258 |
+
if simulate_uneven_inputs
|
| 259 |
+
else contextlib.nullcontext()
|
| 260 |
+
):
|
| 261 |
+
for b in input_batches:
|
| 262 |
+
with dist_autograd.context() as context_id:
|
| 263 |
+
output = self.hybrid_module.forward(b)
|
| 264 |
+
loss = (output * mini_batch.values).sum()
|
| 265 |
+
dist_autograd.backward(context_id, [loss])
|
| 266 |
+
grads_dict = dist_autograd.get_gradients(context_id)
|
| 267 |
+
gLogger.info(
|
| 268 |
+
"Loss is %s for mini batch: %s. Grads dict has %s entries: %s",
|
| 269 |
+
loss,
|
| 270 |
+
mini_batch,
|
| 271 |
+
len(grads_dict),
|
| 272 |
+
grads_dict,
|
| 273 |
+
)
|
| 274 |
+
return (
|
| 275 |
+
tuple(grads_dict[param] for param in self.ddp_params),
|
| 276 |
+
tuple(grads_dict[param] for param in self.non_ddp_params),
|
| 277 |
+
)
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
def get_training_examples():
|
| 281 |
+
n = 16
|
| 282 |
+
training_examples = FeatureSet(
|
| 283 |
+
dense_features=torch.zeros((n, D_DENSE)),
|
| 284 |
+
sparse_features=torch.zeros(n, dtype=torch.long),
|
| 285 |
+
values=torch.zeros(n),
|
| 286 |
+
)
|
| 287 |
+
idx = 0
|
| 288 |
+
# Every example has another one that has exactly the same features but an
|
| 289 |
+
# opposite value. Therefore, their grads cancel each other in all-reduce.
|
| 290 |
+
for value in (-1, 1):
|
| 291 |
+
for x in (-1.0 * value, 1.0 * value):
|
| 292 |
+
for y in (1.0 * value, -1.0 * value):
|
| 293 |
+
for z in (0, 1):
|
| 294 |
+
training_examples.dense_features[idx, :] = torch.tensor((x, y))
|
| 295 |
+
training_examples.sparse_features[idx] = z
|
| 296 |
+
training_examples.values[idx] = value
|
| 297 |
+
idx += 1
|
| 298 |
+
|
| 299 |
+
# Split the examples among NUM_TRAINERS trainers
|
| 300 |
+
assert 0 == (n % NUM_TRAINERS)
|
| 301 |
+
examples_per_trainer = int(n / NUM_TRAINERS)
|
| 302 |
+
return [
|
| 303 |
+
FeatureSet(
|
| 304 |
+
dense_features=training_examples.dense_features[
|
| 305 |
+
start : start + examples_per_trainer, :
|
| 306 |
+
],
|
| 307 |
+
sparse_features=training_examples.sparse_features[
|
| 308 |
+
start : start + examples_per_trainer
|
| 309 |
+
],
|
| 310 |
+
values=training_examples.values[start : start + examples_per_trainer],
|
| 311 |
+
)
|
| 312 |
+
for start in range(0, n, examples_per_trainer)
|
| 313 |
+
]
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
shutdown_signal = threading.Condition()
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
def set_shutdown_signal():
|
| 320 |
+
global shutdown_signal
|
| 321 |
+
with shutdown_signal:
|
| 322 |
+
shutdown_signal.notify()
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
class DdpUnderDistAutogradTest(RpcAgentTestFixture):
|
| 326 |
+
@property
|
| 327 |
+
def world_size(self) -> int:
|
| 328 |
+
return WORLD_SIZE
|
| 329 |
+
|
| 330 |
+
def remote_worker_name(self) -> str:
|
| 331 |
+
# The name has to be consistent with that in 'dist_init' decorator.
|
| 332 |
+
return f"worker{REMOTE_WORKER_RANK}"
|
| 333 |
+
|
| 334 |
+
def trainer_name(self, rank):
|
| 335 |
+
# The name has to be consistent with that in 'dist_init' decorator.
|
| 336 |
+
return f"worker{rank}"
|
| 337 |
+
|
| 338 |
+
def _remote_worker_process(self, ddp_mode):
|
| 339 |
+
gLogger.info("The remote worker is running.")
|
| 340 |
+
dist.init_process_group(
|
| 341 |
+
backend="gloo",
|
| 342 |
+
init_method=INIT_METHOD_TEMPLATE.format(file_name=self.file_name),
|
| 343 |
+
world_size=self.world_size,
|
| 344 |
+
rank=self.rank,
|
| 345 |
+
)
|
| 346 |
+
|
| 347 |
+
if ddp_mode in (DdpMode.INSIDE, DdpMode.OUTSIDE):
|
| 348 |
+
# new_group needs to be called on ranks.
|
| 349 |
+
dist.new_group(TRAINER_RANKS)
|
| 350 |
+
|
| 351 |
+
global shutdown_signal
|
| 352 |
+
with shutdown_signal:
|
| 353 |
+
shutdown_signal.wait()
|
| 354 |
+
gLogger.info("Exiting remote worker.")
|
| 355 |
+
dist.destroy_process_group()
|
| 356 |
+
|
| 357 |
+
def _trainer_process(self, rank: int):
|
| 358 |
+
gLogger.info("Running the trainer #%s...", rank)
|
| 359 |
+
gLogger.info(
|
| 360 |
+
"Initing trainer process group by trainer #%s with ranks %s",
|
| 361 |
+
rank,
|
| 362 |
+
TRAINER_RANKS,
|
| 363 |
+
)
|
| 364 |
+
dist.init_process_group(
|
| 365 |
+
backend="gloo",
|
| 366 |
+
init_method=INIT_METHOD_TEMPLATE.format(file_name=self.file_name),
|
| 367 |
+
world_size=self.world_size,
|
| 368 |
+
rank=self.rank,
|
| 369 |
+
)
|
| 370 |
+
|
| 371 |
+
gLogger.info("Waiting for shutdown signal on trainer #%s...", rank)
|
| 372 |
+
|
| 373 |
+
global shutdown_signal
|
| 374 |
+
with shutdown_signal:
|
| 375 |
+
shutdown_signal.wait()
|
| 376 |
+
gLogger.info("Exiting the trainer #%s...", rank)
|
| 377 |
+
dist.destroy_process_group()
|
| 378 |
+
|
| 379 |
+
def _master_process(self, ddp_mode: DdpMode, simulate_uneven_inputs: bool):
|
| 380 |
+
gLogger.info("Running the master process...")
|
| 381 |
+
dist.init_process_group(
|
| 382 |
+
backend="gloo",
|
| 383 |
+
init_method=INIT_METHOD_TEMPLATE.format(file_name=self.file_name),
|
| 384 |
+
world_size=self.world_size,
|
| 385 |
+
rank=self.rank,
|
| 386 |
+
)
|
| 387 |
+
|
| 388 |
+
remote_em_rref = rpc.remote(
|
| 389 |
+
self.remote_worker_name(), RemoteEM, args=(NUM_EM_ROW, D_SPARSE)
|
| 390 |
+
)
|
| 391 |
+
remote_net_rref = rpc.remote(
|
| 392 |
+
self.remote_worker_name(), RemoteNet, args=(D_DENSE + D_SPARSE, D_HID)
|
| 393 |
+
)
|
| 394 |
+
gLogger.info("Created remote rrefs on master")
|
| 395 |
+
self.do_test_on_master(
|
| 396 |
+
ddp_mode, simulate_uneven_inputs, remote_em_rref, remote_net_rref
|
| 397 |
+
)
|
| 398 |
+
|
| 399 |
+
def do_test_on_master(
|
| 400 |
+
self,
|
| 401 |
+
ddp_mode: DdpMode,
|
| 402 |
+
simulate_uneven_inputs: bool,
|
| 403 |
+
remote_em_rref: rpc.RRef,
|
| 404 |
+
remote_net_rref: rpc.RRef,
|
| 405 |
+
):
|
| 406 |
+
if simulate_uneven_inputs:
|
| 407 |
+
gLogger.info(
|
| 408 |
+
"Running DDP + RPC test with simulating uneven inputs across trainers."
|
| 409 |
+
)
|
| 410 |
+
|
| 411 |
+
trainer_rrefs = []
|
| 412 |
+
for rank in TRAINER_RANKS:
|
| 413 |
+
trainer = self.trainer_name(rank)
|
| 414 |
+
trainer_rrefs.append(
|
| 415 |
+
rpc.remote(
|
| 416 |
+
trainer,
|
| 417 |
+
Trainer,
|
| 418 |
+
args=(remote_em_rref, remote_net_rref, ddp_mode, rank),
|
| 419 |
+
)
|
| 420 |
+
)
|
| 421 |
+
|
| 422 |
+
if ddp_mode in (DdpMode.INSIDE, DdpMode.OUTSIDE):
|
| 423 |
+
# new_group needs to be called on ranks.
|
| 424 |
+
dist.new_group(TRAINER_RANKS)
|
| 425 |
+
|
| 426 |
+
training_examples = get_training_examples()
|
| 427 |
+
for _ in range(3):
|
| 428 |
+
futures = []
|
| 429 |
+
num_trainers = len(trainer_rrefs)
|
| 430 |
+
for idx, trainer_rref in enumerate(trainer_rrefs):
|
| 431 |
+
# Half the trainers will deplete inputs earlier than the rest.
|
| 432 |
+
trainer_has_less_inputs = (
|
| 433 |
+
simulate_uneven_inputs and idx < num_trainers // 2
|
| 434 |
+
)
|
| 435 |
+
futures.append(
|
| 436 |
+
_remote_method_async(
|
| 437 |
+
Trainer.train_batch,
|
| 438 |
+
trainer_rref,
|
| 439 |
+
training_examples[idx],
|
| 440 |
+
trainer_has_less_inputs,
|
| 441 |
+
simulate_uneven_inputs,
|
| 442 |
+
)
|
| 443 |
+
)
|
| 444 |
+
|
| 445 |
+
for future in futures:
|
| 446 |
+
ddp_grads, non_ddp_grads = future.wait()
|
| 447 |
+
# When there are uneven inputs, it is not necessary that grads
|
| 448 |
+
# cancel each other out, since some trainers contribute 0 grad.
|
| 449 |
+
if not simulate_uneven_inputs:
|
| 450 |
+
for grad in ddp_grads:
|
| 451 |
+
self.assertEqual(
|
| 452 |
+
grad,
|
| 453 |
+
torch.zeros_like(grad),
|
| 454 |
+
msg=f"The grad for any ddp parameter should be zeros, because "
|
| 455 |
+
"the training examples' grads cancel each other. Received "
|
| 456 |
+
f"gradient {grad}",
|
| 457 |
+
)
|
| 458 |
+
for grad in non_ddp_grads:
|
| 459 |
+
self.assertNotEqual(
|
| 460 |
+
grad,
|
| 461 |
+
torch.zeros_like(grad),
|
| 462 |
+
msg="The grad for any non-ddp parameter shouldn't be zeros",
|
| 463 |
+
)
|
| 464 |
+
|
| 465 |
+
# Destroy process groups
|
| 466 |
+
for idx, trainer_rref in enumerate(trainer_rrefs):
|
| 467 |
+
_remote_method_async(Trainer.destroy_pg, trainer_rref).wait()
|
| 468 |
+
|
| 469 |
+
# Send shutdown signals.
|
| 470 |
+
for rank in TRAINER_RANKS:
|
| 471 |
+
trainer = self.trainer_name(rank)
|
| 472 |
+
rpc.rpc_sync(trainer, set_shutdown_signal, args=())
|
| 473 |
+
|
| 474 |
+
rpc.rpc_sync(self.remote_worker_name(), set_shutdown_signal, args=())
|
| 475 |
+
|
| 476 |
+
def _do_test(self, ddp_mode, simulate_uneven_inputs=False):
|
| 477 |
+
if self.rank == MASTER_RANK:
|
| 478 |
+
self._master_process(ddp_mode, simulate_uneven_inputs)
|
| 479 |
+
elif self.rank == REMOTE_WORKER_RANK:
|
| 480 |
+
self._remote_worker_process(ddp_mode)
|
| 481 |
+
elif self.rank in TRAINER_RANKS:
|
| 482 |
+
self._trainer_process(self.rank)
|
| 483 |
+
else:
|
| 484 |
+
raise RuntimeError(f"Unknown process rank: {self.rank}")
|
| 485 |
+
|
| 486 |
+
@requires_gloo()
|
| 487 |
+
@dist_init
|
| 488 |
+
def test_backward_no_ddp(self):
|
| 489 |
+
self._do_test(DdpMode.NONE)
|
| 490 |
+
|
| 491 |
+
@requires_gloo()
|
| 492 |
+
@dist_init
|
| 493 |
+
def test_backward_ddp_outside(self):
|
| 494 |
+
self._do_test(DdpMode.OUTSIDE)
|
| 495 |
+
|
| 496 |
+
@requires_gloo()
|
| 497 |
+
@dist_init
|
| 498 |
+
def test_backward_ddp_outside_uneven_inputs(self):
|
| 499 |
+
self._do_test(DdpMode.OUTSIDE, simulate_uneven_inputs=True)
|
| 500 |
+
|
| 501 |
+
@requires_gloo()
|
| 502 |
+
@dist_init
|
| 503 |
+
def test_backward_ddp_inside(self):
|
| 504 |
+
self._do_test(DdpMode.INSIDE)
|
| 505 |
+
|
| 506 |
+
|
| 507 |
+
# Common utils for both CPU and CUDA test suites
|
| 508 |
+
class CommonDdpComparisonTest(RpcAgentTestFixture):
|
| 509 |
+
@property
|
| 510 |
+
def world_size(self) -> int:
|
| 511 |
+
return NUM_TRAINERS
|
| 512 |
+
|
| 513 |
+
def trainer_name(self, rank):
|
| 514 |
+
# The name has to be consistent with that in 'dist_init' decorator.
|
| 515 |
+
return f"worker{rank}"
|
| 516 |
+
|
| 517 |
+
@staticmethod
|
| 518 |
+
def get_remote_grads(rref, context_id):
|
| 519 |
+
return dist_autograd.get_gradients(context_id)[rref.local_value().weight]
|
| 520 |
+
|
| 521 |
+
|
| 522 |
+
class DdpComparisonTest(CommonDdpComparisonTest):
|
| 523 |
+
def _run_test_ddp_comparision(self, simulate_uneven_inputs=False):
|
| 524 |
+
gLogger.info("Running trainer rank: %s", self.rank)
|
| 525 |
+
# Each trainer uses a different random seed. Otherwise, they are going
|
| 526 |
+
# to have exactly the same initial model parameters, input, and
|
| 527 |
+
# therefore grads. That means the grads will be the same before and
|
| 528 |
+
# after DDP's all-reduce.
|
| 529 |
+
torch.manual_seed(self.rank)
|
| 530 |
+
dist.init_process_group(
|
| 531 |
+
backend="gloo",
|
| 532 |
+
# Postfix file_name with "pg" since file_name is also used by RPC agent
|
| 533 |
+
init_method=INIT_METHOD_TEMPLATE.format(file_name=f"{self.file_name}_pg"),
|
| 534 |
+
world_size=self.world_size,
|
| 535 |
+
rank=self.rank,
|
| 536 |
+
)
|
| 537 |
+
net = nn.Linear(2, 3)
|
| 538 |
+
ddp_net = DistributedDataParallel(net)
|
| 539 |
+
|
| 540 |
+
# Odd ranks join early if simulate_uneven_inputs.
|
| 541 |
+
num_inputs = 1
|
| 542 |
+
if simulate_uneven_inputs:
|
| 543 |
+
if self.rank % 2 == 0:
|
| 544 |
+
num_inputs += 2
|
| 545 |
+
inputs_list = [torch.rand((3, 2)) for _ in range(num_inputs)]
|
| 546 |
+
|
| 547 |
+
if simulate_uneven_inputs:
|
| 548 |
+
gLogger.info(
|
| 549 |
+
"Rank %s training with %s inputs.", self.rank, len(inputs_list)
|
| 550 |
+
)
|
| 551 |
+
|
| 552 |
+
# Use distributed autograd. The gradients will be in RPC context map.
|
| 553 |
+
grads_dict = {}
|
| 554 |
+
with ddp_net.join(simulate_uneven_inputs):
|
| 555 |
+
for i, inputs in enumerate(inputs_list):
|
| 556 |
+
with dist_autograd.context() as context_id:
|
| 557 |
+
loss = ddp_net(inputs).norm()
|
| 558 |
+
dist_autograd.backward(context_id, [loss])
|
| 559 |
+
grads_dict = dist_autograd.get_gradients(context_id)
|
| 560 |
+
gLogger.info("Trainer #%s got grad dict: %s", self.rank, grads_dict)
|
| 561 |
+
|
| 562 |
+
# Use local autograd. The gradients will be in each variable's '.grad'.
|
| 563 |
+
ddp_net.zero_grad()
|
| 564 |
+
loss = ddp_net(inputs).norm()
|
| 565 |
+
loss.backward()
|
| 566 |
+
|
| 567 |
+
# The gradients should be the same
|
| 568 |
+
for param in net.parameters():
|
| 569 |
+
self.assertTrue(
|
| 570 |
+
param in grads_dict,
|
| 571 |
+
msg=f"Param {param} is not in dist_auto grad dict {grads_dict} for iteration {i}",
|
| 572 |
+
)
|
| 573 |
+
self.assertEqual(
|
| 574 |
+
grads_dict[param],
|
| 575 |
+
param.grad,
|
| 576 |
+
msg=f"The grads for param {param} are different under local "
|
| 577 |
+
f"and dist autograd: {param.grad} \n---\n {grads_dict[param]} for iteration {i}",
|
| 578 |
+
)
|
| 579 |
+
dist.destroy_process_group()
|
| 580 |
+
|
| 581 |
+
@requires_gloo()
|
| 582 |
+
@dist_init
|
| 583 |
+
def test_ddp_comparison(self):
|
| 584 |
+
self._run_test_ddp_comparision()
|
| 585 |
+
|
| 586 |
+
@requires_gloo()
|
| 587 |
+
@dist_init
|
| 588 |
+
def test_ddp_comparison_uneven_inputs(self):
|
| 589 |
+
# test with simulating uneven inputs in DDP
|
| 590 |
+
self._run_test_ddp_comparision(simulate_uneven_inputs=True)
|
| 591 |
+
|
| 592 |
+
@requires_gloo()
|
| 593 |
+
@dist_init
|
| 594 |
+
def test_ddp_dist_autograd_sparse_grads(self):
|
| 595 |
+
# Each trainer uses a different random seed. Otherwise, they are going
|
| 596 |
+
# to have exactly the same initial model parameters, input, and
|
| 597 |
+
# therefore grads. That means the grads will be the same before and
|
| 598 |
+
# after DDP's all-reduce.
|
| 599 |
+
torch.manual_seed(self.rank)
|
| 600 |
+
dist.init_process_group(
|
| 601 |
+
backend="gloo",
|
| 602 |
+
init_method=INIT_METHOD_TEMPLATE.format(file_name=self.file_name),
|
| 603 |
+
world_size=self.world_size,
|
| 604 |
+
rank=self.rank,
|
| 605 |
+
)
|
| 606 |
+
|
| 607 |
+
model = nn.EmbeddingBag(10, 3, sparse=True)
|
| 608 |
+
ddp_model = DistributedDataParallel(model)
|
| 609 |
+
|
| 610 |
+
# Different inputs for each
|
| 611 |
+
input = torch.LongTensor(10).random_(0, 10)
|
| 612 |
+
offsets = torch.LongTensor([0, 4])
|
| 613 |
+
|
| 614 |
+
# Run local.
|
| 615 |
+
loss = ddp_model(input, offsets).sum()
|
| 616 |
+
loss.backward()
|
| 617 |
+
|
| 618 |
+
with dist_autograd.context() as context_id:
|
| 619 |
+
loss = ddp_model(input, offsets).sum()
|
| 620 |
+
dist_autograd.backward(context_id, [loss])
|
| 621 |
+
grads_dict = dist_autograd.get_gradients(context_id)
|
| 622 |
+
self.assertEqual(1, len(grads_dict))
|
| 623 |
+
self.assertEqual(model.weight.grad, grads_dict[model.weight])
|
| 624 |
+
|
| 625 |
+
@requires_gloo()
|
| 626 |
+
@dist_init
|
| 627 |
+
def test_ddp_dist_autograd_local_vs_remote(self):
|
| 628 |
+
# Each trainer uses a different random seed. Otherwise, they are going
|
| 629 |
+
# to have exactly the same initial model parameters, input, and
|
| 630 |
+
# therefore grads. That means the grads will be the same before and
|
| 631 |
+
# after DDP's all-reduce.
|
| 632 |
+
torch.manual_seed(self.rank)
|
| 633 |
+
dist.init_process_group(
|
| 634 |
+
backend="gloo",
|
| 635 |
+
init_method=INIT_METHOD_TEMPLATE.format(file_name=self.file_name),
|
| 636 |
+
world_size=self.world_size,
|
| 637 |
+
rank=self.rank,
|
| 638 |
+
)
|
| 639 |
+
|
| 640 |
+
# Use two different remote device input string, w/ and w/o the default
|
| 641 |
+
# device string "cpu", respectively.
|
| 642 |
+
for remote_device in ["worker0/cpu", "worker0"]:
|
| 643 |
+
remote_layer1 = RemoteModule(
|
| 644 |
+
remote_device=remote_device, module_cls=nn.Linear, args=(10, 5, False)
|
| 645 |
+
)
|
| 646 |
+
layer1 = nn.Linear(10, 5, False)
|
| 647 |
+
# Start with the same parameters for remote and local
|
| 648 |
+
layer1.weight = remote_layer1.module_rref.to_here().weight
|
| 649 |
+
|
| 650 |
+
# Run local case.
|
| 651 |
+
layer2 = nn.Linear(5, 1)
|
| 652 |
+
inputs = torch.rand((10, 10))
|
| 653 |
+
ddp_model = DistributedDataParallel(layer2)
|
| 654 |
+
loss = ddp_model(layer1(inputs)).sum()
|
| 655 |
+
loss.backward()
|
| 656 |
+
|
| 657 |
+
# Run remote case.
|
| 658 |
+
with dist_autograd.context() as context_id:
|
| 659 |
+
loss = ddp_model(remote_layer1(inputs)).sum()
|
| 660 |
+
dist_autograd.backward(context_id, [loss])
|
| 661 |
+
grads_dict = dist_autograd.get_gradients(context_id)
|
| 662 |
+
dist.barrier()
|
| 663 |
+
self.assertEqual(layer2.weight.grad, grads_dict[layer2.weight])
|
| 664 |
+
self.assertEqual(
|
| 665 |
+
layer1.weight.grad,
|
| 666 |
+
rpc.rpc_sync(
|
| 667 |
+
"worker0",
|
| 668 |
+
CommonDdpComparisonTest.get_remote_grads,
|
| 669 |
+
args=(remote_layer1.module_rref, context_id),
|
| 670 |
+
),
|
| 671 |
+
)
|
| 672 |
+
|
| 673 |
+
|
| 674 |
+
class CudaDdpComparisonTest(CommonDdpComparisonTest):
|
| 675 |
+
@skip_if_lt_x_gpu(NUM_TRAINERS)
|
| 676 |
+
@requires_nccl()
|
| 677 |
+
@dist_init
|
| 678 |
+
@skip_if_rocm_multiprocess
|
| 679 |
+
def test_ddp_dist_autograd_local_vs_remote_gpu(self):
|
| 680 |
+
# Each trainer uses a different random seed. Otherwise, they are going
|
| 681 |
+
# to have exactly the same initial model parameters, input, and
|
| 682 |
+
# therefore grads. That means the grads will be the same before and
|
| 683 |
+
# after DDP's all-reduce.
|
| 684 |
+
torch.manual_seed(self.rank)
|
| 685 |
+
dist.init_process_group(
|
| 686 |
+
backend="gloo",
|
| 687 |
+
init_method=INIT_METHOD_TEMPLATE.format(file_name=self.file_name),
|
| 688 |
+
world_size=self.world_size,
|
| 689 |
+
rank=self.rank,
|
| 690 |
+
)
|
| 691 |
+
|
| 692 |
+
remote_layer1 = RemoteModule(
|
| 693 |
+
remote_device="worker0/cpu", module_cls=nn.Linear, args=(10, 7, False)
|
| 694 |
+
)
|
| 695 |
+
layer1 = nn.Linear(10, 7, False)
|
| 696 |
+
# Start with the same parameters for remote and local
|
| 697 |
+
layer1.weight = remote_layer1.module_rref.to_here().weight
|
| 698 |
+
|
| 699 |
+
layer2 = nn.Linear(7, 5).cuda(self.rank)
|
| 700 |
+
ddp_layer2 = DistributedDataParallel(layer2, device_ids=[self.rank])
|
| 701 |
+
|
| 702 |
+
remote_layer3 = RemoteModule(
|
| 703 |
+
remote_device="worker0/cpu", module_cls=nn.Linear, args=(5, 3, False)
|
| 704 |
+
)
|
| 705 |
+
layer3 = nn.Linear(5, 3, False)
|
| 706 |
+
# Start with the same parameters for remote and local
|
| 707 |
+
layer3.weight = remote_layer3.module_rref.to_here().weight
|
| 708 |
+
|
| 709 |
+
layer4 = nn.Linear(3, 1).cuda(self.rank)
|
| 710 |
+
ddp_layer4 = DistributedDataParallel(layer4, device_ids=[self.rank])
|
| 711 |
+
|
| 712 |
+
# Run local case.
|
| 713 |
+
inputs = torch.rand((10, 10))
|
| 714 |
+
loss = ddp_layer4(
|
| 715 |
+
layer3(ddp_layer2(layer1(inputs).cuda(self.rank)).cpu()).cuda(self.rank)
|
| 716 |
+
).sum()
|
| 717 |
+
loss.backward()
|
| 718 |
+
|
| 719 |
+
# Run remote case.
|
| 720 |
+
with dist_autograd.context() as context_id:
|
| 721 |
+
loss = ddp_layer4(
|
| 722 |
+
remote_layer3(
|
| 723 |
+
ddp_layer2(remote_layer1(inputs).cuda(self.rank)).cpu()
|
| 724 |
+
).cuda(self.rank)
|
| 725 |
+
).sum()
|
| 726 |
+
dist_autograd.backward(context_id, [loss])
|
| 727 |
+
grads_dict = dist_autograd.get_gradients(context_id)
|
| 728 |
+
dist.barrier()
|
| 729 |
+
self.assertEqual(
|
| 730 |
+
layer1.weight.grad,
|
| 731 |
+
rpc.rpc_sync(
|
| 732 |
+
"worker0",
|
| 733 |
+
CommonDdpComparisonTest.get_remote_grads,
|
| 734 |
+
args=(remote_layer1.module_rref, context_id),
|
| 735 |
+
),
|
| 736 |
+
)
|
| 737 |
+
self.assertEqual(layer2.weight.grad, grads_dict[layer2.weight])
|
| 738 |
+
self.assertEqual(
|
| 739 |
+
layer3.weight.grad,
|
| 740 |
+
rpc.rpc_sync(
|
| 741 |
+
"worker0",
|
| 742 |
+
CommonDdpComparisonTest.get_remote_grads,
|
| 743 |
+
args=(remote_layer3.module_rref, context_id),
|
| 744 |
+
),
|
| 745 |
+
)
|
| 746 |
+
self.assertEqual(layer4.weight.grad, grads_dict[layer4.weight])
|
pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/distributed/distributed_test.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/distributed/distributed_utils.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
|
| 3 |
+
from contextlib import contextmanager
|
| 4 |
+
from datetime import timedelta
|
| 5 |
+
from functools import partial, wraps
|
| 6 |
+
|
| 7 |
+
import torch.distributed as dist
|
| 8 |
+
import torch.distributed.distributed_c10d as c10d
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class MockProcessGroup(dist.ProcessGroup):
|
| 12 |
+
def __init__(self, rank, world):
|
| 13 |
+
super().__init__(rank, world)
|
| 14 |
+
|
| 15 |
+
def getBackendName(self):
|
| 16 |
+
return "mock_process_group"
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def create_mock_pg(prefix_store, rank, world_size, timeout):
|
| 20 |
+
return MockProcessGroup(rank, world_size)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
dist.Backend.register_backend("mock_process_group", create_mock_pg)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def mock_init_dist(rank, world_size):
|
| 27 |
+
# !!! WARNING !!!
|
| 28 |
+
# Kids don't try this at home, this is a cute pile of hacks that
|
| 29 |
+
# depends on a small mountain of c10d internals
|
| 30 |
+
assert not dist.is_initialized()
|
| 31 |
+
store = dist.HashStore()
|
| 32 |
+
# Trick _store_based_barrier into believing everyone else already checked-in
|
| 33 |
+
# Zero is the group index
|
| 34 |
+
store.add(f"{c10d.STORE_BASED_BARRIER_PREFIX}:0", world_size - 1)
|
| 35 |
+
dist.init_process_group(
|
| 36 |
+
backend="mock_process_group",
|
| 37 |
+
rank=rank,
|
| 38 |
+
world_size=world_size,
|
| 39 |
+
store=store,
|
| 40 |
+
group_name="fake",
|
| 41 |
+
timeout=timedelta(seconds=1),
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
@contextmanager
|
| 46 |
+
def with_dist(rank=0, world_size=2):
|
| 47 |
+
"""
|
| 48 |
+
Context manager that initializer c10d with a fake process group.
|
| 49 |
+
"""
|
| 50 |
+
mock_init_dist(rank=rank, world_size=world_size)
|
| 51 |
+
try:
|
| 52 |
+
yield
|
| 53 |
+
finally:
|
| 54 |
+
dist.destroy_process_group()
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def with_fake_comms(func=None, rank=0, world_size=2):
|
| 58 |
+
"""
|
| 59 |
+
Function wrapper that inits a fake process group designed for testing.
|
| 60 |
+
Right now only querying for world size is available
|
| 61 |
+
"""
|
| 62 |
+
if func is None:
|
| 63 |
+
return partial(with_fake_comms, rank=rank, world_size=world_size)
|
| 64 |
+
|
| 65 |
+
@wraps(func)
|
| 66 |
+
def wrapper(self, *args, **kwargs):
|
| 67 |
+
with with_dist(rank, world_size):
|
| 68 |
+
func(self, *args, **kwargs)
|
| 69 |
+
|
| 70 |
+
return wrapper
|
pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/distributed/fake_pg.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
|
| 3 |
+
import torch.distributed as dist
|
| 4 |
+
from torch._C._distributed_c10d import FakeProcessGroup
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class FakeStore(dist.Store):
|
| 8 |
+
"""
|
| 9 |
+
A fake store is a fake Key-Value store simply for initialization usage
|
| 10 |
+
the of fake process group, one can either use FakeStore or HashStore.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def _create_fake_pg(common_opts, backend_opts):
|
| 15 |
+
"""
|
| 16 |
+
A fake process group (not related to FakeTensor) is a process group which
|
| 17 |
+
doesn't actually do any communication, it just hallucinates some
|
| 18 |
+
communication. You can run a single rank with a fake process group
|
| 19 |
+
without needing multiple processes (simulates per-rank behavior)
|
| 20 |
+
|
| 21 |
+
NOTE: This is not a real process group, and it would produce wrong results
|
| 22 |
+
for every collective. It should be used as a convenient tool when playing
|
| 23 |
+
with distributed but don't care about the actual data.
|
| 24 |
+
"""
|
| 25 |
+
return FakeProcessGroup(
|
| 26 |
+
common_opts.group_rank, common_opts.group_size, backend_opts
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
dist.Backend.register_backend(
|
| 31 |
+
"fake", _create_fake_pg, extended_api=True, devices=["cpu", "cuda", "hpu"]
|
| 32 |
+
)
|
pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/distributed/multi_threaded_pg.py
ADDED
|
@@ -0,0 +1,573 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
|
| 3 |
+
import sys
|
| 4 |
+
import threading
|
| 5 |
+
import weakref
|
| 6 |
+
from dataclasses import dataclass
|
| 7 |
+
from functools import partial, reduce
|
| 8 |
+
from typing import Optional, Union
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
import torch.distributed as dist
|
| 12 |
+
from torch._C._distributed_c10d import (
|
| 13 |
+
_create_work_from_future,
|
| 14 |
+
AllgatherOptions,
|
| 15 |
+
AllreduceOptions,
|
| 16 |
+
AllToAllOptions,
|
| 17 |
+
BarrierOptions,
|
| 18 |
+
BroadcastOptions,
|
| 19 |
+
ReduceOp,
|
| 20 |
+
ReduceScatterOptions,
|
| 21 |
+
ScatterOptions,
|
| 22 |
+
Store,
|
| 23 |
+
)
|
| 24 |
+
from torch.distributed.distributed_c10d import _CollOp, _store_based_barrier, P2POp
|
| 25 |
+
from torch.futures import Future
|
| 26 |
+
from torch.utils import _pytree as pytree
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
"""
|
| 30 |
+
TODO:
|
| 31 |
+
Lots of missing collectives.
|
| 32 |
+
Collectives validation.
|
| 33 |
+
Make timeout robust by making collectives respect the test deadline.
|
| 34 |
+
Make tests robust by making collectives interruptible.
|
| 35 |
+
We need some synchronization around cleanup to ensure that timedout ranks don't cause spurious failures.
|
| 36 |
+
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def flatten_list(lst):
|
| 41 |
+
return pytree.tree_leaves(lst)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def ret_work(ret):
|
| 45 |
+
fut = Future()
|
| 46 |
+
fut.set_result(ret)
|
| 47 |
+
return _create_work_from_future(fut)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def binop_reduce(tensors, op):
|
| 51 |
+
res = op(torch.stack(tensors), dim=0)
|
| 52 |
+
if isinstance(res, torch.Tensor):
|
| 53 |
+
return res
|
| 54 |
+
# min/max return a namedtuple
|
| 55 |
+
return res.values
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def bitwise_reduce(tensors, op):
|
| 59 |
+
return reduce(op, tensors)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
_reduce_ops = {
|
| 63 |
+
ReduceOp.SUM: partial(binop_reduce, op=torch.sum),
|
| 64 |
+
ReduceOp.AVG: partial(binop_reduce, op=torch.mean),
|
| 65 |
+
ReduceOp.PRODUCT: partial(binop_reduce, op=torch.prod),
|
| 66 |
+
ReduceOp.MIN: partial(binop_reduce, op=torch.min),
|
| 67 |
+
ReduceOp.MAX: partial(binop_reduce, op=torch.max),
|
| 68 |
+
ReduceOp.BAND: partial(bitwise_reduce, op=torch.bitwise_and),
|
| 69 |
+
ReduceOp.BOR: partial(bitwise_reduce, op=torch.bitwise_or),
|
| 70 |
+
ReduceOp.BXOR: partial(bitwise_reduce, op=torch.bitwise_xor),
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
class AllToAll:
|
| 75 |
+
@torch.no_grad()
|
| 76 |
+
def work(self, data):
|
| 77 |
+
world_size = len(data)
|
| 78 |
+
for dest_rank in range(world_size):
|
| 79 |
+
output_tensor_list, _ = data[dest_rank]
|
| 80 |
+
for src_rank in range(world_size):
|
| 81 |
+
_, input_tensor_list = data[src_rank]
|
| 82 |
+
output_tensor_list[src_rank].copy_(input_tensor_list[dest_rank])
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class AllToAllBase:
|
| 86 |
+
@torch.no_grad()
|
| 87 |
+
def work(self, data):
|
| 88 |
+
world_size = len(data)
|
| 89 |
+
for dest_rank in range(world_size):
|
| 90 |
+
output_buffer, _, output_split_sizes, _ = data[dest_rank]
|
| 91 |
+
|
| 92 |
+
output_indexes = self._size_cumsum(
|
| 93 |
+
output_buffer.size(0), output_split_sizes, world_size
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
for src_rank in range(world_size):
|
| 97 |
+
_, input_buffer, _, input_split_sizes = data[src_rank]
|
| 98 |
+
input_indexes = self._size_cumsum(
|
| 99 |
+
input_buffer.size(0), input_split_sizes, world_size
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
output_buffer[
|
| 103 |
+
output_indexes[src_rank] : output_indexes[src_rank + 1]
|
| 104 |
+
].copy_(
|
| 105 |
+
input_buffer[
|
| 106 |
+
input_indexes[dest_rank] : input_indexes[dest_rank + 1]
|
| 107 |
+
]
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
def _size_cumsum(
|
| 111 |
+
self,
|
| 112 |
+
buf_size: int,
|
| 113 |
+
sizes: Union[torch.Tensor, list[int], None],
|
| 114 |
+
world_size: int,
|
| 115 |
+
) -> torch.Tensor:
|
| 116 |
+
if sizes is None or len(sizes) == 0:
|
| 117 |
+
sizes = torch.full((world_size,), buf_size // world_size, dtype=torch.int64)
|
| 118 |
+
if not isinstance(sizes, torch.Tensor):
|
| 119 |
+
sizes = torch.tensor(sizes, dtype=torch.int64)
|
| 120 |
+
assert sizes.dtype == torch.int64
|
| 121 |
+
sizes = torch.cumsum(
|
| 122 |
+
torch.cat(
|
| 123 |
+
(torch.tensor([0], dtype=torch.int64, device=sizes.device), sizes),
|
| 124 |
+
dim=0,
|
| 125 |
+
),
|
| 126 |
+
dim=0,
|
| 127 |
+
)
|
| 128 |
+
return sizes
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
class AllReduce:
|
| 132 |
+
def __init__(self, op):
|
| 133 |
+
if op.op not in _reduce_ops:
|
| 134 |
+
raise NotImplementedError(
|
| 135 |
+
f"AllReduce op {op.op} not supported on multithreaded pg for now."
|
| 136 |
+
)
|
| 137 |
+
self.op = op.op
|
| 138 |
+
|
| 139 |
+
@torch.no_grad()
|
| 140 |
+
def work(self, data):
|
| 141 |
+
for i in range(len(data[0])):
|
| 142 |
+
# use rank0 as the device for sum
|
| 143 |
+
rank_0_device = data[0][i].device
|
| 144 |
+
# collect all data to the list and make them
|
| 145 |
+
# all on rank 0 device
|
| 146 |
+
tensors = [
|
| 147 |
+
data[src_rank][i].to(rank_0_device) for src_rank in range(0, len(data))
|
| 148 |
+
]
|
| 149 |
+
|
| 150 |
+
# now mimic reduce across all ranks
|
| 151 |
+
res = _reduce_ops[self.op](tensors)
|
| 152 |
+
|
| 153 |
+
# copy all the reduced value to each rank
|
| 154 |
+
for src_rank in range(len(data)):
|
| 155 |
+
data[src_rank][i].copy_(res.to(data[src_rank][i].device))
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
class AllGather:
|
| 159 |
+
@torch.no_grad()
|
| 160 |
+
def work(self, data):
|
| 161 |
+
for src_rank in range(len(data)):
|
| 162 |
+
in_tensor_list = data[src_rank][1]
|
| 163 |
+
# Can't handle all_gather with multiple tensors
|
| 164 |
+
assert len(in_tensor_list) == 1
|
| 165 |
+
src_tensor = in_tensor_list[0]
|
| 166 |
+
|
| 167 |
+
for dest in data:
|
| 168 |
+
dest_tensor = dest[0][0][src_rank]
|
| 169 |
+
dest_tensor.copy_(src_tensor)
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
class Scatter:
|
| 173 |
+
def __init__(self, src):
|
| 174 |
+
self.src = src
|
| 175 |
+
|
| 176 |
+
@torch.no_grad()
|
| 177 |
+
def work(self, data):
|
| 178 |
+
src_in_tensor_list = data[self.src][1]
|
| 179 |
+
# Can't handle scatter with multiple input tensor list
|
| 180 |
+
assert len(src_in_tensor_list) == 1
|
| 181 |
+
src_in_tensors = src_in_tensor_list[0]
|
| 182 |
+
|
| 183 |
+
for rank, each_rank_data in enumerate(data):
|
| 184 |
+
out_tensor_list = each_rank_data[0]
|
| 185 |
+
# Can't handle scatter with multiple output tensor
|
| 186 |
+
assert len(out_tensor_list) == 1
|
| 187 |
+
dest_tensor = out_tensor_list[0]
|
| 188 |
+
dest_tensor.copy_(src_in_tensors[rank])
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
class Gather:
|
| 192 |
+
def __init__(self, dst):
|
| 193 |
+
self.dst = dst
|
| 194 |
+
|
| 195 |
+
@torch.no_grad()
|
| 196 |
+
def work(self, data):
|
| 197 |
+
# Can't handle gather with multiple tensor lists
|
| 198 |
+
assert len(data[self.dst][0]) == 1
|
| 199 |
+
out_tensor_list = data[self.dst][0][0]
|
| 200 |
+
for rank, each_rank_data in enumerate(data):
|
| 201 |
+
src_in_tensor_list = each_rank_data[1]
|
| 202 |
+
# Can't handle gather with multiple tensor lists
|
| 203 |
+
assert len(src_in_tensor_list) == 1
|
| 204 |
+
dest_tensor = out_tensor_list[rank]
|
| 205 |
+
dest_tensor.copy_(src_in_tensor_list[0])
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
class ReduceScatter:
|
| 209 |
+
def __init__(self, op):
|
| 210 |
+
if op != dist.ReduceOp.SUM and op != dist.ReduceOp.AVG:
|
| 211 |
+
raise NotImplementedError(f"ReduceScatter does not support {op}")
|
| 212 |
+
self.op = op
|
| 213 |
+
|
| 214 |
+
@torch.no_grad()
|
| 215 |
+
def work(self, data):
|
| 216 |
+
start_reduction = [False for _ in range(len(data))]
|
| 217 |
+
for each_rank_data in data:
|
| 218 |
+
# Can't handle reduce_scatter with multiple scatter list
|
| 219 |
+
assert len(each_rank_data[1]) == 1
|
| 220 |
+
to_scatter = each_rank_data[1][0]
|
| 221 |
+
for i in range(len(to_scatter)):
|
| 222 |
+
dest_tensor_on_rank_i = data[i][0]
|
| 223 |
+
# Can't handle reduce_scatter with multiple output tensor
|
| 224 |
+
assert len(dest_tensor_on_rank_i) == 1
|
| 225 |
+
dst_tensor_device = dest_tensor_on_rank_i[0].device
|
| 226 |
+
if not start_reduction[i]:
|
| 227 |
+
dest_tensor_on_rank_i[0].copy_(to_scatter[i].to(dst_tensor_device))
|
| 228 |
+
start_reduction[i] = True
|
| 229 |
+
else:
|
| 230 |
+
dest_tensor_on_rank_i[0].add_(to_scatter[i].to(dst_tensor_device))
|
| 231 |
+
if self.op == dist.ReduceOp.AVG:
|
| 232 |
+
num_ranks = len(data)
|
| 233 |
+
for each_rank_data in data:
|
| 234 |
+
each_rank_data[0][0] /= num_ranks
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
class Broadcast:
|
| 238 |
+
def __init__(self, src):
|
| 239 |
+
self.src = src
|
| 240 |
+
|
| 241 |
+
@torch.no_grad()
|
| 242 |
+
def work(self, data):
|
| 243 |
+
in_tensor_list = flatten_list(data[self.src])
|
| 244 |
+
for i in range(len(data)):
|
| 245 |
+
out_tensor_list = flatten_list(data[i])
|
| 246 |
+
for j in range(len(in_tensor_list)):
|
| 247 |
+
out_tensor_list[j].copy_(in_tensor_list[j])
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
class Collective:
|
| 251 |
+
def __init__(self, world_size, collective, pg):
|
| 252 |
+
self._world_size = world_size
|
| 253 |
+
self._collective = collective
|
| 254 |
+
|
| 255 |
+
self._start_cond = threading.Condition()
|
| 256 |
+
self._done_cond = threading.Condition()
|
| 257 |
+
|
| 258 |
+
self._data = [None] * world_size
|
| 259 |
+
self._count = 0
|
| 260 |
+
self._done = False
|
| 261 |
+
|
| 262 |
+
self._pg = pg
|
| 263 |
+
|
| 264 |
+
def join(self, rank, data):
|
| 265 |
+
with self._start_cond:
|
| 266 |
+
self._data[rank] = data
|
| 267 |
+
self._count += 1
|
| 268 |
+
|
| 269 |
+
# notify rank 0
|
| 270 |
+
if self._count == self._world_size:
|
| 271 |
+
if rank > 0:
|
| 272 |
+
self._start_cond.notify()
|
| 273 |
+
|
| 274 |
+
if rank == 0:
|
| 275 |
+
self._start_cond.wait_for(
|
| 276 |
+
lambda: self._count == self._world_size
|
| 277 |
+
or self._pg._terminate.is_set()
|
| 278 |
+
)
|
| 279 |
+
# SystemExit is not a subclass of Exception but BaseException
|
| 280 |
+
# and can be distinguished from normal exception raised from program errors
|
| 281 |
+
# so that we can hide it from the exception queue
|
| 282 |
+
if self._pg._terminate.is_set():
|
| 283 |
+
sys.exit("Test termination event occurs.")
|
| 284 |
+
|
| 285 |
+
with self._done_cond:
|
| 286 |
+
# wait for rank 0 to finish
|
| 287 |
+
if rank > 0:
|
| 288 |
+
self._done_cond.wait_for(
|
| 289 |
+
lambda: self._done or self._pg._terminate.is_set()
|
| 290 |
+
)
|
| 291 |
+
if self._pg._terminate.is_set():
|
| 292 |
+
sys.exit("Test termination event occurs.")
|
| 293 |
+
else:
|
| 294 |
+
# copy data around
|
| 295 |
+
self._collective.work(self._data)
|
| 296 |
+
self._done = True
|
| 297 |
+
self._done_cond.notify_all()
|
| 298 |
+
return ret_work(data)
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
class ProcessLocalGroup(dist.ProcessGroup):
|
| 302 |
+
_coll_lock = threading.Lock()
|
| 303 |
+
_cur_coll_on_pgs = {}
|
| 304 |
+
|
| 305 |
+
_terminate = threading.Event()
|
| 306 |
+
|
| 307 |
+
@classmethod
|
| 308 |
+
def _start_coll(cls, collective, pg):
|
| 309 |
+
with cls._coll_lock:
|
| 310 |
+
# pg_name is unique, we use that to record the mapping between pg and collective
|
| 311 |
+
if pg.pg_name not in cls._cur_coll_on_pgs:
|
| 312 |
+
cls._cur_coll_on_pgs[pg.pg_name] = Collective(
|
| 313 |
+
pg.size(), collective, cls
|
| 314 |
+
)
|
| 315 |
+
return cls._cur_coll_on_pgs[pg.pg_name]
|
| 316 |
+
|
| 317 |
+
@classmethod
|
| 318 |
+
def _end_coll(cls, collective, pg):
|
| 319 |
+
# This is racily called by all ranks, so only one will work
|
| 320 |
+
with cls._coll_lock:
|
| 321 |
+
if (
|
| 322 |
+
pg.pg_name in cls._cur_coll_on_pgs
|
| 323 |
+
and cls._cur_coll_on_pgs[pg.pg_name] == collective
|
| 324 |
+
):
|
| 325 |
+
cls._cur_coll_on_pgs.pop(pg.pg_name)
|
| 326 |
+
|
| 327 |
+
@classmethod
|
| 328 |
+
def exception_handle(cls, exc):
|
| 329 |
+
cls._terminate.set()
|
| 330 |
+
for coll in cls._cur_coll_on_pgs.values():
|
| 331 |
+
with coll._start_cond:
|
| 332 |
+
coll._start_cond.notify()
|
| 333 |
+
with coll._done_cond:
|
| 334 |
+
coll._done_cond.notify_all()
|
| 335 |
+
|
| 336 |
+
@classmethod
|
| 337 |
+
def reset(cls):
|
| 338 |
+
with cls._coll_lock:
|
| 339 |
+
cls._cur_coll_on_pgs = {}
|
| 340 |
+
cls._terminate.clear()
|
| 341 |
+
|
| 342 |
+
def alltoall_base(
|
| 343 |
+
self,
|
| 344 |
+
output_buffer: torch.Tensor,
|
| 345 |
+
input_buffer: torch.Tensor,
|
| 346 |
+
output_split_sizes: Optional[list[int]],
|
| 347 |
+
input_split_sizes: Optional[list[int]],
|
| 348 |
+
opts=AllToAllOptions(),
|
| 349 |
+
) -> torch.Tensor:
|
| 350 |
+
coll = ProcessLocalGroup._start_coll(AllToAllBase(), self)
|
| 351 |
+
res = coll.join(
|
| 352 |
+
self._rank,
|
| 353 |
+
(output_buffer, input_buffer, output_split_sizes, input_split_sizes),
|
| 354 |
+
)
|
| 355 |
+
ProcessLocalGroup._end_coll(coll, self)
|
| 356 |
+
return res
|
| 357 |
+
|
| 358 |
+
def alltoall(self, output_tensor_list, input_tensor_list, opts=AllToAllOptions()):
|
| 359 |
+
coll = ProcessLocalGroup._start_coll(AllToAll(), self)
|
| 360 |
+
res = coll.join(self._rank, (output_tensor_list, input_tensor_list))
|
| 361 |
+
ProcessLocalGroup._end_coll(coll, self)
|
| 362 |
+
return res
|
| 363 |
+
|
| 364 |
+
def allreduce(self, tensor_list, opts=AllreduceOptions()):
|
| 365 |
+
coll = ProcessLocalGroup._start_coll(AllReduce(opts.reduceOp), self)
|
| 366 |
+
res = coll.join(self._rank, tensor_list)
|
| 367 |
+
ProcessLocalGroup._end_coll(coll, self)
|
| 368 |
+
return res
|
| 369 |
+
|
| 370 |
+
def allreduce_coalesced(self, tensor_list, opts=AllreduceOptions()):
|
| 371 |
+
coll = ProcessLocalGroup._start_coll(AllReduce(opts.reduceOp), self)
|
| 372 |
+
res = coll.join(self._rank, tensor_list)
|
| 373 |
+
ProcessLocalGroup._end_coll(coll, self)
|
| 374 |
+
return res
|
| 375 |
+
|
| 376 |
+
def barrier(self, opts=BarrierOptions()):
|
| 377 |
+
return self.allreduce(tensor_list=[torch.ones(1)])
|
| 378 |
+
|
| 379 |
+
def allgather(self, output_tensors, input_tensor, opts=AllgatherOptions()):
|
| 380 |
+
coll = ProcessLocalGroup._start_coll(AllGather(), self)
|
| 381 |
+
res = coll.join(self._rank, (output_tensors, input_tensor))
|
| 382 |
+
ProcessLocalGroup._end_coll(coll, self)
|
| 383 |
+
return res
|
| 384 |
+
|
| 385 |
+
def _allgather_base(self, output_tensor, input_tensor, opts=AllgatherOptions()):
|
| 386 |
+
tensor_list = list(torch.chunk(output_tensor, self._world_size))
|
| 387 |
+
return self.allgather([tensor_list], [input_tensor], opts)
|
| 388 |
+
|
| 389 |
+
def broadcast(self, tensor_list, opts=BroadcastOptions()):
|
| 390 |
+
coll = ProcessLocalGroup._start_coll(Broadcast(opts.rootRank), self)
|
| 391 |
+
res = coll.join(self._rank, tensor_list)
|
| 392 |
+
ProcessLocalGroup._end_coll(coll, self)
|
| 393 |
+
return res
|
| 394 |
+
|
| 395 |
+
def scatter(self, output_tensors, input_tensors, opts=ScatterOptions()):
|
| 396 |
+
coll = ProcessLocalGroup._start_coll(Scatter(opts.rootRank), self)
|
| 397 |
+
res = coll.join(self._rank, (output_tensors, input_tensors))
|
| 398 |
+
ProcessLocalGroup._end_coll(coll, self)
|
| 399 |
+
return res
|
| 400 |
+
|
| 401 |
+
def gather(self, output_tensors, input_tensors, opts=ScatterOptions()):
|
| 402 |
+
coll = ProcessLocalGroup._start_coll(Gather(opts.rootRank), self)
|
| 403 |
+
res = coll.join(self._rank, (output_tensors, input_tensors))
|
| 404 |
+
ProcessLocalGroup._end_coll(coll, self)
|
| 405 |
+
return res
|
| 406 |
+
|
| 407 |
+
def reduce_scatter(self, output_tensor, scatter_list, opts=ReduceScatterOptions()):
|
| 408 |
+
coll = ProcessLocalGroup._start_coll(ReduceScatter(opts.reduceOp), self)
|
| 409 |
+
res = coll.join(self._rank, (output_tensor, scatter_list))
|
| 410 |
+
ProcessLocalGroup._end_coll(coll, self)
|
| 411 |
+
return res
|
| 412 |
+
|
| 413 |
+
def _reduce_scatter_base(
|
| 414 |
+
self, output_tensor, input_tensor, opts=ReduceScatterOptions()
|
| 415 |
+
):
|
| 416 |
+
tensor_list = list(torch.chunk(input_tensor, self._world_size))
|
| 417 |
+
return self.reduce_scatter([output_tensor], [tensor_list], opts)
|
| 418 |
+
|
| 419 |
+
def reduce_scatter_tensor_coalesced(
|
| 420 |
+
self, output_tensors, input_tensors, opts=ReduceScatterOptions()
|
| 421 |
+
):
|
| 422 |
+
works = [
|
| 423 |
+
self._reduce_scatter_base(output_tensor, input_tensor, opts)
|
| 424 |
+
for output_tensor, input_tensor in zip(output_tensors, input_tensors)
|
| 425 |
+
]
|
| 426 |
+
for work in works[:-1]:
|
| 427 |
+
work.wait()
|
| 428 |
+
return works[-1]
|
| 429 |
+
|
| 430 |
+
def allgather_into_tensor_coalesced(
|
| 431 |
+
self, output_tensor_list, input_tensor_list, opts=AllgatherOptions()
|
| 432 |
+
):
|
| 433 |
+
res = None
|
| 434 |
+
for o_t, i_t in zip(output_tensor_list, input_tensor_list):
|
| 435 |
+
res = self._allgather_base(o_t, i_t)
|
| 436 |
+
return res
|
| 437 |
+
|
| 438 |
+
def __init__(self, rank, world_size):
|
| 439 |
+
super().__init__(rank, world_size)
|
| 440 |
+
self._rank = rank
|
| 441 |
+
self._world_size = world_size
|
| 442 |
+
world = dist.distributed_c10d._world
|
| 443 |
+
if isinstance(world, ThreadLocalWorld):
|
| 444 |
+
world = world._get_world()
|
| 445 |
+
self._world = weakref.ref(world)
|
| 446 |
+
self._ctx = torch.autograd.set_multithreading_enabled(False)
|
| 447 |
+
|
| 448 |
+
def size(self):
|
| 449 |
+
return self._world_size
|
| 450 |
+
|
| 451 |
+
@property
|
| 452 |
+
def pg_name(self):
|
| 453 |
+
"""
|
| 454 |
+
return the global registered name of the current pg in the world
|
| 455 |
+
"""
|
| 456 |
+
return self._world().pg_names[self]
|
| 457 |
+
|
| 458 |
+
@property
|
| 459 |
+
def group_name(self):
|
| 460 |
+
return self.pg_name
|
| 461 |
+
|
| 462 |
+
def getBackendName(self):
|
| 463 |
+
return "threaded"
|
| 464 |
+
|
| 465 |
+
def __repr__(self):
|
| 466 |
+
return f"ThreadedPG world_size:{self._world_size} rank:{self._rank}"
|
| 467 |
+
|
| 468 |
+
|
| 469 |
+
def _create_threaded_pg(prefix_store, rank, world_size, timeout):
|
| 470 |
+
pg = ProcessLocalGroup(rank, world_size)
|
| 471 |
+
# https://github.com/pytorch/pytorch/pull/103033 changed store based barrier to optional
|
| 472 |
+
# When device mesh involves sub groups while store based barrier is not enabled in c10d,
|
| 473 |
+
# even though threaded pg actual collectives are assumed to be single threaded,
|
| 474 |
+
# different threads may be initializing different groups,
|
| 475 |
+
# leading to race conditions.
|
| 476 |
+
# For example, if we have a mesh of [[0, 1], [2, 3]], the sub groups
|
| 477 |
+
# (dim 0 and 1) would be initialized in different threads independently.
|
| 478 |
+
# In this case we can no longer rely on class or global variables
|
| 479 |
+
# but have to rely on store based barrier to make sure each group
|
| 480 |
+
# is ready separately before we can invoke collectives in any of the groups.
|
| 481 |
+
|
| 482 |
+
# the prefix store is already per group so we pass an empty name here
|
| 483 |
+
_store_based_barrier(rank, prefix_store, "", world_size, timeout)
|
| 484 |
+
return pg
|
| 485 |
+
|
| 486 |
+
|
| 487 |
+
dist.Backend.register_backend("threaded", _create_threaded_pg, devices=["cpu", "cuda"])
|
| 488 |
+
|
| 489 |
+
|
| 490 |
+
@dataclass
|
| 491 |
+
class WorldData:
|
| 492 |
+
default_pg: dist.ProcessGroup
|
| 493 |
+
pg_map: dict[dist.ProcessGroup, tuple[str, Optional[Store]]]
|
| 494 |
+
pg_names: dict[dist.ProcessGroup, str]
|
| 495 |
+
pg_group_ranks: dict[dist.ProcessGroup, dict[int, int]]
|
| 496 |
+
pg_backend_config: dict[dist.ProcessGroup, str]
|
| 497 |
+
group_count: int
|
| 498 |
+
tags_to_pg: dict[str, list[dist.ProcessGroup]]
|
| 499 |
+
pg_to_tag: dict[dist.ProcessGroup, str]
|
| 500 |
+
pg_coalesce_state: dict[dist.ProcessGroup, list[Union[_CollOp, P2POp]]]
|
| 501 |
+
|
| 502 |
+
|
| 503 |
+
class ThreadLocalWorld:
|
| 504 |
+
_world = threading.local()
|
| 505 |
+
|
| 506 |
+
def _get_world(self) -> WorldData:
|
| 507 |
+
if not hasattr(ThreadLocalWorld._world, "world"):
|
| 508 |
+
ThreadLocalWorld._world.world = WorldData(
|
| 509 |
+
None, {}, {}, {}, {}, 0, {}, {}, {}
|
| 510 |
+
)
|
| 511 |
+
return ThreadLocalWorld._world.world
|
| 512 |
+
|
| 513 |
+
@property
|
| 514 |
+
def default_pg(self):
|
| 515 |
+
return self._get_world().default_pg
|
| 516 |
+
|
| 517 |
+
@default_pg.setter
|
| 518 |
+
def default_pg(self, value):
|
| 519 |
+
self._get_world().default_pg = value
|
| 520 |
+
|
| 521 |
+
@property
|
| 522 |
+
def pg_map(self):
|
| 523 |
+
return self._get_world().pg_map
|
| 524 |
+
|
| 525 |
+
@property
|
| 526 |
+
def pg_names(self):
|
| 527 |
+
return self._get_world().pg_names
|
| 528 |
+
|
| 529 |
+
@property
|
| 530 |
+
def pg_group_ranks(self):
|
| 531 |
+
return self._get_world().pg_group_ranks
|
| 532 |
+
|
| 533 |
+
@property
|
| 534 |
+
def pg_backend_config(self):
|
| 535 |
+
return self._get_world().pg_backend_config
|
| 536 |
+
|
| 537 |
+
@property
|
| 538 |
+
def group_count(self) -> int:
|
| 539 |
+
return self._get_world().group_count
|
| 540 |
+
|
| 541 |
+
@group_count.setter
|
| 542 |
+
def group_count(self, value):
|
| 543 |
+
self._get_world().group_count = value
|
| 544 |
+
|
| 545 |
+
@property
|
| 546 |
+
def tags_to_pg(self):
|
| 547 |
+
return self._get_world().tags_to_pg
|
| 548 |
+
|
| 549 |
+
@property
|
| 550 |
+
def pg_to_tag(self):
|
| 551 |
+
return self._get_world().pg_to_tag
|
| 552 |
+
|
| 553 |
+
@property
|
| 554 |
+
def pg_coalesce_state(self) -> dict[dist.ProcessGroup, list[Union[_CollOp, P2POp]]]:
|
| 555 |
+
return self._get_world().pg_coalesce_state
|
| 556 |
+
|
| 557 |
+
|
| 558 |
+
_old_pg_world = None
|
| 559 |
+
_ctx_manager = None
|
| 560 |
+
|
| 561 |
+
|
| 562 |
+
def _install_threaded_pg():
|
| 563 |
+
global _old_pg_world
|
| 564 |
+
global _ctx_manager
|
| 565 |
+
_old_pg_world = dist.distributed_c10d._world
|
| 566 |
+
dist.distributed_c10d._world = ThreadLocalWorld()
|
| 567 |
+
_ctx_manager = torch.autograd.set_multithreading_enabled(False)
|
| 568 |
+
|
| 569 |
+
return dist.distributed_c10d._world
|
| 570 |
+
|
| 571 |
+
|
| 572 |
+
def _uninstall_threaded_pg():
|
| 573 |
+
dist.distributed_c10d._world = _old_pg_world
|
pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/distributed/nn/__init__.py
ADDED
|
File without changes
|
pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/distributed/nn/api/__init__.py
ADDED
|
File without changes
|
pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/distributed/nn/api/remote_module_test.py
ADDED
|
@@ -0,0 +1,752 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
|
| 3 |
+
import enum
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
import torch.distributed.rpc as rpc
|
| 7 |
+
import torch.testing._internal.dist_utils as dist_utils
|
| 8 |
+
from torch import nn, Tensor
|
| 9 |
+
from torch._jit_internal import Future
|
| 10 |
+
from torch.distributed.nn import RemoteModule
|
| 11 |
+
from torch.distributed.nn.api.remote_module import (
|
| 12 |
+
_REMOTE_MODULE_PICKLED_ATTRIBUTES,
|
| 13 |
+
_RemoteModule,
|
| 14 |
+
)
|
| 15 |
+
from torch.testing._internal.common_distributed import skip_if_lt_x_gpu
|
| 16 |
+
from torch.testing._internal.common_utils import TemporaryFileName, TEST_WITH_ROCM
|
| 17 |
+
from torch.testing._internal.distributed.rpc.rpc_agent_test_fixture import (
|
| 18 |
+
RpcAgentTestFixture,
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
_PARAM_VAL = torch.nn.Parameter(torch.ones(1))
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
# RPC handler for querying the device on the destination worker.
|
| 26 |
+
def remote_device(module_rref):
|
| 27 |
+
for param in module_rref.local_value().parameters():
|
| 28 |
+
return param.device
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
# RPC handler for querying __dict__ on the destination worker.
|
| 32 |
+
def remote_module_attributes(remote_module):
|
| 33 |
+
return remote_module.__dict__
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
# RPC handler for running forward on the destination worker.
|
| 37 |
+
def remote_forward(remote_module, args):
|
| 38 |
+
return remote_module.forward(*args)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
# RPC handler for running forward_async on the destination worker.
|
| 42 |
+
def remote_forward_async(remote_module, args):
|
| 43 |
+
# Since future cannot be pickled and sent over the RPC layer,
|
| 44 |
+
# have to wait and behave just like ``forward_sync``.
|
| 45 |
+
return remote_module.forward_async(*args).wait()
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
# RPC handler for getting training mode on the destination worker.
|
| 49 |
+
def get_remote_training_arg(module_rref):
|
| 50 |
+
return module_rref.local_value().training
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
class ModuleCreationMode(enum.Enum):
|
| 54 |
+
MODULE_CTOR_WITH_INTERFACE = "module_ctor_with_interface"
|
| 55 |
+
MODULE_CTOR = "module_ctor"
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
@torch.jit.interface
|
| 59 |
+
class MyModuleInterface:
|
| 60 |
+
def forward(
|
| 61 |
+
self, tensor: Tensor, number: int, word: str = "default"
|
| 62 |
+
) -> tuple[str, int, Tensor]:
|
| 63 |
+
# pyre-ignore[7]: Pyre and torch.jit.interface don't mix well
|
| 64 |
+
pass
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
@torch.jit.interface
|
| 68 |
+
class RemoteMyModuleInterface:
|
| 69 |
+
def forward(
|
| 70 |
+
self, tensor: Tensor, number: int, word: str = "default"
|
| 71 |
+
) -> tuple[str, int, Tensor]:
|
| 72 |
+
# pyre-ignore[7]: Pyre and torch.jit.interface don't mix well
|
| 73 |
+
pass
|
| 74 |
+
|
| 75 |
+
def forward_async(
|
| 76 |
+
self, tensor: Tensor, number: int, word: str = "default"
|
| 77 |
+
) -> Future[tuple[str, int, Tensor]]:
|
| 78 |
+
pass
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
class MyModule(nn.Module):
|
| 82 |
+
def __init__(self, first_arg, first_kwarg=-1):
|
| 83 |
+
super().__init__()
|
| 84 |
+
self.param1 = _PARAM_VAL
|
| 85 |
+
|
| 86 |
+
def forward(
|
| 87 |
+
self, tensor: Tensor, number: int, word: str = "default"
|
| 88 |
+
) -> tuple[str, int, Tensor]:
|
| 89 |
+
return word, number, tensor
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
class BadModule:
|
| 93 |
+
def __init__(self, first_arg, first_kwarg=-1):
|
| 94 |
+
pass
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def create_scripted_module(first_arg, first_kwarg=-1):
|
| 98 |
+
module = MyModule(first_arg, first_kwarg=first_kwarg)
|
| 99 |
+
scripted_module = torch.jit.script(module)
|
| 100 |
+
return scripted_module
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
# Common utils for both CPU and CUDA test suites
|
| 104 |
+
class CommonRemoteModuleTest(RpcAgentTestFixture):
|
| 105 |
+
@property
|
| 106 |
+
def world_size(self): # Override setting in RpcAgentTestFixture
|
| 107 |
+
return 2
|
| 108 |
+
|
| 109 |
+
@staticmethod
|
| 110 |
+
def _create_remote_module_iter(remote_device, modes=None):
|
| 111 |
+
if modes is None:
|
| 112 |
+
modes = ModuleCreationMode.__members__.values()
|
| 113 |
+
|
| 114 |
+
args = (1,)
|
| 115 |
+
kwargs = dict(first_kwarg=2)
|
| 116 |
+
|
| 117 |
+
if ModuleCreationMode.MODULE_CTOR in modes:
|
| 118 |
+
remote_module = RemoteModule(remote_device, MyModule, args, kwargs)
|
| 119 |
+
yield remote_module
|
| 120 |
+
|
| 121 |
+
if ModuleCreationMode.MODULE_CTOR_WITH_INTERFACE in modes:
|
| 122 |
+
remote_module = _RemoteModule(
|
| 123 |
+
remote_device,
|
| 124 |
+
create_scripted_module,
|
| 125 |
+
args,
|
| 126 |
+
kwargs,
|
| 127 |
+
_module_interface_cls=MyModuleInterface,
|
| 128 |
+
)
|
| 129 |
+
scripted_remote_module = torch.jit.script(remote_module)
|
| 130 |
+
yield scripted_remote_module
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
class RemoteModuleTest(CommonRemoteModuleTest):
|
| 134 |
+
@dist_utils.dist_init
|
| 135 |
+
def test_bad_module(self):
|
| 136 |
+
if self.rank != 0:
|
| 137 |
+
return
|
| 138 |
+
dst_worker_name = dist_utils.worker_name((self.rank + 1) % self.world_size)
|
| 139 |
+
remote_device = f"{dst_worker_name}/cpu"
|
| 140 |
+
args = (1,)
|
| 141 |
+
kwargs = dict(first_kwarg=2)
|
| 142 |
+
|
| 143 |
+
with self.assertRaisesRegex(
|
| 144 |
+
ValueError,
|
| 145 |
+
r"Expect `module_cls\(\*args, \*\*kwargs\)` returns an instance of <class nn.Module>,",
|
| 146 |
+
):
|
| 147 |
+
RemoteModule(remote_device, BadModule, args, kwargs).forward()
|
| 148 |
+
|
| 149 |
+
with self.assertRaisesRegex(
|
| 150 |
+
ValueError,
|
| 151 |
+
r"Expect `module_cls\(\*args, \*\*kwargs\)` returns an instance of <class nn.Module>,",
|
| 152 |
+
):
|
| 153 |
+
RemoteModule(remote_device, BadModule, args, kwargs).forward()
|
| 154 |
+
|
| 155 |
+
@dist_utils.dist_init
|
| 156 |
+
def test_forward_async(self):
|
| 157 |
+
if self.rank != 0:
|
| 158 |
+
return
|
| 159 |
+
dst_worker_name = dist_utils.worker_name((self.rank + 1) % self.world_size)
|
| 160 |
+
args = (torch.ones(1), 2, "3")
|
| 161 |
+
for remote_module in self._create_remote_module_iter(dst_worker_name):
|
| 162 |
+
ret_fut = remote_module.forward_async(*args)
|
| 163 |
+
ret = ret_fut.wait()
|
| 164 |
+
self.assertEqual(ret, tuple(reversed(args)))
|
| 165 |
+
|
| 166 |
+
@dist_utils.dist_init
|
| 167 |
+
def test_forward_async_script(self):
|
| 168 |
+
if self.rank != 0:
|
| 169 |
+
return
|
| 170 |
+
dst_worker_name = dist_utils.worker_name((self.rank + 1) % self.world_size)
|
| 171 |
+
|
| 172 |
+
scripted_remote_module = next(
|
| 173 |
+
self._create_remote_module_iter(
|
| 174 |
+
dst_worker_name, modes=[ModuleCreationMode.MODULE_CTOR_WITH_INTERFACE]
|
| 175 |
+
)
|
| 176 |
+
)
|
| 177 |
+
|
| 178 |
+
@torch.jit.script
|
| 179 |
+
def run_forward_async(scripted_remote_module: RemoteMyModuleInterface):
|
| 180 |
+
ret_fut = scripted_remote_module.forward_async(torch.ones(1), 2, "3")
|
| 181 |
+
ret = ret_fut.wait()
|
| 182 |
+
return ret
|
| 183 |
+
|
| 184 |
+
ret = run_forward_async(scripted_remote_module)
|
| 185 |
+
|
| 186 |
+
self.assertEqual(ret, ("3", 2, torch.ones(1)))
|
| 187 |
+
|
| 188 |
+
@dist_utils.dist_init
|
| 189 |
+
def test_forward_sync(self):
|
| 190 |
+
if self.rank != 0:
|
| 191 |
+
return
|
| 192 |
+
dst_worker_name = dist_utils.worker_name((self.rank + 1) % self.world_size)
|
| 193 |
+
args = (torch.ones(1), 2, "3")
|
| 194 |
+
for remote_module in self._create_remote_module_iter(dst_worker_name):
|
| 195 |
+
ret = remote_module.forward(*args)
|
| 196 |
+
self.assertEqual(ret, tuple(reversed(args)))
|
| 197 |
+
|
| 198 |
+
@dist_utils.dist_init
|
| 199 |
+
def test_forward_sync_script(self):
|
| 200 |
+
if self.rank != 0:
|
| 201 |
+
return
|
| 202 |
+
dst_worker_name = dist_utils.worker_name((self.rank + 1) % self.world_size)
|
| 203 |
+
|
| 204 |
+
scripted_remote_module = next(
|
| 205 |
+
self._create_remote_module_iter(
|
| 206 |
+
dst_worker_name, modes=[ModuleCreationMode.MODULE_CTOR_WITH_INTERFACE]
|
| 207 |
+
)
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
@torch.jit.script
|
| 211 |
+
def run_forward(scripted_remote_module: MyModuleInterface):
|
| 212 |
+
ret = scripted_remote_module.forward(torch.ones(1), 2, "3")
|
| 213 |
+
return ret
|
| 214 |
+
|
| 215 |
+
ret = run_forward(scripted_remote_module)
|
| 216 |
+
|
| 217 |
+
self.assertEqual(ret, ("3", 2, torch.ones(1)))
|
| 218 |
+
|
| 219 |
+
@dist_utils.dist_init
|
| 220 |
+
def test_forward_with_kwargs(self):
|
| 221 |
+
if self.rank != 0:
|
| 222 |
+
return
|
| 223 |
+
dst_worker_name = dist_utils.worker_name((self.rank + 1) % self.world_size)
|
| 224 |
+
args = (torch.ones(1), 2)
|
| 225 |
+
kwargs = dict(word="3")
|
| 226 |
+
# Only test Python nn.Module, because script module methods don't support taking kwargs.
|
| 227 |
+
for remote_module in self._create_remote_module_iter(
|
| 228 |
+
dst_worker_name, modes=[ModuleCreationMode.MODULE_CTOR]
|
| 229 |
+
):
|
| 230 |
+
ret_fut = remote_module.forward_async(*args, **kwargs)
|
| 231 |
+
ret = ret_fut.wait()
|
| 232 |
+
self.assertEqual(ret, tuple(reversed(args + ("3",))))
|
| 233 |
+
|
| 234 |
+
ret = remote_module.forward(*args, **kwargs)
|
| 235 |
+
self.assertEqual(ret, tuple(reversed(args + ("3",))))
|
| 236 |
+
|
| 237 |
+
@dist_utils.dist_init
|
| 238 |
+
def test_remote_parameters(self):
|
| 239 |
+
if self.rank != 0:
|
| 240 |
+
return
|
| 241 |
+
dst_worker_name = dist_utils.worker_name((self.rank + 1) % self.world_size)
|
| 242 |
+
|
| 243 |
+
# Only test Python nn.Module, because script module methods don't support ``remote_parameters``.
|
| 244 |
+
for remote_module in self._create_remote_module_iter(
|
| 245 |
+
dst_worker_name, modes=[ModuleCreationMode.MODULE_CTOR]
|
| 246 |
+
):
|
| 247 |
+
param_rrefs = remote_module.remote_parameters()
|
| 248 |
+
self.assertEqual(len(param_rrefs), 1)
|
| 249 |
+
self.assertTrue(torch.equal(param_rrefs[0].to_here(), _PARAM_VAL))
|
| 250 |
+
|
| 251 |
+
@dist_utils.dist_init
|
| 252 |
+
def test_get_module_rref(self):
|
| 253 |
+
if self.rank != 0:
|
| 254 |
+
return
|
| 255 |
+
dst_worker_name = dist_utils.worker_name((self.rank + 1) % self.world_size)
|
| 256 |
+
|
| 257 |
+
# Only test Python nn.Module, because script module methods don't support ``get_module_rref``.
|
| 258 |
+
for remote_module in self._create_remote_module_iter(
|
| 259 |
+
dst_worker_name, modes=[ModuleCreationMode.MODULE_CTOR]
|
| 260 |
+
):
|
| 261 |
+
rref = remote_module.get_module_rref()
|
| 262 |
+
self.assertEqual(rref, remote_module.module_rref)
|
| 263 |
+
for param in rref.to_here().parameters():
|
| 264 |
+
self.assertTrue(torch.equal(param, _PARAM_VAL))
|
| 265 |
+
|
| 266 |
+
@dist_utils.dist_init
|
| 267 |
+
def test_train_eval(self):
|
| 268 |
+
if self.rank != 0:
|
| 269 |
+
return
|
| 270 |
+
dst_worker_name = dist_utils.worker_name((self.rank + 1) % self.world_size)
|
| 271 |
+
|
| 272 |
+
for remote_module in self._create_remote_module_iter(
|
| 273 |
+
dst_worker_name, modes=[ModuleCreationMode.MODULE_CTOR]
|
| 274 |
+
):
|
| 275 |
+
remote_module.train()
|
| 276 |
+
ret1 = rpc.rpc_sync(
|
| 277 |
+
dst_worker_name,
|
| 278 |
+
get_remote_training_arg,
|
| 279 |
+
args=(remote_module.get_module_rref(),),
|
| 280 |
+
)
|
| 281 |
+
self.assertEqual(ret1, True)
|
| 282 |
+
|
| 283 |
+
remote_module.eval()
|
| 284 |
+
ret2 = rpc.rpc_sync(
|
| 285 |
+
dst_worker_name,
|
| 286 |
+
get_remote_training_arg,
|
| 287 |
+
args=(remote_module.get_module_rref(),),
|
| 288 |
+
)
|
| 289 |
+
self.assertEqual(ret2, False)
|
| 290 |
+
|
| 291 |
+
@dist_utils.dist_init
|
| 292 |
+
def test_unsupported_methods(self):
|
| 293 |
+
if self.rank != 0:
|
| 294 |
+
return
|
| 295 |
+
dst_worker_name = dist_utils.worker_name((self.rank + 1) % self.world_size)
|
| 296 |
+
|
| 297 |
+
for remote_module in self._create_remote_module_iter(
|
| 298 |
+
dst_worker_name, modes=[ModuleCreationMode.MODULE_CTOR]
|
| 299 |
+
):
|
| 300 |
+
with self.assertRaisesRegex(
|
| 301 |
+
ValueError, r"Method ``register_buffer`` not supported for RemoteModule"
|
| 302 |
+
):
|
| 303 |
+
remote_module.register_buffer("buffer", torch.ones(5))
|
| 304 |
+
with self.assertRaisesRegex(
|
| 305 |
+
ValueError,
|
| 306 |
+
r"Method ``register_parameter`` not supported for RemoteModule",
|
| 307 |
+
):
|
| 308 |
+
remote_module.register_parameter(
|
| 309 |
+
"param", torch.nn.Parameter(torch.ones(1))
|
| 310 |
+
)
|
| 311 |
+
with self.assertRaisesRegex(
|
| 312 |
+
ValueError, r"Method ``add_module`` not supported for RemoteModule"
|
| 313 |
+
):
|
| 314 |
+
remote_module.add_module("empty", None)
|
| 315 |
+
|
| 316 |
+
with self.assertRaisesRegex(
|
| 317 |
+
ValueError, r"Method ``apply`` not supported for RemoteModule"
|
| 318 |
+
):
|
| 319 |
+
fn = torch.rand((3, 3), requires_grad=False)
|
| 320 |
+
remote_module.apply(fn)
|
| 321 |
+
|
| 322 |
+
with self.assertRaisesRegex(
|
| 323 |
+
ValueError, r"Method ``cuda`` not supported for RemoteModule"
|
| 324 |
+
):
|
| 325 |
+
remote_module.cuda()
|
| 326 |
+
with self.assertRaisesRegex(
|
| 327 |
+
ValueError, r"Method ``cpu`` not supported for RemoteModule"
|
| 328 |
+
):
|
| 329 |
+
remote_module.cpu()
|
| 330 |
+
with self.assertRaisesRegex(
|
| 331 |
+
ValueError, r"Method ``type`` not supported for RemoteModule"
|
| 332 |
+
):
|
| 333 |
+
remote_module.type(torch.FloatTensor)
|
| 334 |
+
with self.assertRaisesRegex(
|
| 335 |
+
ValueError, r"Method ``float`` not supported for RemoteModule"
|
| 336 |
+
):
|
| 337 |
+
remote_module.float()
|
| 338 |
+
with self.assertRaisesRegex(
|
| 339 |
+
ValueError, r"Method ``double`` not supported for RemoteModule"
|
| 340 |
+
):
|
| 341 |
+
remote_module.double()
|
| 342 |
+
with self.assertRaisesRegex(
|
| 343 |
+
ValueError, r"Method ``bfloat16`` not supported for RemoteModule"
|
| 344 |
+
):
|
| 345 |
+
remote_module.bfloat16()
|
| 346 |
+
with self.assertRaisesRegex(
|
| 347 |
+
ValueError, r"Method ``to`` not supported for RemoteModule"
|
| 348 |
+
):
|
| 349 |
+
remote_module.to("cpu", dtype=torch.int32)
|
| 350 |
+
|
| 351 |
+
def hook(module, grad_input, grad_output):
|
| 352 |
+
pass
|
| 353 |
+
|
| 354 |
+
with self.assertRaisesRegex(
|
| 355 |
+
ValueError,
|
| 356 |
+
r"Method ``register_backward_hook`` not supported for RemoteModule",
|
| 357 |
+
):
|
| 358 |
+
remote_module.register_backward_hook(hook)
|
| 359 |
+
with self.assertRaisesRegex(
|
| 360 |
+
ValueError,
|
| 361 |
+
r"Method ``register_forward_pre_hook`` not supported for RemoteModule",
|
| 362 |
+
):
|
| 363 |
+
remote_module.register_forward_pre_hook(hook)
|
| 364 |
+
with self.assertRaisesRegex(
|
| 365 |
+
ValueError,
|
| 366 |
+
r"Method ``register_forward_hook`` not supported for RemoteModule",
|
| 367 |
+
):
|
| 368 |
+
remote_module.register_forward_hook(hook)
|
| 369 |
+
|
| 370 |
+
with self.assertRaisesRegex(
|
| 371 |
+
ValueError, r"Method ``state_dict`` not supported for RemoteModule"
|
| 372 |
+
):
|
| 373 |
+
remote_module.state_dict()
|
| 374 |
+
with self.assertRaisesRegex(
|
| 375 |
+
ValueError, r"Method ``load_state_dict`` not supported for RemoteModule"
|
| 376 |
+
):
|
| 377 |
+
remote_module.load_state_dict({})
|
| 378 |
+
|
| 379 |
+
with self.assertRaisesRegex(
|
| 380 |
+
ValueError,
|
| 381 |
+
r"Method ``parameters`` not supported for RemoteModule. Please use ``remote_parameters`` instead.",
|
| 382 |
+
):
|
| 383 |
+
remote_module.parameters()
|
| 384 |
+
with self.assertRaisesRegex(
|
| 385 |
+
ValueError,
|
| 386 |
+
r"Method ``named_parameters`` not supported for RemoteModule",
|
| 387 |
+
):
|
| 388 |
+
remote_module.named_parameters()
|
| 389 |
+
with self.assertRaisesRegex(
|
| 390 |
+
ValueError, r"Method ``buffers`` not supported for RemoteModule"
|
| 391 |
+
):
|
| 392 |
+
remote_module.buffers()
|
| 393 |
+
with self.assertRaisesRegex(
|
| 394 |
+
ValueError, r"Method ``named_buffers`` not supported for RemoteModule"
|
| 395 |
+
):
|
| 396 |
+
remote_module.named_buffers()
|
| 397 |
+
with self.assertRaisesRegex(
|
| 398 |
+
ValueError, r"Method ``children`` not supported for RemoteModule"
|
| 399 |
+
):
|
| 400 |
+
remote_module.children()
|
| 401 |
+
with self.assertRaisesRegex(
|
| 402 |
+
ValueError, r"Method ``named_children`` not supported for RemoteModule"
|
| 403 |
+
):
|
| 404 |
+
remote_module.named_children()
|
| 405 |
+
with self.assertRaisesRegex(
|
| 406 |
+
ValueError, r"Method ``modules`` not supported for RemoteModule"
|
| 407 |
+
):
|
| 408 |
+
remote_module.modules()
|
| 409 |
+
with self.assertRaisesRegex(
|
| 410 |
+
ValueError, r"Method ``named_modules`` not supported for RemoteModule"
|
| 411 |
+
):
|
| 412 |
+
remote_module.named_modules()
|
| 413 |
+
|
| 414 |
+
with self.assertRaisesRegex(
|
| 415 |
+
ValueError, r"Method ``requires_grad_`` not supported for RemoteModule"
|
| 416 |
+
):
|
| 417 |
+
remote_module.requires_grad_()
|
| 418 |
+
with self.assertRaisesRegex(
|
| 419 |
+
ValueError, r"Method ``zero_grad`` not supported for RemoteModule"
|
| 420 |
+
):
|
| 421 |
+
remote_module.zero_grad()
|
| 422 |
+
with self.assertRaisesRegex(
|
| 423 |
+
ValueError, r"Method ``share_memory`` not supported for RemoteModule"
|
| 424 |
+
):
|
| 425 |
+
remote_module.share_memory()
|
| 426 |
+
with self.assertRaisesRegex(
|
| 427 |
+
ValueError, r"Method ``extra_repr`` not supported for RemoteModule"
|
| 428 |
+
):
|
| 429 |
+
remote_module.extra_repr()
|
| 430 |
+
|
| 431 |
+
@dist_utils.dist_init
|
| 432 |
+
def test_send_remote_module_with_a_new_attribute_not_pickled_over_the_wire(self):
|
| 433 |
+
if self.rank != 0:
|
| 434 |
+
return
|
| 435 |
+
dst_worker_name = dist_utils.worker_name((self.rank + 1) % self.world_size)
|
| 436 |
+
|
| 437 |
+
# If a new attribute is added to this RemoteModule after the initialization,
|
| 438 |
+
# and it will be sent over the wire by RPC,
|
| 439 |
+
# this new field will not be pickled, because it's not specified in _REMOTE_MODULE_PICKLED_ATTRIBUTES.
|
| 440 |
+
# Note that adding a new attribute out of constructor should rarely happen.
|
| 441 |
+
# If a new attribute is added to RemoteModule constructor,
|
| 442 |
+
# there is a sanity check to enforce developers to add this attribute to either
|
| 443 |
+
# _REMOTE_MODULE_PICKLED_ATTRIBUTES or _REMOTE_MODULE_ATTRIBUTES_IGNORE_FOR_PICKLING.
|
| 444 |
+
for remote_module in self._create_remote_module_iter(
|
| 445 |
+
dst_worker_name, modes=[ModuleCreationMode.MODULE_CTOR]
|
| 446 |
+
):
|
| 447 |
+
new_attr_name = "new_attr"
|
| 448 |
+
setattr(remote_module, new_attr_name, 1)
|
| 449 |
+
|
| 450 |
+
attrs = rpc.rpc_sync(
|
| 451 |
+
dst_worker_name, remote_module_attributes, (remote_module,)
|
| 452 |
+
)
|
| 453 |
+
self.assertNotIn(new_attr_name, attrs)
|
| 454 |
+
|
| 455 |
+
@dist_utils.dist_init
|
| 456 |
+
def test_remote_module_py_pickle_not_supported(self):
|
| 457 |
+
if self.rank != 0:
|
| 458 |
+
return
|
| 459 |
+
dst_worker_name = dist_utils.worker_name((self.rank + 1) % self.world_size)
|
| 460 |
+
|
| 461 |
+
for remote_module in self._create_remote_module_iter(
|
| 462 |
+
dst_worker_name, modes=[ModuleCreationMode.MODULE_CTOR]
|
| 463 |
+
):
|
| 464 |
+
with TemporaryFileName() as fname:
|
| 465 |
+
with self.assertRaisesRegex(
|
| 466 |
+
RuntimeError,
|
| 467 |
+
"Cannot pickle RemoteModule in python pickler. RemoteModule can only be pickled when using RPC",
|
| 468 |
+
):
|
| 469 |
+
torch.save(remote_module, fname)
|
| 470 |
+
|
| 471 |
+
@dist_utils.dist_init
|
| 472 |
+
def test_remote_module_py_pickle_not_supported_script(self):
|
| 473 |
+
if self.rank != 0:
|
| 474 |
+
return
|
| 475 |
+
dst_worker_name = dist_utils.worker_name((self.rank + 1) % self.world_size)
|
| 476 |
+
|
| 477 |
+
for remote_module in self._create_remote_module_iter(
|
| 478 |
+
dst_worker_name, modes=[ModuleCreationMode.MODULE_CTOR_WITH_INTERFACE]
|
| 479 |
+
):
|
| 480 |
+
with TemporaryFileName() as fname:
|
| 481 |
+
with self.assertRaisesRegex(
|
| 482 |
+
torch.jit.Error, "can only be pickled when using RPC"
|
| 483 |
+
):
|
| 484 |
+
torch.save(remote_module, fname)
|
| 485 |
+
|
| 486 |
+
|
| 487 |
+
class ThreeWorkersRemoteModuleTest(CommonRemoteModuleTest):
|
| 488 |
+
@property
|
| 489 |
+
def world_size(self): # Override setting in CommonRemoteModuleTest
|
| 490 |
+
return 3
|
| 491 |
+
|
| 492 |
+
@dist_utils.dist_init
|
| 493 |
+
def test_send_remote_module_over_the_wire(self):
|
| 494 |
+
if self.rank != 0:
|
| 495 |
+
return
|
| 496 |
+
dst_worker1_name = dist_utils.worker_name((self.rank + 1) % self.world_size)
|
| 497 |
+
dst_worker2_name = dist_utils.worker_name((self.rank + 2) % self.world_size)
|
| 498 |
+
|
| 499 |
+
# Unpickled attributes include both the inherent attributes of RemoteModule
|
| 500 |
+
# (not inherited from the superclass) and two installed methods.
|
| 501 |
+
expected_unpickled_attrs = list(_REMOTE_MODULE_PICKLED_ATTRIBUTES)
|
| 502 |
+
expected_unpickled_attrs.append("forward_async")
|
| 503 |
+
expected_unpickled_attrs.append("forward")
|
| 504 |
+
|
| 505 |
+
# Create a remote module on worker1 and then pass it to worker2 over the RPC layer.
|
| 506 |
+
for remote_module in self._create_remote_module_iter(
|
| 507 |
+
dst_worker1_name, modes=[ModuleCreationMode.MODULE_CTOR]
|
| 508 |
+
):
|
| 509 |
+
# Test querying some simple attributes from worker2.
|
| 510 |
+
attrs = rpc.rpc_sync(
|
| 511 |
+
dst_worker2_name, remote_module_attributes, (remote_module,)
|
| 512 |
+
)
|
| 513 |
+
self.assertListEqual(list(attrs.keys()), expected_unpickled_attrs)
|
| 514 |
+
self.assertEqual(attrs["on"], "worker1")
|
| 515 |
+
self.assertEqual(attrs["device"], "cpu")
|
| 516 |
+
self.assertFalse(attrs["is_device_map_set"])
|
| 517 |
+
self.assertFalse(attrs["is_scriptable"])
|
| 518 |
+
|
| 519 |
+
# Test the installed methods on worker1's can be initiated by worker2 over RPC layer.
|
| 520 |
+
# NOTE: In practice a remote module should be directly stored on the worker that runs ``forward``` or ``forward_async``,
|
| 521 |
+
# not have another worker to initiate forward over the RPC layer.
|
| 522 |
+
args = (torch.ones(1), 2, "3")
|
| 523 |
+
ret1 = rpc.rpc_sync(dst_worker2_name, remote_forward, (remote_module, args))
|
| 524 |
+
self.assertEqual(ret1, tuple(reversed(args)))
|
| 525 |
+
ret2 = rpc.rpc_sync(
|
| 526 |
+
dst_worker2_name, remote_forward_async, (remote_module, args)
|
| 527 |
+
)
|
| 528 |
+
self.assertEqual(ret2, tuple(reversed(args)))
|
| 529 |
+
|
| 530 |
+
@dist_utils.dist_init
|
| 531 |
+
def test_send_remote_module_over_the_wire_script_not_supported(self):
|
| 532 |
+
if self.rank != 0:
|
| 533 |
+
return
|
| 534 |
+
dst_worker1_name = dist_utils.worker_name((self.rank + 1) % self.world_size)
|
| 535 |
+
dst_worker2_name = dist_utils.worker_name((self.rank + 2) % self.world_size)
|
| 536 |
+
|
| 537 |
+
# Unpickled attributes include both the inherent attributes of RemoteModule
|
| 538 |
+
# (not inherited from the superclass) and two installed methods.
|
| 539 |
+
expected_unpickled_attrs = list(_REMOTE_MODULE_PICKLED_ATTRIBUTES)
|
| 540 |
+
expected_unpickled_attrs.append("forward_async")
|
| 541 |
+
expected_unpickled_attrs.append("forward")
|
| 542 |
+
|
| 543 |
+
with self.assertRaisesRegex(
|
| 544 |
+
RuntimeError, "Passing a script RemoteModule over RPC is not supported."
|
| 545 |
+
):
|
| 546 |
+
# Create a remote module on worker1 and then pass it to worker2 over the RPC layer.
|
| 547 |
+
for remote_module in self._create_remote_module_iter(
|
| 548 |
+
dst_worker1_name, modes=[ModuleCreationMode.MODULE_CTOR_WITH_INTERFACE]
|
| 549 |
+
):
|
| 550 |
+
# Test querying some simple attributes from worker2.
|
| 551 |
+
rpc.rpc_sync(
|
| 552 |
+
dst_worker2_name, remote_module_attributes, (remote_module,)
|
| 553 |
+
)
|
| 554 |
+
|
| 555 |
+
@dist_utils.dist_init
|
| 556 |
+
def test_create_remote_module_from_module_rref(self):
|
| 557 |
+
if self.rank != 0:
|
| 558 |
+
return
|
| 559 |
+
dst_worker1_name = dist_utils.worker_name((self.rank + 1) % self.world_size)
|
| 560 |
+
dst_worker2_name = dist_utils.worker_name((self.rank + 2) % self.world_size)
|
| 561 |
+
|
| 562 |
+
# Create a remote module on worker1 and then pass its `module_rref` to worker2 over the RPC layer.
|
| 563 |
+
for remote_module in self._create_remote_module_iter(
|
| 564 |
+
dst_worker1_name, modes=[ModuleCreationMode.MODULE_CTOR]
|
| 565 |
+
):
|
| 566 |
+
remote_module2 = rpc.rpc_sync(
|
| 567 |
+
dst_worker2_name,
|
| 568 |
+
RemoteModule.init_from_module_rref,
|
| 569 |
+
(dst_worker2_name, remote_module.get_module_rref()),
|
| 570 |
+
)
|
| 571 |
+
|
| 572 |
+
args = (torch.ones(1), 2, "3")
|
| 573 |
+
ret1 = rpc.rpc_sync(dst_worker1_name, remote_forward, (remote_module, args))
|
| 574 |
+
ret2 = rpc.rpc_sync(
|
| 575 |
+
dst_worker2_name, remote_forward, (remote_module2, args)
|
| 576 |
+
)
|
| 577 |
+
self.assertEqual(ret1, ret2)
|
| 578 |
+
|
| 579 |
+
|
| 580 |
+
class CudaRemoteModuleTest(CommonRemoteModuleTest):
|
| 581 |
+
@skip_if_lt_x_gpu(1)
|
| 582 |
+
@dist_utils.dist_init
|
| 583 |
+
def test_valid_device(self):
|
| 584 |
+
if self.rank != 0:
|
| 585 |
+
return
|
| 586 |
+
dst_rank = (self.rank + 1) % self.world_size
|
| 587 |
+
dst_worker_name = dist_utils.worker_name(dst_rank)
|
| 588 |
+
|
| 589 |
+
for remote_module in self._create_remote_module_iter(
|
| 590 |
+
f"{dst_worker_name}/cuda:0", modes=[ModuleCreationMode.MODULE_CTOR]
|
| 591 |
+
):
|
| 592 |
+
device = rpc.rpc_sync(
|
| 593 |
+
dst_worker_name, remote_device, (remote_module.module_rref,)
|
| 594 |
+
)
|
| 595 |
+
self.assertEqual(device.type, "cuda")
|
| 596 |
+
self.assertEqual(device.index, 0)
|
| 597 |
+
|
| 598 |
+
# Test rank works as well.
|
| 599 |
+
for remote_module in self._create_remote_module_iter(
|
| 600 |
+
f"rank:{dst_rank}/cuda:0", modes=[ModuleCreationMode.MODULE_CTOR]
|
| 601 |
+
):
|
| 602 |
+
device = rpc.rpc_sync(
|
| 603 |
+
dst_worker_name, remote_device, (remote_module.module_rref,)
|
| 604 |
+
)
|
| 605 |
+
self.assertEqual(device.type, "cuda")
|
| 606 |
+
self.assertEqual(device.index, 0)
|
| 607 |
+
|
| 608 |
+
@skip_if_lt_x_gpu(1)
|
| 609 |
+
@dist_utils.dist_init
|
| 610 |
+
def test_invalid_devices(self):
|
| 611 |
+
if self.rank != 0:
|
| 612 |
+
return
|
| 613 |
+
dst_worker_name = dist_utils.worker_name((self.rank + 1) % self.world_size)
|
| 614 |
+
|
| 615 |
+
with self.assertRaisesRegex(
|
| 616 |
+
RuntimeError,
|
| 617 |
+
r"Expected one of .+ device type at start of device string",
|
| 618 |
+
):
|
| 619 |
+
[
|
| 620 |
+
m.forward()
|
| 621 |
+
for m in self._create_remote_module_iter(
|
| 622 |
+
f"{dst_worker_name}/foo",
|
| 623 |
+
modes=[ModuleCreationMode.MODULE_CTOR],
|
| 624 |
+
)
|
| 625 |
+
]
|
| 626 |
+
|
| 627 |
+
if TEST_WITH_ROCM:
|
| 628 |
+
errorString = (
|
| 629 |
+
r"HIP error: invalid device ordinal\n"
|
| 630 |
+
r"HIP kernel errors might be asynchronously reported at some other API call, "
|
| 631 |
+
r"so the stacktrace below might be incorrect.\n"
|
| 632 |
+
r"For debugging consider passing AMD_SERIALIZE_KERNEL=3"
|
| 633 |
+
)
|
| 634 |
+
else:
|
| 635 |
+
errorString = r"CUDA error: invalid device ordinal"
|
| 636 |
+
with self.assertRaisesRegex(RuntimeError, errorString):
|
| 637 |
+
[
|
| 638 |
+
m.forward()
|
| 639 |
+
for m in self._create_remote_module_iter(
|
| 640 |
+
f"{dst_worker_name}/cuda:100",
|
| 641 |
+
modes=[ModuleCreationMode.MODULE_CTOR],
|
| 642 |
+
)
|
| 643 |
+
]
|
| 644 |
+
|
| 645 |
+
with self.assertRaisesRegex(RuntimeError, r"Invalid device string: 'cpu2'"):
|
| 646 |
+
[
|
| 647 |
+
m.forward()
|
| 648 |
+
for m in self._create_remote_module_iter(
|
| 649 |
+
f"{dst_worker_name}/cpu2",
|
| 650 |
+
modes=[ModuleCreationMode.MODULE_CTOR],
|
| 651 |
+
)
|
| 652 |
+
]
|
| 653 |
+
|
| 654 |
+
with self.assertRaisesRegex(RuntimeError, r"Device string must not be empty"):
|
| 655 |
+
[
|
| 656 |
+
m.forward()
|
| 657 |
+
for m in self._create_remote_module_iter(
|
| 658 |
+
f"{dst_worker_name}/",
|
| 659 |
+
modes=[ModuleCreationMode.MODULE_CTOR],
|
| 660 |
+
)
|
| 661 |
+
]
|
| 662 |
+
|
| 663 |
+
with self.assertRaisesRegex(
|
| 664 |
+
ValueError,
|
| 665 |
+
r"Could not parse remote_device: worker1/cuda:0/cuda:1. The valid format is '<workername>/<device>'",
|
| 666 |
+
):
|
| 667 |
+
[
|
| 668 |
+
m.forward()
|
| 669 |
+
for m in self._create_remote_module_iter(
|
| 670 |
+
f"{dst_worker_name}/cuda:0/cuda:1",
|
| 671 |
+
modes=[ModuleCreationMode.MODULE_CTOR],
|
| 672 |
+
)
|
| 673 |
+
]
|
| 674 |
+
|
| 675 |
+
with self.assertRaisesRegex(
|
| 676 |
+
ValueError,
|
| 677 |
+
r"Could not parse remote_device: /. The valid format is '<workername>/<device>'",
|
| 678 |
+
):
|
| 679 |
+
[
|
| 680 |
+
m.forward()
|
| 681 |
+
for m in self._create_remote_module_iter(
|
| 682 |
+
"/",
|
| 683 |
+
modes=[ModuleCreationMode.MODULE_CTOR],
|
| 684 |
+
)
|
| 685 |
+
]
|
| 686 |
+
|
| 687 |
+
with self.assertRaisesRegex(
|
| 688 |
+
ValueError,
|
| 689 |
+
r"Could not parse remote_device: /cuda:0. The valid format is '<workername>/<device>'",
|
| 690 |
+
):
|
| 691 |
+
[
|
| 692 |
+
m.forward()
|
| 693 |
+
for m in self._create_remote_module_iter(
|
| 694 |
+
"/cuda:0",
|
| 695 |
+
modes=[ModuleCreationMode.MODULE_CTOR],
|
| 696 |
+
)
|
| 697 |
+
]
|
| 698 |
+
|
| 699 |
+
@skip_if_lt_x_gpu(1)
|
| 700 |
+
@dist_utils.dist_init
|
| 701 |
+
def test_input_moved_to_cuda_device(self):
|
| 702 |
+
if self.rank != 0:
|
| 703 |
+
return
|
| 704 |
+
dst_worker_name = dist_utils.worker_name((self.rank + 1) % self.world_size)
|
| 705 |
+
|
| 706 |
+
# These two CPU tensors (in args and kwargs) should be implicitly moved to an appropriate cuda device.
|
| 707 |
+
t1 = torch.ones(1)
|
| 708 |
+
args = (t1, 2)
|
| 709 |
+
t2 = t1 * 2
|
| 710 |
+
kwargs = dict(word=t2)
|
| 711 |
+
|
| 712 |
+
# Only test Python nn.Module, because script module methods don't support taking kwargs.
|
| 713 |
+
for remote_module in self._create_remote_module_iter(
|
| 714 |
+
f"{dst_worker_name}/cuda:0", modes=[ModuleCreationMode.MODULE_CTOR]
|
| 715 |
+
):
|
| 716 |
+
ret_fut = remote_module.forward_async(*args, **kwargs)
|
| 717 |
+
ret = ret_fut.wait()
|
| 718 |
+
self.assertEqual(ret, tuple(reversed(args + (t2,))))
|
| 719 |
+
# TODO: Once the RPC backend can support directly sending GPU tensors, the expected device type should be "cuda:0".
|
| 720 |
+
self.assertEqual(ret[0].device.type, "cpu")
|
| 721 |
+
self.assertEqual(ret[2].device.type, "cpu")
|
| 722 |
+
|
| 723 |
+
ret = remote_module.forward(*args, **kwargs)
|
| 724 |
+
self.assertEqual(ret, tuple(reversed(args + (t2,))))
|
| 725 |
+
# TODO: Once the RPC backend can support directly sending GPU tensors, the expected device type should be "cuda:0".
|
| 726 |
+
self.assertEqual(ret[0].device.type, "cpu")
|
| 727 |
+
self.assertEqual(ret[2].device.type, "cpu")
|
| 728 |
+
|
| 729 |
+
@skip_if_lt_x_gpu(1)
|
| 730 |
+
@dist_utils.dist_init
|
| 731 |
+
def test_input_moved_to_cuda_device_script(self):
|
| 732 |
+
if self.rank != 0:
|
| 733 |
+
return
|
| 734 |
+
dst_worker_name = dist_utils.worker_name((self.rank + 1) % self.world_size)
|
| 735 |
+
|
| 736 |
+
scripted_remote_module = next(
|
| 737 |
+
self._create_remote_module_iter(
|
| 738 |
+
f"{dst_worker_name}/cuda:0",
|
| 739 |
+
modes=[ModuleCreationMode.MODULE_CTOR_WITH_INTERFACE],
|
| 740 |
+
)
|
| 741 |
+
)
|
| 742 |
+
|
| 743 |
+
@torch.jit.script
|
| 744 |
+
def run_forward(scripted_remote_module: MyModuleInterface):
|
| 745 |
+
ret = scripted_remote_module.forward(torch.ones(1), 2, "3")
|
| 746 |
+
return ret
|
| 747 |
+
|
| 748 |
+
ret = run_forward(scripted_remote_module)
|
| 749 |
+
|
| 750 |
+
self.assertEqual(ret, ("3", 2, torch.ones(1)))
|
| 751 |
+
# TODO: Once the RPC backend can support directly sending GPU tensors, the expected device type should be "cuda:0".
|
| 752 |
+
self.assertEqual(ret[2].device.type, "cpu")
|
pace_revision/.venv-pace/lib/python3.11/site-packages/torch/testing/_internal/distributed/rpc/__init__.py
ADDED
|
File without changes
|