Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch-2.10.0+cu126.dist-info/INSTALLER +1 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch-2.10.0+cu126.dist-info/METADATA +640 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch-2.10.0+cu126.dist-info/RECORD +0 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch-2.10.0+cu126.dist-info/REQUESTED +0 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch-2.10.0+cu126.dist-info/WHEEL +5 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch-2.10.0+cu126.dist-info/entry_points.txt +6 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch-2.10.0+cu126.dist-info/licenses/LICENSE +0 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch-2.10.0+cu126.dist-info/licenses/NOTICE +456 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch-2.10.0+cu126.dist-info/top_level.txt +3 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/_pallas.py +103 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/_python_dispatch.py +911 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/_pytree.py +2216 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/_runtime_estimation.py +151 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/_stats.py +31 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/_strobelight/__init__.py +0 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/_strobelight/cli_function_profiler.py +313 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/_sympy/__init__.py +0 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/_sympy/functions.py +1463 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/_sympy/interp.py +228 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/_sympy/numbers.py +399 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/_sympy/printers.py +593 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/_sympy/reference.py +600 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/_sympy/singleton_int.py +96 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/_sympy/solve.py +179 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/_sympy/symbol.py +101 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/_sympy/value_ranges.py +1145 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/_thunk.py +29 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/_traceback.py +260 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/_triton.py +204 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/_typing_utils.py +14 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/_zip.py +86 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/backcompat/__init__.py +27 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/backend_registration.py +521 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/benchmark/__init__.py +6 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/benchmark/examples/__init__.py +0 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/benchmark/examples/compare.py +99 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/benchmark/examples/fuzzer.py +86 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/benchmark/examples/op_benchmark.py +107 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/benchmark/examples/simple_timeit.py +25 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/benchmark/examples/spectral_ops_fuzz_test.py +114 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/benchmark/op_fuzzers/__init__.py +0 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/benchmark/op_fuzzers/binary.py +107 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/benchmark/op_fuzzers/sparse_binary.py +107 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/benchmark/op_fuzzers/sparse_unary.py +92 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/benchmark/op_fuzzers/spectral.py +94 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/benchmark/op_fuzzers/unary.py +82 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/benchmark/utils/__init__.py +0 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/benchmark/utils/_stubs.py +42 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/benchmark/utils/common.py +359 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/benchmark/utils/compare.py +345 -0
miniconda3/envs/ladir/lib/python3.10/site-packages/torch-2.10.0+cu126.dist-info/INSTALLER
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
pip
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch-2.10.0+cu126.dist-info/METADATA
ADDED
|
@@ -0,0 +1,640 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.4
|
| 2 |
+
Name: torch
|
| 3 |
+
Version: 2.10.0+cu126
|
| 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: cuda-bindings==12.9.4; platform_system == "Linux"
|
| 42 |
+
Requires-Dist: nvidia-cuda-nvrtc-cu12==12.6.77; platform_system == "Linux"
|
| 43 |
+
Requires-Dist: nvidia-cuda-runtime-cu12==12.6.77; platform_system == "Linux"
|
| 44 |
+
Requires-Dist: nvidia-cuda-cupti-cu12==12.6.80; platform_system == "Linux"
|
| 45 |
+
Requires-Dist: nvidia-cudnn-cu12==9.10.2.21; platform_system == "Linux"
|
| 46 |
+
Requires-Dist: nvidia-cublas-cu12==12.6.4.1; platform_system == "Linux"
|
| 47 |
+
Requires-Dist: nvidia-cufft-cu12==11.3.0.4; platform_system == "Linux"
|
| 48 |
+
Requires-Dist: nvidia-curand-cu12==10.3.7.77; platform_system == "Linux"
|
| 49 |
+
Requires-Dist: nvidia-cusolver-cu12==11.7.1.2; platform_system == "Linux"
|
| 50 |
+
Requires-Dist: nvidia-cusparse-cu12==12.5.4.2; platform_system == "Linux"
|
| 51 |
+
Requires-Dist: nvidia-cusparselt-cu12==0.7.1; platform_system == "Linux"
|
| 52 |
+
Requires-Dist: nvidia-nccl-cu12==2.27.5; platform_system == "Linux"
|
| 53 |
+
Requires-Dist: nvidia-nvshmem-cu12==3.4.5; platform_system == "Linux"
|
| 54 |
+
Requires-Dist: nvidia-nvtx-cu12==12.6.77; platform_system == "Linux"
|
| 55 |
+
Requires-Dist: nvidia-nvjitlink-cu12==12.6.85; platform_system == "Linux"
|
| 56 |
+
Requires-Dist: nvidia-cufile-cu12==1.11.1.6; platform_system == "Linux"
|
| 57 |
+
Requires-Dist: triton==3.6.0; platform_system == "Linux"
|
| 58 |
+
Provides-Extra: optree
|
| 59 |
+
Requires-Dist: optree>=0.13.0; extra == "optree"
|
| 60 |
+
Provides-Extra: opt-einsum
|
| 61 |
+
Requires-Dist: opt-einsum>=3.3; extra == "opt-einsum"
|
| 62 |
+
Provides-Extra: pyyaml
|
| 63 |
+
Requires-Dist: pyyaml; extra == "pyyaml"
|
| 64 |
+
Dynamic: license-file
|
| 65 |
+
Dynamic: requires-dist
|
| 66 |
+
|
| 67 |
+

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

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

|
| 169 |
+
|
| 170 |
+
### Python First
|
| 171 |
+
|
| 172 |
+
PyTorch is not a Python binding into a monolithic C++ framework.
|
| 173 |
+
It is built to be deeply integrated into Python.
|
| 174 |
+
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.
|
| 175 |
+
You can write your new neural network layers in Python itself, using your favorite libraries
|
| 176 |
+
and use packages such as [Cython](https://cython.org/) and [Numba](http://numba.pydata.org/).
|
| 177 |
+
Our goal is to not reinvent the wheel where appropriate.
|
| 178 |
+
|
| 179 |
+
### Imperative Experiences
|
| 180 |
+
|
| 181 |
+
PyTorch is designed to be intuitive, linear in thought, and easy to use.
|
| 182 |
+
When you execute a line of code, it gets executed. There isn't an asynchronous view of the world.
|
| 183 |
+
When you drop into a debugger or receive error messages and stack traces, understanding them is straightforward.
|
| 184 |
+
The stack trace points to exactly where your code was defined.
|
| 185 |
+
We hope you never spend hours debugging your code because of bad stack traces or asynchronous and opaque execution engines.
|
| 186 |
+
|
| 187 |
+
### Fast and Lean
|
| 188 |
+
|
| 189 |
+
PyTorch has minimal framework overhead. We integrate acceleration libraries
|
| 190 |
+
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.
|
| 191 |
+
At the core, its CPU and GPU Tensor and neural network backends
|
| 192 |
+
are mature and have been tested for years.
|
| 193 |
+
|
| 194 |
+
Hence, PyTorch is quite fast — whether you run small or large neural networks.
|
| 195 |
+
|
| 196 |
+
The memory usage in PyTorch is extremely efficient compared to Torch or some of the alternatives.
|
| 197 |
+
We've written custom memory allocators for the GPU to make sure that
|
| 198 |
+
your deep learning models are maximally memory efficient.
|
| 199 |
+
This enables you to train bigger deep learning models than before.
|
| 200 |
+
|
| 201 |
+
### Extensions Without Pain
|
| 202 |
+
|
| 203 |
+
Writing new neural network modules, or interfacing with PyTorch's Tensor API was designed to be straightforward
|
| 204 |
+
and with minimal abstractions.
|
| 205 |
+
|
| 206 |
+
You can write new neural network layers in Python using the torch API
|
| 207 |
+
[or your favorite NumPy-based libraries such as SciPy](https://pytorch.org/tutorials/advanced/numpy_extensions_tutorial.html).
|
| 208 |
+
|
| 209 |
+
If you want to write your layers in C/C++, we provide a convenient extension API that is efficient and with minimal boilerplate.
|
| 210 |
+
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).
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
## Installation
|
| 214 |
+
|
| 215 |
+
### Binaries
|
| 216 |
+
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/)
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
#### NVIDIA Jetson Platforms
|
| 220 |
+
|
| 221 |
+
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)
|
| 222 |
+
|
| 223 |
+
They require JetPack 4.2 and above, and [@dusty-nv](https://github.com/dusty-nv) and [@ptrblck](https://github.com/ptrblck) are maintaining them.
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
### From Source
|
| 227 |
+
|
| 228 |
+
#### Prerequisites
|
| 229 |
+
If you are installing from source, you will need:
|
| 230 |
+
- Python 3.10 or later
|
| 231 |
+
- A compiler that fully supports C++17, such as clang or gcc (gcc 9.4.0 or newer is required, on Linux)
|
| 232 |
+
- Visual Studio or Visual Studio Build Tool (Windows only)
|
| 233 |
+
|
| 234 |
+
\* PyTorch CI uses Visual C++ BuildTools, which come with Visual Studio Enterprise,
|
| 235 |
+
Professional, or Community Editions. You can also install the build tools from
|
| 236 |
+
https://visualstudio.microsoft.com/visual-cpp-build-tools/. The build tools *do not*
|
| 237 |
+
come with Visual Studio Code by default.
|
| 238 |
+
|
| 239 |
+
An example of environment setup is shown below:
|
| 240 |
+
|
| 241 |
+
* Linux:
|
| 242 |
+
|
| 243 |
+
```bash
|
| 244 |
+
$ source <CONDA_INSTALL_DIR>/bin/activate
|
| 245 |
+
$ conda create -y -n <CONDA_NAME>
|
| 246 |
+
$ conda activate <CONDA_NAME>
|
| 247 |
+
```
|
| 248 |
+
|
| 249 |
+
* Windows:
|
| 250 |
+
|
| 251 |
+
```bash
|
| 252 |
+
$ source <CONDA_INSTALL_DIR>\Scripts\activate.bat
|
| 253 |
+
$ conda create -y -n <CONDA_NAME>
|
| 254 |
+
$ conda activate <CONDA_NAME>
|
| 255 |
+
$ call "C:\Program Files\Microsoft Visual Studio\<VERSION>\Community\VC\Auxiliary\Build\vcvarsall.bat" x64
|
| 256 |
+
```
|
| 257 |
+
|
| 258 |
+
A conda environment is not required. You can also do a PyTorch build in a
|
| 259 |
+
standard virtual environment, e.g., created with tools like `uv`, provided
|
| 260 |
+
your system has installed all the necessary dependencies unavailable as pip
|
| 261 |
+
packages (e.g., CUDA, MKL.)
|
| 262 |
+
|
| 263 |
+
##### NVIDIA CUDA Support
|
| 264 |
+
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:
|
| 265 |
+
- [NVIDIA CUDA](https://developer.nvidia.com/cuda-downloads)
|
| 266 |
+
- [NVIDIA cuDNN](https://developer.nvidia.com/cudnn) v8.5 or above
|
| 267 |
+
- [Compiler](https://gist.github.com/ax3l/9489132) compatible with CUDA
|
| 268 |
+
|
| 269 |
+
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.
|
| 270 |
+
|
| 271 |
+
If you want to disable CUDA support, export the environment variable `USE_CUDA=0`.
|
| 272 |
+
Other potentially useful environment variables may be found in `setup.py`. If
|
| 273 |
+
CUDA is installed in a non-standard location, set PATH so that the nvcc you
|
| 274 |
+
want to use can be found (e.g., `export PATH=/usr/local/cuda-12.8/bin:$PATH`).
|
| 275 |
+
|
| 276 |
+
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/)
|
| 277 |
+
|
| 278 |
+
##### AMD ROCm Support
|
| 279 |
+
If you want to compile with ROCm support, install
|
| 280 |
+
- [AMD ROCm](https://rocm.docs.amd.com/en/latest/deploy/linux/quick_start.html) 4.0 and above installation
|
| 281 |
+
- ROCm is currently supported only for Linux systems.
|
| 282 |
+
|
| 283 |
+
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)
|
| 284 |
+
|
| 285 |
+
If you want to disable ROCm support, export the environment variable `USE_ROCM=0`.
|
| 286 |
+
Other potentially useful environment variables may be found in `setup.py`.
|
| 287 |
+
|
| 288 |
+
##### Intel GPU Support
|
| 289 |
+
If you want to compile with Intel GPU support, follow these
|
| 290 |
+
- [PyTorch Prerequisites for Intel GPUs](https://www.intel.com/content/www/us/en/developer/articles/tool/pytorch-prerequisites-for-intel-gpus.html) instructions.
|
| 291 |
+
- Intel GPU is supported for Linux and Windows.
|
| 292 |
+
|
| 293 |
+
If you want to disable Intel GPU support, export the environment variable `USE_XPU=0`.
|
| 294 |
+
Other potentially useful environment variables may be found in `setup.py`.
|
| 295 |
+
|
| 296 |
+
#### Get the PyTorch Source
|
| 297 |
+
|
| 298 |
+
```bash
|
| 299 |
+
git clone https://github.com/pytorch/pytorch
|
| 300 |
+
cd pytorch
|
| 301 |
+
# if you are updating an existing checkout
|
| 302 |
+
git submodule sync
|
| 303 |
+
git submodule update --init --recursive
|
| 304 |
+
```
|
| 305 |
+
|
| 306 |
+
#### Install Dependencies
|
| 307 |
+
|
| 308 |
+
**Common**
|
| 309 |
+
|
| 310 |
+
```bash
|
| 311 |
+
# Run this command from the PyTorch directory after cloning the source code using the “Get the PyTorch Source“ section above
|
| 312 |
+
pip install --group dev
|
| 313 |
+
```
|
| 314 |
+
|
| 315 |
+
**On Linux**
|
| 316 |
+
|
| 317 |
+
```bash
|
| 318 |
+
pip install mkl-static mkl-include
|
| 319 |
+
# CUDA only: Add LAPACK support for the GPU if needed
|
| 320 |
+
# magma installation: run with active conda environment. specify CUDA version to install
|
| 321 |
+
.ci/docker/common/install_magma_conda.sh 12.4
|
| 322 |
+
|
| 323 |
+
# (optional) If using torch.compile with inductor/triton, install the matching version of triton
|
| 324 |
+
# Run from the pytorch directory after cloning
|
| 325 |
+
# For Intel GPU support, please explicitly `export USE_XPU=1` before running command.
|
| 326 |
+
make triton
|
| 327 |
+
```
|
| 328 |
+
|
| 329 |
+
**On MacOS**
|
| 330 |
+
|
| 331 |
+
```bash
|
| 332 |
+
# Add this package on intel x86 processor machines only
|
| 333 |
+
pip install mkl-static mkl-include
|
| 334 |
+
# Add these packages if torch.distributed is needed
|
| 335 |
+
conda install pkg-config libuv
|
| 336 |
+
```
|
| 337 |
+
|
| 338 |
+
**On Windows**
|
| 339 |
+
|
| 340 |
+
```bash
|
| 341 |
+
pip install mkl-static mkl-include
|
| 342 |
+
# Add these packages if torch.distributed is needed.
|
| 343 |
+
# Distributed package support on Windows is a prototype feature and is subject to changes.
|
| 344 |
+
conda install -c conda-forge libuv=1.51
|
| 345 |
+
```
|
| 346 |
+
|
| 347 |
+
#### Install PyTorch
|
| 348 |
+
|
| 349 |
+
**On Linux**
|
| 350 |
+
|
| 351 |
+
If you're compiling for AMD ROCm then first run this command:
|
| 352 |
+
|
| 353 |
+
```bash
|
| 354 |
+
# Only run this if you're compiling for ROCm
|
| 355 |
+
python tools/amd_build/build_amd.py
|
| 356 |
+
```
|
| 357 |
+
|
| 358 |
+
Install PyTorch
|
| 359 |
+
|
| 360 |
+
```bash
|
| 361 |
+
# the CMake prefix for conda environment
|
| 362 |
+
export CMAKE_PREFIX_PATH="${CONDA_PREFIX:-'$(dirname $(which conda))/../'}:${CMAKE_PREFIX_PATH}"
|
| 363 |
+
python -m pip install --no-build-isolation -v -e .
|
| 364 |
+
|
| 365 |
+
# the CMake prefix for non-conda environment, e.g. Python venv
|
| 366 |
+
# call following after activating the venv
|
| 367 |
+
export CMAKE_PREFIX_PATH="${VIRTUAL_ENV}:${CMAKE_PREFIX_PATH}"
|
| 368 |
+
```
|
| 369 |
+
|
| 370 |
+
**On macOS**
|
| 371 |
+
|
| 372 |
+
```bash
|
| 373 |
+
python -m pip install --no-build-isolation -v -e .
|
| 374 |
+
```
|
| 375 |
+
|
| 376 |
+
**On Windows**
|
| 377 |
+
|
| 378 |
+
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)
|
| 379 |
+
|
| 380 |
+
**CPU-only builds**
|
| 381 |
+
|
| 382 |
+
In this mode PyTorch computations will run on your CPU, not your GPU.
|
| 383 |
+
|
| 384 |
+
```cmd
|
| 385 |
+
python -m pip install --no-build-isolation -v -e .
|
| 386 |
+
```
|
| 387 |
+
|
| 388 |
+
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.
|
| 389 |
+
|
| 390 |
+
**CUDA based build**
|
| 391 |
+
|
| 392 |
+
In this mode PyTorch computations will leverage your GPU via CUDA for faster number crunching
|
| 393 |
+
|
| 394 |
+
[NVTX](https://docs.nvidia.com/gameworks/content/gameworkslibrary/nvtx/nvidia_tools_extension_library_nvtx.htm) is needed to build Pytorch with CUDA.
|
| 395 |
+
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.
|
| 396 |
+
Make sure that CUDA with Nsight Compute is installed after Visual Studio.
|
| 397 |
+
|
| 398 |
+
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.
|
| 399 |
+
<br/> If Ninja is selected as the generator, the latest MSVC will get selected as the underlying toolchain.
|
| 400 |
+
|
| 401 |
+
Additional libraries such as
|
| 402 |
+
[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.
|
| 403 |
+
|
| 404 |
+
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
|
| 405 |
+
|
| 406 |
+
```cmd
|
| 407 |
+
cmd
|
| 408 |
+
|
| 409 |
+
:: Set the environment variables after you have downloaded and unzipped the mkl package,
|
| 410 |
+
:: else CMake would throw an error as `Could NOT find OpenMP`.
|
| 411 |
+
set CMAKE_INCLUDE_PATH={Your directory}\mkl\include
|
| 412 |
+
set LIB={Your directory}\mkl\lib;%LIB%
|
| 413 |
+
|
| 414 |
+
:: Read the content in the previous section carefully before you proceed.
|
| 415 |
+
:: [Optional] If you want to override the underlying toolset used by Ninja and Visual Studio with CUDA, please run the following script block.
|
| 416 |
+
:: "Visual Studio 2019 Developer Command Prompt" will be run automatically.
|
| 417 |
+
:: Make sure you have CMake >= 3.12 before you do this when you use the Visual Studio generator.
|
| 418 |
+
set CMAKE_GENERATOR_TOOLSET_VERSION=14.27
|
| 419 |
+
set DISTUTILS_USE_SDK=1
|
| 420 |
+
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%
|
| 421 |
+
|
| 422 |
+
:: [Optional] If you want to override the CUDA host compiler
|
| 423 |
+
set CUDAHOSTCXX=C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.27.29110\bin\HostX64\x64\cl.exe
|
| 424 |
+
|
| 425 |
+
python -m pip install --no-build-isolation -v -e .
|
| 426 |
+
```
|
| 427 |
+
|
| 428 |
+
**Intel GPU builds**
|
| 429 |
+
|
| 430 |
+
In this mode PyTorch with Intel GPU support will be built.
|
| 431 |
+
|
| 432 |
+
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.
|
| 433 |
+
|
| 434 |
+
Then PyTorch can be built with the command:
|
| 435 |
+
|
| 436 |
+
```cmd
|
| 437 |
+
:: CMD Commands:
|
| 438 |
+
:: Set the CMAKE_PREFIX_PATH to help find corresponding packages
|
| 439 |
+
:: %CONDA_PREFIX% only works after `conda activate custom_env`
|
| 440 |
+
|
| 441 |
+
if defined CMAKE_PREFIX_PATH (
|
| 442 |
+
set "CMAKE_PREFIX_PATH=%CONDA_PREFIX%\Library;%CMAKE_PREFIX_PATH%"
|
| 443 |
+
) else (
|
| 444 |
+
set "CMAKE_PREFIX_PATH=%CONDA_PREFIX%\Library"
|
| 445 |
+
)
|
| 446 |
+
|
| 447 |
+
python -m pip install --no-build-isolation -v -e .
|
| 448 |
+
```
|
| 449 |
+
|
| 450 |
+
##### Adjust Build Options (Optional)
|
| 451 |
+
|
| 452 |
+
You can adjust the configuration of cmake variables optionally (without building first), by doing
|
| 453 |
+
the following. For example, adjusting the pre-detected directories for CuDNN or BLAS can be done
|
| 454 |
+
with such a step.
|
| 455 |
+
|
| 456 |
+
On Linux
|
| 457 |
+
|
| 458 |
+
```bash
|
| 459 |
+
export CMAKE_PREFIX_PATH="${CONDA_PREFIX:-'$(dirname $(which conda))/../'}:${CMAKE_PREFIX_PATH}"
|
| 460 |
+
CMAKE_ONLY=1 python setup.py build
|
| 461 |
+
ccmake build # or cmake-gui build
|
| 462 |
+
```
|
| 463 |
+
|
| 464 |
+
On macOS
|
| 465 |
+
|
| 466 |
+
```bash
|
| 467 |
+
export CMAKE_PREFIX_PATH="${CONDA_PREFIX:-'$(dirname $(which conda))/../'}:${CMAKE_PREFIX_PATH}"
|
| 468 |
+
MACOSX_DEPLOYMENT_TARGET=11.0 CMAKE_ONLY=1 python setup.py build
|
| 469 |
+
ccmake build # or cmake-gui build
|
| 470 |
+
```
|
| 471 |
+
|
| 472 |
+
### Docker Image
|
| 473 |
+
|
| 474 |
+
#### Using pre-built images
|
| 475 |
+
|
| 476 |
+
You can also pull a pre-built docker image from Docker Hub and run with docker v19.03+
|
| 477 |
+
|
| 478 |
+
```bash
|
| 479 |
+
docker run --gpus all --rm -ti --ipc=host pytorch/pytorch:latest
|
| 480 |
+
```
|
| 481 |
+
|
| 482 |
+
Please note that PyTorch uses shared memory to share data between processes, so if torch multiprocessing is used (e.g.
|
| 483 |
+
for multithreaded data loaders) the default shared memory segment size that container runs with is not enough, and you
|
| 484 |
+
should increase shared memory size either with `--ipc=host` or `--shm-size` command line options to `nvidia-docker run`.
|
| 485 |
+
|
| 486 |
+
#### Building the image yourself
|
| 487 |
+
|
| 488 |
+
**NOTE:** Must be built with a docker version > 18.06
|
| 489 |
+
|
| 490 |
+
The `Dockerfile` is supplied to build images with CUDA 11.1 support and cuDNN v8.
|
| 491 |
+
You can pass `PYTHON_VERSION=x.y` make variable to specify which Python version is to be used by Miniconda, or leave it
|
| 492 |
+
unset to use the default.
|
| 493 |
+
|
| 494 |
+
```bash
|
| 495 |
+
make -f docker.Makefile
|
| 496 |
+
# images are tagged as docker.io/${your_docker_username}/pytorch
|
| 497 |
+
```
|
| 498 |
+
|
| 499 |
+
You can also pass the `CMAKE_VARS="..."` environment variable to specify additional CMake variables to be passed to CMake during the build.
|
| 500 |
+
See [setup.py](./setup.py) for the list of available variables.
|
| 501 |
+
|
| 502 |
+
```bash
|
| 503 |
+
make -f docker.Makefile
|
| 504 |
+
```
|
| 505 |
+
|
| 506 |
+
### Building the Documentation
|
| 507 |
+
|
| 508 |
+
To build documentation in various formats, you will need [Sphinx](http://www.sphinx-doc.org)
|
| 509 |
+
and the pytorch_sphinx_theme2.
|
| 510 |
+
|
| 511 |
+
Before you build the documentation locally, ensure `torch` is
|
| 512 |
+
installed in your environment. For small fixes, you can install the
|
| 513 |
+
nightly version as described in [Getting Started](https://pytorch.org/get-started/locally/).
|
| 514 |
+
|
| 515 |
+
For more complex fixes, such as adding a new module and docstrings for
|
| 516 |
+
the new module, you might need to install torch [from source](#from-source).
|
| 517 |
+
See [Docstring Guidelines](https://github.com/pytorch/pytorch/wiki/Docstring-Guidelines)
|
| 518 |
+
for docstring conventions.
|
| 519 |
+
|
| 520 |
+
```bash
|
| 521 |
+
cd docs/
|
| 522 |
+
pip install -r requirements.txt
|
| 523 |
+
make html
|
| 524 |
+
make serve
|
| 525 |
+
```
|
| 526 |
+
|
| 527 |
+
Run `make` to get a list of all available output formats.
|
| 528 |
+
|
| 529 |
+
If you get a katex error run `npm install katex`. If it persists, try
|
| 530 |
+
`npm install -g katex`
|
| 531 |
+
|
| 532 |
+
> [!NOTE]
|
| 533 |
+
> If you installed `nodejs` with a different package manager (e.g.,
|
| 534 |
+
> `conda`) then `npm` will probably install a version of `katex` that is not
|
| 535 |
+
> compatible with your version of `nodejs` and doc builds will fail.
|
| 536 |
+
> A combination of versions that is known to work is `node@6.13.1` and
|
| 537 |
+
> `katex@0.13.18`. To install the latter with `npm` you can run
|
| 538 |
+
> ```npm install -g katex@0.13.18```
|
| 539 |
+
|
| 540 |
+
> [!NOTE]
|
| 541 |
+
> If you see a numpy incompatibility error, run:
|
| 542 |
+
> ```
|
| 543 |
+
> pip install 'numpy<2'
|
| 544 |
+
> ```
|
| 545 |
+
|
| 546 |
+
When you make changes to the dependencies run by CI, edit the
|
| 547 |
+
`.ci/docker/requirements-docs.txt` file.
|
| 548 |
+
|
| 549 |
+
#### Building a PDF
|
| 550 |
+
|
| 551 |
+
To compile a PDF of all PyTorch documentation, ensure you have
|
| 552 |
+
`texlive` and LaTeX installed. On macOS, you can install them using:
|
| 553 |
+
|
| 554 |
+
```
|
| 555 |
+
brew install --cask mactex
|
| 556 |
+
```
|
| 557 |
+
|
| 558 |
+
To create the PDF:
|
| 559 |
+
|
| 560 |
+
1. Run:
|
| 561 |
+
|
| 562 |
+
```
|
| 563 |
+
make latexpdf
|
| 564 |
+
```
|
| 565 |
+
|
| 566 |
+
This will generate the necessary files in the `build/latex` directory.
|
| 567 |
+
|
| 568 |
+
2. Navigate to this directory and execute:
|
| 569 |
+
|
| 570 |
+
```
|
| 571 |
+
make LATEXOPTS="-interaction=nonstopmode"
|
| 572 |
+
```
|
| 573 |
+
|
| 574 |
+
This will produce a `pytorch.pdf` with the desired content. Run this
|
| 575 |
+
command one more time so that it generates the correct table
|
| 576 |
+
of contents and index.
|
| 577 |
+
|
| 578 |
+
> [!NOTE]
|
| 579 |
+
> To view the Table of Contents, switch to the **Table of Contents**
|
| 580 |
+
> view in your PDF viewer.
|
| 581 |
+
|
| 582 |
+
|
| 583 |
+
### Previous Versions
|
| 584 |
+
|
| 585 |
+
Installation instructions and binaries for previous PyTorch versions may be found
|
| 586 |
+
on [our website](https://pytorch.org/get-started/previous-versions).
|
| 587 |
+
|
| 588 |
+
|
| 589 |
+
## Getting Started
|
| 590 |
+
|
| 591 |
+
Three pointers to get you started:
|
| 592 |
+
- [Tutorials: get you started with understanding and using PyTorch](https://pytorch.org/tutorials/)
|
| 593 |
+
- [Examples: easy to understand PyTorch code across all domains](https://github.com/pytorch/examples)
|
| 594 |
+
- [The API Reference](https://pytorch.org/docs/)
|
| 595 |
+
- [Glossary](https://github.com/pytorch/pytorch/blob/main/GLOSSARY.md)
|
| 596 |
+
|
| 597 |
+
## Resources
|
| 598 |
+
|
| 599 |
+
* [PyTorch.org](https://pytorch.org/)
|
| 600 |
+
* [PyTorch Tutorials](https://pytorch.org/tutorials/)
|
| 601 |
+
* [PyTorch Examples](https://github.com/pytorch/examples)
|
| 602 |
+
* [PyTorch Models](https://pytorch.org/hub/)
|
| 603 |
+
* [Intro to Deep Learning with PyTorch from Udacity](https://www.udacity.com/course/deep-learning-pytorch--ud188)
|
| 604 |
+
* [Intro to Machine Learning with PyTorch from Udacity](https://www.udacity.com/course/intro-to-machine-learning-nanodegree--nd229)
|
| 605 |
+
* [Deep Neural Networks with PyTorch from Coursera](https://www.coursera.org/learn/deep-neural-networks-with-pytorch)
|
| 606 |
+
* [PyTorch Twitter](https://twitter.com/PyTorch)
|
| 607 |
+
* [PyTorch Blog](https://pytorch.org/blog/)
|
| 608 |
+
* [PyTorch YouTube](https://www.youtube.com/channel/UCWXI5YeOsh03QvJ59PMaXFw)
|
| 609 |
+
|
| 610 |
+
## Communication
|
| 611 |
+
* Forums: Discuss implementations, research, etc. https://discuss.pytorch.org
|
| 612 |
+
* GitHub Issues: Bug reports, feature requests, install issues, RFCs, thoughts, etc.
|
| 613 |
+
* 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
|
| 614 |
+
* Newsletter: No-noise, a one-way email newsletter with important announcements about PyTorch. You can sign-up here: https://eepurl.com/cbG0rv
|
| 615 |
+
* Facebook Page: Important announcements about PyTorch. https://www.facebook.com/pytorch
|
| 616 |
+
* For brand guidelines, please visit our website at [pytorch.org](https://pytorch.org/)
|
| 617 |
+
|
| 618 |
+
## Releases and Contributing
|
| 619 |
+
|
| 620 |
+
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).
|
| 621 |
+
|
| 622 |
+
We appreciate all contributions. If you are planning to contribute back bug-fixes, please do so without any further discussion.
|
| 623 |
+
|
| 624 |
+
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.
|
| 625 |
+
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.
|
| 626 |
+
|
| 627 |
+
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).
|
| 628 |
+
|
| 629 |
+
## The Team
|
| 630 |
+
|
| 631 |
+
PyTorch is a community-driven project with several skillful engineers and researchers contributing to it.
|
| 632 |
+
|
| 633 |
+
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.
|
| 634 |
+
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 -->
|
| 635 |
+
|
| 636 |
+
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.
|
| 637 |
+
|
| 638 |
+
## License
|
| 639 |
+
|
| 640 |
+
PyTorch has a BSD-style license, as found in the [LICENSE](LICENSE) file.
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch-2.10.0+cu126.dist-info/RECORD
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch-2.10.0+cu126.dist-info/REQUESTED
ADDED
|
File without changes
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch-2.10.0+cu126.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: setuptools (80.9.0)
|
| 3 |
+
Root-Is-Purelib: false
|
| 4 |
+
Tag: cp310-cp310-manylinux_2_28_x86_64
|
| 5 |
+
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch-2.10.0+cu126.dist-info/entry_points.txt
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[console_scripts]
|
| 2 |
+
torchfrtrace = torch.distributed.flight_recorder.fr_trace:main
|
| 3 |
+
torchrun = torch.distributed.run:main
|
| 4 |
+
|
| 5 |
+
[torchrun.logs_specs]
|
| 6 |
+
default = torch.distributed.elastic.multiprocessing:DefaultLogsSpecs
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch-2.10.0+cu126.dist-info/licenses/LICENSE
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch-2.10.0+cu126.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.
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch-2.10.0+cu126.dist-info/top_level.txt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
functorch
|
| 2 |
+
torch
|
| 3 |
+
torchgen
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/_pallas.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import functools
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
@functools.cache
|
| 7 |
+
def has_jax_package() -> bool:
|
| 8 |
+
"""Check if JAX is installed."""
|
| 9 |
+
try:
|
| 10 |
+
import jax # noqa: F401 # type: ignore[import-not-found]
|
| 11 |
+
|
| 12 |
+
return True
|
| 13 |
+
except ImportError:
|
| 14 |
+
return False
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@functools.cache
|
| 18 |
+
def has_pallas_package() -> bool:
|
| 19 |
+
"""Check if Pallas (JAX experimental) is available."""
|
| 20 |
+
if not has_jax_package():
|
| 21 |
+
return False
|
| 22 |
+
try:
|
| 23 |
+
from jax.experimental import ( # noqa: F401 # type: ignore[import-not-found]
|
| 24 |
+
pallas as pl,
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
return True
|
| 28 |
+
except ImportError:
|
| 29 |
+
return False
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
@functools.cache
|
| 33 |
+
def get_jax_version(fallback: tuple[int, int, int] = (0, 0, 0)) -> tuple[int, int, int]:
|
| 34 |
+
"""Get JAX version as (major, minor, patch) tuple."""
|
| 35 |
+
try:
|
| 36 |
+
import jax # type: ignore[import-not-found]
|
| 37 |
+
|
| 38 |
+
version_parts = jax.__version__.split(".")
|
| 39 |
+
major, minor, patch = (int(v) for v in version_parts[:3])
|
| 40 |
+
return (major, minor, patch)
|
| 41 |
+
except (ImportError, ValueError, AttributeError):
|
| 42 |
+
return fallback
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
@functools.cache
|
| 46 |
+
def has_jax_cuda_backend() -> bool:
|
| 47 |
+
"""Check if JAX has CUDA backend support."""
|
| 48 |
+
if not has_jax_package():
|
| 49 |
+
return False
|
| 50 |
+
try:
|
| 51 |
+
import jax # type: ignore[import-not-found]
|
| 52 |
+
|
| 53 |
+
# Check if CUDA backend is available
|
| 54 |
+
devices = jax.devices("gpu")
|
| 55 |
+
return len(devices) > 0
|
| 56 |
+
except Exception:
|
| 57 |
+
return False
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
@functools.cache
|
| 61 |
+
def has_jax_tpu_backend() -> bool:
|
| 62 |
+
"""Check if JAX has TPU backend support."""
|
| 63 |
+
if not has_jax_package():
|
| 64 |
+
return False
|
| 65 |
+
try:
|
| 66 |
+
import jax # type: ignore[import-not-found]
|
| 67 |
+
|
| 68 |
+
# Check if TPU backend is available
|
| 69 |
+
devices = jax.devices("tpu")
|
| 70 |
+
return len(devices) > 0
|
| 71 |
+
except Exception:
|
| 72 |
+
return False
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
@functools.cache
|
| 76 |
+
def has_cpu_pallas() -> bool:
|
| 77 |
+
"""Checks for a full Pallas-on-CPU environment."""
|
| 78 |
+
return has_pallas_package()
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
@functools.cache
|
| 82 |
+
def has_cuda_pallas() -> bool:
|
| 83 |
+
"""Checks for a full Pallas-on-CUDA environment."""
|
| 84 |
+
return has_pallas_package() and torch.cuda.is_available() and has_jax_cuda_backend()
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
@functools.cache
|
| 88 |
+
def has_tpu_pallas() -> bool:
|
| 89 |
+
"""Checks for a full Pallas-on-TPU environment."""
|
| 90 |
+
return has_pallas_package() and has_jax_tpu_backend()
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
@functools.cache
|
| 94 |
+
def has_pallas() -> bool:
|
| 95 |
+
"""
|
| 96 |
+
Check if Pallas backend is fully available for use.
|
| 97 |
+
|
| 98 |
+
Requirements:
|
| 99 |
+
- JAX package installed
|
| 100 |
+
- Pallas (jax.experimental.pallas) available
|
| 101 |
+
- A compatible backend (CUDA or TPU) is available in both PyTorch and JAX.
|
| 102 |
+
"""
|
| 103 |
+
return has_cpu_pallas() or has_cuda_pallas() or has_tpu_pallas()
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/_python_dispatch.py
ADDED
|
@@ -0,0 +1,911 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import contextlib
|
| 5 |
+
import functools
|
| 6 |
+
import warnings
|
| 7 |
+
from collections import deque
|
| 8 |
+
from dataclasses import dataclass
|
| 9 |
+
from typing import cast, overload, Protocol, TYPE_CHECKING
|
| 10 |
+
from typing_extensions import TypeIs
|
| 11 |
+
|
| 12 |
+
import torch
|
| 13 |
+
import torchgen
|
| 14 |
+
import torchgen.model
|
| 15 |
+
from torch._C import (
|
| 16 |
+
_get_dispatch_stack_at,
|
| 17 |
+
_len_torch_dispatch_stack,
|
| 18 |
+
_pop_torch_dispatch_stack,
|
| 19 |
+
_push_on_torch_dispatch_stack,
|
| 20 |
+
DispatchKey,
|
| 21 |
+
)
|
| 22 |
+
from torch._C._dynamo.guards import set_is_in_mode_without_ignore_compile_internals
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
if TYPE_CHECKING:
|
| 26 |
+
from collections.abc import Sequence
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
# TODO: Limitations and things about enable_torch_dispatch_mode we should fix before exposing it:
|
| 30 |
+
# - We need a better user-facing api for _DisableTorchDispatch that
|
| 31 |
+
# is able to selectively disable __torch_dispatch__ of a particular class.
|
| 32 |
+
# - It doesn't work with the tensor constructors (torch.tensor, torch.Tensor)
|
| 33 |
+
# - Better name (see https://github.com/pytorch/pytorch/pull/63496#discussion_r694091694)
|
| 34 |
+
|
| 35 |
+
_is_in_torch_dispatch_mode = False
|
| 36 |
+
_is_in_non_infra_torch_dispatch_mode = False
|
| 37 |
+
# If inside any mode that has ignore_compile_internals() = False
|
| 38 |
+
_is_in_any_mode_without_ignore_compile_internals = False
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def is_in_torch_dispatch_mode(include_infra_modes: bool = True) -> bool:
|
| 42 |
+
return (
|
| 43 |
+
_is_in_torch_dispatch_mode
|
| 44 |
+
if include_infra_modes
|
| 45 |
+
else _is_in_non_infra_torch_dispatch_mode
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def is_in_any_mode_without_ignore_compile_internals() -> bool:
|
| 50 |
+
return _is_in_any_mode_without_ignore_compile_internals
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
class TorchDispatchMode:
|
| 54 |
+
"""
|
| 55 |
+
A ``TorchDispatchMode`` allows you to override the meaning of all
|
| 56 |
+
``__torch_dispatch__`` overrideable functions within a dynamic scope,
|
| 57 |
+
without having to actually create a tensor subclass or manually
|
| 58 |
+
monkey-patch functions in the PyTorch API. Some common situations
|
| 59 |
+
where you should use a mode:
|
| 60 |
+
|
| 61 |
+
* You want to override the meaning of factory functions, or other
|
| 62 |
+
functions that do not otherwise take a tensor as an argument
|
| 63 |
+
(these cannot be overridden with tensor subclasses).
|
| 64 |
+
|
| 65 |
+
* You want to override the behavior of all functions without needing
|
| 66 |
+
to wrap your inputs in tensor subclasses; e.g., if you are just
|
| 67 |
+
interested in logging intermediate computations.
|
| 68 |
+
|
| 69 |
+
* You want to control the order of execution of various tensor
|
| 70 |
+
subclasses explicitly, rather than implicitly via the return of
|
| 71 |
+
``NotImplemented``.
|
| 72 |
+
|
| 73 |
+
Independent subclasses of :class:`TorchDispatchMode` are compositional:
|
| 74 |
+
modes can be pushed onto a stack using ``with MyMode():``.
|
| 75 |
+
When you call functions in the PyTorch API inside your
|
| 76 |
+
``__torch_dispatch__`` implementation, by default, they will forward on to
|
| 77 |
+
the next mode on the mode stack. If you want recursively call back into
|
| 78 |
+
your current ``__torch_dispatch__`` implementation, either explicitly
|
| 79 |
+
invoke ``self.__torch_dispatch__(...)``, or use the context manager
|
| 80 |
+
``self`` to make PyTorch
|
| 81 |
+
API self-referential (beware of infinite loops, in this case!)
|
| 82 |
+
"""
|
| 83 |
+
|
| 84 |
+
# - When False, custom torch dispatch mode will error out explicitly when a hop
|
| 85 |
+
# is called under the mode.
|
| 86 |
+
# - When True, custom torch dispatch mode's __torch_dispatch__ will be triggered.
|
| 87 |
+
# Mode authors can implement how the mode interacts with higher order operators.
|
| 88 |
+
supports_higher_order_operators = False
|
| 89 |
+
|
| 90 |
+
def __init__(self, _dispatch_key=None) -> None:
|
| 91 |
+
if _dispatch_key is not None:
|
| 92 |
+
if not isinstance(_dispatch_key, torch._C.DispatchKey):
|
| 93 |
+
raise AssertionError("_dispatch_key must be a torch._C.DispatchKey")
|
| 94 |
+
self.__dict__["_dispatch_key"] = _dispatch_key
|
| 95 |
+
|
| 96 |
+
self.old_dispatch_mode_flags: deque[bool] = deque()
|
| 97 |
+
self.old_non_infra_dispatch_mode_flags: deque[bool] = deque()
|
| 98 |
+
self.old_without_ignore_compile_internals_dispatch_mode_flags: deque[bool] = (
|
| 99 |
+
deque()
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
def _lazy_init_old_dispatch_mode_flags(self) -> None:
|
| 103 |
+
if not hasattr(self, "old_dispatch_mode_flags"):
|
| 104 |
+
self.old_dispatch_mode_flags: deque[bool] = deque() # type: ignore[no-redef]
|
| 105 |
+
|
| 106 |
+
if not hasattr(self, "old_non_infra_dispatch_mode_flags"):
|
| 107 |
+
self.old_non_infra_dispatch_mode_flags: deque[bool] = deque() # type: ignore[no-redef]
|
| 108 |
+
|
| 109 |
+
if not hasattr(
|
| 110 |
+
self, "old_without_ignore_compile_internals_dispatch_mode_flags"
|
| 111 |
+
):
|
| 112 |
+
self.old_without_ignore_compile_internals_dispatch_mode_flags: deque[ # type: ignore[no-redef]
|
| 113 |
+
bool
|
| 114 |
+
] = deque()
|
| 115 |
+
|
| 116 |
+
def __torch_dispatch__(self, func, types, args=(), kwargs=None):
|
| 117 |
+
raise NotImplementedError
|
| 118 |
+
|
| 119 |
+
def __enter__(self):
|
| 120 |
+
global _is_in_torch_dispatch_mode
|
| 121 |
+
global _is_in_non_infra_torch_dispatch_mode
|
| 122 |
+
global _is_in_any_mode_without_ignore_compile_internals
|
| 123 |
+
|
| 124 |
+
# Previously, there wasn't any state in this class' constructor
|
| 125 |
+
# super calls were added to existing modes, but for any new modes
|
| 126 |
+
# this will replicate the previous behavior of not strictly needing
|
| 127 |
+
# to call super().__init__()
|
| 128 |
+
self._lazy_init_old_dispatch_mode_flags()
|
| 129 |
+
self.old_dispatch_mode_flags.append(_is_in_torch_dispatch_mode)
|
| 130 |
+
_is_in_torch_dispatch_mode = True
|
| 131 |
+
self.old_non_infra_dispatch_mode_flags.append(
|
| 132 |
+
_is_in_non_infra_torch_dispatch_mode
|
| 133 |
+
)
|
| 134 |
+
_is_in_non_infra_torch_dispatch_mode = (
|
| 135 |
+
_is_in_non_infra_torch_dispatch_mode or not self.is_infra_mode()
|
| 136 |
+
)
|
| 137 |
+
self.old_without_ignore_compile_internals_dispatch_mode_flags.append(
|
| 138 |
+
_is_in_any_mode_without_ignore_compile_internals
|
| 139 |
+
)
|
| 140 |
+
_is_in_any_mode_without_ignore_compile_internals = (
|
| 141 |
+
_is_in_any_mode_without_ignore_compile_internals
|
| 142 |
+
or not self.ignore_compile_internals()
|
| 143 |
+
)
|
| 144 |
+
set_is_in_mode_without_ignore_compile_internals(
|
| 145 |
+
_is_in_any_mode_without_ignore_compile_internals
|
| 146 |
+
)
|
| 147 |
+
_push_mode(self)
|
| 148 |
+
return self
|
| 149 |
+
|
| 150 |
+
def __exit__(self, exc_type, exc_val, exc_tb):
|
| 151 |
+
mb_dk_or_mode_key = self.__dict__.get("_dispatch_key", None)
|
| 152 |
+
if mb_dk_or_mode_key is None:
|
| 153 |
+
# Today, mode keys are not used at all in the per-dispatch-key-mode logic (for pre-dispatch)
|
| 154 |
+
# We should probably revisit this.
|
| 155 |
+
mb_dk_or_mode_key = self.__dict__.get("_mode_key", None)
|
| 156 |
+
global _is_in_torch_dispatch_mode
|
| 157 |
+
_is_in_torch_dispatch_mode = self.old_dispatch_mode_flags.pop()
|
| 158 |
+
global _is_in_non_infra_torch_dispatch_mode
|
| 159 |
+
_is_in_non_infra_torch_dispatch_mode = (
|
| 160 |
+
self.old_non_infra_dispatch_mode_flags.pop()
|
| 161 |
+
)
|
| 162 |
+
global _is_in_any_mode_without_ignore_compile_internals
|
| 163 |
+
_is_in_any_mode_without_ignore_compile_internals = (
|
| 164 |
+
self.old_without_ignore_compile_internals_dispatch_mode_flags.pop()
|
| 165 |
+
)
|
| 166 |
+
set_is_in_mode_without_ignore_compile_internals(
|
| 167 |
+
_is_in_any_mode_without_ignore_compile_internals
|
| 168 |
+
)
|
| 169 |
+
_pop_mode(mb_dk_or_mode_key)
|
| 170 |
+
|
| 171 |
+
@classmethod
|
| 172 |
+
def push(cls, *args, **kwargs):
|
| 173 |
+
warnings.warn(
|
| 174 |
+
"`Mode.push()` is no longer necessary and can be replaced with just `with Mode()`",
|
| 175 |
+
stacklevel=2,
|
| 176 |
+
)
|
| 177 |
+
instance = cls(*args, **kwargs)
|
| 178 |
+
return instance
|
| 179 |
+
|
| 180 |
+
@classmethod
|
| 181 |
+
def is_infra_mode(cls) -> bool:
|
| 182 |
+
return False
|
| 183 |
+
|
| 184 |
+
@classmethod
|
| 185 |
+
def ignore_compile_internals(cls) -> bool:
|
| 186 |
+
"""Ignore operators that are compiled via torch.compile.
|
| 187 |
+
|
| 188 |
+
If ``True``, then this TorchDispatchMode ignores operators that
|
| 189 |
+
are optimized by :func:`torch.compile`. Mechanically, this involves
|
| 190 |
+
turning off the TorchDispatchMode throughout the whole compilation process,
|
| 191 |
+
and turning it back on for the runtime of the compiled artifact(s).
|
| 192 |
+
For example,
|
| 193 |
+
|
| 194 |
+
@torch.compile
|
| 195 |
+
def f(x):
|
| 196 |
+
return x.sin().cos()
|
| 197 |
+
|
| 198 |
+
with LoggingMode():
|
| 199 |
+
f(x)
|
| 200 |
+
|
| 201 |
+
The above example will not log anything if
|
| 202 |
+
``LoggingMode.ignore_compile_internals()`` is True.
|
| 203 |
+
torch.compile will fuse sin() and cos() into a single operation
|
| 204 |
+
and this TorchDispatchMode will not be passed sin and cos.
|
| 205 |
+
|
| 206 |
+
If ``False`` (default), :func:`torch.compile` will respect
|
| 207 |
+
the eager semantics of passing this TorchDispatchMode all
|
| 208 |
+
operators that would have run during eager execution.
|
| 209 |
+
The way this will usually happen is that :func:`torch.compile`
|
| 210 |
+
will just fallback to eager-mode PyTorch.
|
| 211 |
+
"""
|
| 212 |
+
if cls.is_infra_mode():
|
| 213 |
+
return True
|
| 214 |
+
return False
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
def _get_current_dispatch_mode() -> TorchDispatchMode | None:
|
| 218 |
+
"""
|
| 219 |
+
Return the top user mode on the stack (the next one that would be
|
| 220 |
+
executed) if there are any.
|
| 221 |
+
"""
|
| 222 |
+
stack_len = _len_torch_dispatch_stack()
|
| 223 |
+
if stack_len > 0:
|
| 224 |
+
return _get_dispatch_stack_at(stack_len - 1)
|
| 225 |
+
return None
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
def _detect_infra_mode(key):
|
| 229 |
+
if key not in (
|
| 230 |
+
torch._C._TorchDispatchModeKey.FUNCTIONAL,
|
| 231 |
+
torch._C._TorchDispatchModeKey.PROXY,
|
| 232 |
+
):
|
| 233 |
+
raise AssertionError(
|
| 234 |
+
f"key must be either FUNCTIONAL ({torch._C._TorchDispatchModeKey.FUNCTIONAL}) \
|
| 235 |
+
or PROXY ({torch._C._TorchDispatchModeKey.PROXY}) _TorchDispatchModeKey, \
|
| 236 |
+
got {key}"
|
| 237 |
+
)
|
| 238 |
+
from torch._ops import _get_dispatch_mode_pre_dispatch
|
| 239 |
+
|
| 240 |
+
pre_dispatch_mode = _get_dispatch_mode_pre_dispatch(key)
|
| 241 |
+
post_dispatch_mode = torch._C._get_dispatch_mode(key)
|
| 242 |
+
|
| 243 |
+
if pre_dispatch_mode is not None and post_dispatch_mode is not None:
|
| 244 |
+
raise AssertionError(
|
| 245 |
+
"At most one of pre_dispatch_mode and post_dispatch_mode may be active"
|
| 246 |
+
)
|
| 247 |
+
|
| 248 |
+
if pre_dispatch_mode is None:
|
| 249 |
+
return post_dispatch_mode
|
| 250 |
+
|
| 251 |
+
return pre_dispatch_mode
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def _unset_infra_mode(key):
|
| 255 |
+
from torch._ops import _get_dispatch_mode_pre_dispatch, unset_mode_pre_dispatch
|
| 256 |
+
|
| 257 |
+
pre_dispatch_mode = _get_dispatch_mode_pre_dispatch(key)
|
| 258 |
+
post_dispatch_mode = torch._C._get_dispatch_mode(key)
|
| 259 |
+
if pre_dispatch_mode and post_dispatch_mode:
|
| 260 |
+
raise AssertionError(
|
| 261 |
+
"Can't have active infra mode on both pre and post dispatch mode stack"
|
| 262 |
+
)
|
| 263 |
+
|
| 264 |
+
if pre_dispatch_mode:
|
| 265 |
+
mode = unset_mode_pre_dispatch(key)
|
| 266 |
+
return mode
|
| 267 |
+
if post_dispatch_mode:
|
| 268 |
+
return torch._C._unset_dispatch_mode(key)
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
def _disable_infra_mode(key):
|
| 272 |
+
if key not in (
|
| 273 |
+
torch._C._TorchDispatchModeKey.FUNCTIONAL,
|
| 274 |
+
torch._C._TorchDispatchModeKey.PROXY,
|
| 275 |
+
):
|
| 276 |
+
raise AssertionError(
|
| 277 |
+
"key must be either FUNCTIONAL or PROXY _TorchDispatchModeKey"
|
| 278 |
+
)
|
| 279 |
+
mode_unset = _unset_infra_mode(key)
|
| 280 |
+
try:
|
| 281 |
+
yield mode_unset
|
| 282 |
+
finally:
|
| 283 |
+
if mode_unset is not None:
|
| 284 |
+
_push_mode(mode_unset)
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
def _get_current_dispatch_mode_stack() -> list[TorchDispatchMode]:
|
| 288 |
+
"""
|
| 289 |
+
Returns the current stack of dispatch modes, with the most recent
|
| 290 |
+
(i.e., the one that will be processed first) at the end of the
|
| 291 |
+
list (standard stack convention).
|
| 292 |
+
"""
|
| 293 |
+
stack_len = _len_torch_dispatch_stack()
|
| 294 |
+
return [_get_dispatch_stack_at(i) for i in range(stack_len)]
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
def _push_mode(mode: TorchDispatchMode) -> None:
|
| 298 |
+
k = mode._dispatch_key if hasattr(mode, "_dispatch_key") else None
|
| 299 |
+
if k is not None and k != torch._C.DispatchKey.PreDispatch:
|
| 300 |
+
raise AssertionError(
|
| 301 |
+
"mode._dispatch_key must be None or DispatchKey.PreDispatch"
|
| 302 |
+
)
|
| 303 |
+
if k is None:
|
| 304 |
+
_push_on_torch_dispatch_stack(mode)
|
| 305 |
+
return
|
| 306 |
+
|
| 307 |
+
from torch._ops import _set_mode_pre_dispatch, get_cached_ops
|
| 308 |
+
|
| 309 |
+
# See Note [Not Caching Per-Dispatch-Key Mode Handlers]
|
| 310 |
+
# Clear the cache of every op that has been used so far, for this particular key.
|
| 311 |
+
ks = torch._C._functionality_to_backend_keys(k)
|
| 312 |
+
for op in get_cached_ops():
|
| 313 |
+
for key in ks:
|
| 314 |
+
op._uncache_dispatch(key)
|
| 315 |
+
_set_mode_pre_dispatch(mode)
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
def _pop_mode(k: DispatchKey | torch._C._TorchDispatchModeKey | None = None):
|
| 319 |
+
if k == torch._C.DispatchKey.PreDispatch: # type: ignore[attr-defined]
|
| 320 |
+
from torch._ops import _pop_mode_from_pre_dispatch
|
| 321 |
+
|
| 322 |
+
return _pop_mode_from_pre_dispatch()
|
| 323 |
+
|
| 324 |
+
if k is None or isinstance(k, torch._C._TorchDispatchModeKey):
|
| 325 |
+
return _pop_torch_dispatch_stack(k)
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
@contextlib.contextmanager
|
| 329 |
+
def _pop_mode_temporarily(k: DispatchKey | None = None):
|
| 330 |
+
old = _pop_mode(k)
|
| 331 |
+
try:
|
| 332 |
+
yield old
|
| 333 |
+
finally:
|
| 334 |
+
_push_mode(old)
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
@contextlib.contextmanager
|
| 338 |
+
def _disable_current_modes():
|
| 339 |
+
from torch._ops import (
|
| 340 |
+
_len_torch_dispatch_stack_pre_dispatch,
|
| 341 |
+
_pop_mode_from_pre_dispatch,
|
| 342 |
+
)
|
| 343 |
+
from torch._subclasses.functional_tensor import FunctionalTensorMode
|
| 344 |
+
from torch._subclasses.schema_check_mode import SchemaCheckMode
|
| 345 |
+
from torch.fx.experimental.proxy_tensor import ProxyTorchDispatchMode
|
| 346 |
+
|
| 347 |
+
mode_len_pre_dispatch = _len_torch_dispatch_stack_pre_dispatch()
|
| 348 |
+
old_pre_dispatch_modes = [
|
| 349 |
+
_pop_mode_from_pre_dispatch() for _ in range(mode_len_pre_dispatch)
|
| 350 |
+
]
|
| 351 |
+
|
| 352 |
+
has_proxy_mode_in_pre_dispatch = False
|
| 353 |
+
has_functional_mode_in_pre_dispatch = False
|
| 354 |
+
has_schema_check_mode_in_pre_dispatch = False
|
| 355 |
+
|
| 356 |
+
for i in old_pre_dispatch_modes:
|
| 357 |
+
if isinstance(i, ProxyTorchDispatchMode):
|
| 358 |
+
has_proxy_mode_in_pre_dispatch = True
|
| 359 |
+
if isinstance(i, FunctionalTensorMode):
|
| 360 |
+
has_functional_mode_in_pre_dispatch = True
|
| 361 |
+
if isinstance(i, SchemaCheckMode):
|
| 362 |
+
has_schema_check_mode_in_pre_dispatch = True
|
| 363 |
+
|
| 364 |
+
mode_len = _len_torch_dispatch_stack()
|
| 365 |
+
old_modes = [_pop_mode() for _ in range(mode_len)]
|
| 366 |
+
|
| 367 |
+
for old in old_modes:
|
| 368 |
+
if (
|
| 369 |
+
isinstance(old, FunctionalTensorMode)
|
| 370 |
+
and has_functional_mode_in_pre_dispatch
|
| 371 |
+
):
|
| 372 |
+
raise AssertionError(
|
| 373 |
+
"Can't have FunctionalMode available both in PreDispatch and Python Key"
|
| 374 |
+
)
|
| 375 |
+
if isinstance(old, ProxyTorchDispatchMode) and has_proxy_mode_in_pre_dispatch:
|
| 376 |
+
raise AssertionError(
|
| 377 |
+
"Can't have ProxyTorchDispatchMode available both in PreDispatch and Python Key"
|
| 378 |
+
)
|
| 379 |
+
if isinstance(old, SchemaCheckMode) and has_schema_check_mode_in_pre_dispatch:
|
| 380 |
+
raise AssertionError(
|
| 381 |
+
"Can't have SchemaCheckMode available both in PreDispatch and Python Key"
|
| 382 |
+
)
|
| 383 |
+
|
| 384 |
+
# Manually disable proxy and fake modes, if any are active
|
| 385 |
+
try:
|
| 386 |
+
yield old_pre_dispatch_modes + old_modes
|
| 387 |
+
finally:
|
| 388 |
+
for mode in reversed(old_modes):
|
| 389 |
+
_push_mode(mode)
|
| 390 |
+
for mode in reversed(old_pre_dispatch_modes):
|
| 391 |
+
_push_mode(mode)
|
| 392 |
+
|
| 393 |
+
|
| 394 |
+
class BaseTorchDispatchMode(TorchDispatchMode):
|
| 395 |
+
def __torch_dispatch__(self, func, types, args=(), kwargs=None):
|
| 396 |
+
if kwargs is None:
|
| 397 |
+
kwargs = {}
|
| 398 |
+
return func(*args, **kwargs)
|
| 399 |
+
|
| 400 |
+
|
| 401 |
+
# Subtypes which have __tensor_flatten__ and __tensor_unflatten__.
|
| 402 |
+
class TensorWithFlatten(Protocol):
|
| 403 |
+
def __tensor_flatten__(self) -> tuple[Sequence[str], object]: ...
|
| 404 |
+
|
| 405 |
+
@staticmethod
|
| 406 |
+
def __tensor_unflatten__(
|
| 407 |
+
inner_tensors: int, flatten_spec: int, outer_size: int, outer_stride: int
|
| 408 |
+
) -> torch.Tensor: ...
|
| 409 |
+
|
| 410 |
+
# It would be really nice to be able to say that the return of
|
| 411 |
+
# is_traceable_wrapper_subclass() is Intersection[torch.Tensor,
|
| 412 |
+
# TensorWithFlatten] - but that doesn't exist.
|
| 413 |
+
|
| 414 |
+
shape: torch._C.Size
|
| 415 |
+
|
| 416 |
+
@overload
|
| 417 |
+
def stride(self, dim: None = None) -> tuple[int, ...]: ...
|
| 418 |
+
|
| 419 |
+
@overload
|
| 420 |
+
def stride(self, dim: int) -> int: ...
|
| 421 |
+
|
| 422 |
+
@overload
|
| 423 |
+
def size(self, dim: None = None) -> tuple[int, ...]: ...
|
| 424 |
+
|
| 425 |
+
@overload
|
| 426 |
+
def size(self, dim: int) -> int: ...
|
| 427 |
+
|
| 428 |
+
def storage_offset(self) -> int: ...
|
| 429 |
+
|
| 430 |
+
def dim(self) -> int: ...
|
| 431 |
+
|
| 432 |
+
@overload
|
| 433 |
+
def to(
|
| 434 |
+
self,
|
| 435 |
+
dtype: torch.types._dtype,
|
| 436 |
+
non_blocking: bool = False,
|
| 437 |
+
copy: bool = False,
|
| 438 |
+
*,
|
| 439 |
+
memory_format: torch.memory_format | None = None,
|
| 440 |
+
) -> torch.Tensor: ...
|
| 441 |
+
|
| 442 |
+
@overload
|
| 443 |
+
def to(
|
| 444 |
+
self,
|
| 445 |
+
device: torch._prims_common.DeviceLikeType | None = None,
|
| 446 |
+
dtype: torch.types._dtype | None = None,
|
| 447 |
+
non_blocking: bool = False,
|
| 448 |
+
copy: bool = False,
|
| 449 |
+
*,
|
| 450 |
+
memory_format: torch.memory_format | None = None,
|
| 451 |
+
) -> torch.Tensor: ...
|
| 452 |
+
|
| 453 |
+
@overload
|
| 454 |
+
def to(
|
| 455 |
+
self,
|
| 456 |
+
other: torch.Tensor,
|
| 457 |
+
non_blocking: bool = False,
|
| 458 |
+
copy: bool = False,
|
| 459 |
+
*,
|
| 460 |
+
memory_format: torch.memory_format | None = None,
|
| 461 |
+
) -> torch.Tensor: ...
|
| 462 |
+
|
| 463 |
+
|
| 464 |
+
def is_traceable_wrapper_subclass(t: object) -> TypeIs[TensorWithFlatten]:
|
| 465 |
+
"""
|
| 466 |
+
Returns whether or not a tensor subclass that implements __torch_dispatch__
|
| 467 |
+
is 'traceable' with torch.compile.
|
| 468 |
+
In order for a tensor subclass to support TorchDispatchMode-style tracing in PT2,
|
| 469 |
+
It must implement two magic methods: __tensor_flatten__ and __tensor_unflatten__.
|
| 470 |
+
It is also expected to obey some restrictions around traceability and aliasing:
|
| 471 |
+
* The subclass's __torch_dispatch__() implementation should desugar into pytorch
|
| 472 |
+
dispatcher operations that can be traced into a graph.
|
| 473 |
+
* The subclass should use return_and_correct_aliasing(). This is needed today to make
|
| 474 |
+
sure that torch.compile does the right thing in a few cases around input mutation
|
| 475 |
+
and output aliasing.
|
| 476 |
+
|
| 477 |
+
Expected magic method signatures:
|
| 478 |
+
attrs, ctx = t.__tensor_flatten__()
|
| 479 |
+
attrs: list of attribute name strings for inner tensors
|
| 480 |
+
ctx: dict containing any other subclass-specific metadata needed for unflattening
|
| 481 |
+
|
| 482 |
+
t = MySubClass.__tensor_unflatten__(inner_tensors, ctx, outer_size, outer_stride)
|
| 483 |
+
inner_tensors: dict mapping attribute name -> tensor for each inner tensor
|
| 484 |
+
ctx: dict with subclass metadata in the form that __tensor_flatten__() produces
|
| 485 |
+
outer_size: expected (possibly symbolic) size that the returned subclass
|
| 486 |
+
instance should have. Note that this arg is useful for certain subclasses
|
| 487 |
+
that require the shape info to be constructed. In most cases, this arg can be
|
| 488 |
+
safely ignored.
|
| 489 |
+
outer_stride: expected (possibly symbolic) stride that the returned subclass
|
| 490 |
+
instance should have. Note that this arg is useful for certain subclasses
|
| 491 |
+
that require the stride info to be constructed. In most cases, this arg can be
|
| 492 |
+
safely ignored.
|
| 493 |
+
"""
|
| 494 |
+
is_subclass = isinstance(t, torch.Tensor) and type(t) is not torch.Tensor
|
| 495 |
+
return (
|
| 496 |
+
is_subclass
|
| 497 |
+
and hasattr(t, "__tensor_flatten__")
|
| 498 |
+
and hasattr(t, "__tensor_unflatten__")
|
| 499 |
+
)
|
| 500 |
+
|
| 501 |
+
|
| 502 |
+
def is_traceable_wrapper_subclass_type(t: type) -> TypeIs[type[TensorWithFlatten]]:
|
| 503 |
+
"""Same as above, but takes a type argument instead of an instance."""
|
| 504 |
+
return (
|
| 505 |
+
issubclass(t, torch.Tensor)
|
| 506 |
+
and t is not torch.Tensor
|
| 507 |
+
and hasattr(t, "__tensor_flatten__")
|
| 508 |
+
and hasattr(t, "__tensor_unflatten__")
|
| 509 |
+
)
|
| 510 |
+
|
| 511 |
+
|
| 512 |
+
def transform_subclass(t, callback, outer_size=None, outer_stride=None):
|
| 513 |
+
"""
|
| 514 |
+
Given a traceable, wrapper tensor subclass ``t`` that implements
|
| 515 |
+
``__torch_dispatch__`` and holds some inner tensors,
|
| 516 |
+
and a callback of type ``Callable[[str, torch.Tensor], torch.Tensor]``,
|
| 517 |
+
`transform_subclass` will construct a fresh instance of the wrapper tensor subclass.
|
| 518 |
+
It will do so by grabbing each inner tensor attribute from the wrapper,
|
| 519 |
+
passing them into ``callback`` to get a transformed tensor,
|
| 520 |
+
and putting each transformed tensor into the fresh tensor subclass instance.
|
| 521 |
+
|
| 522 |
+
Note: this function will not handle ensuring that the fresh subclass
|
| 523 |
+
gets the same (autograd, and aliasing) metadata as the original tensor.
|
| 524 |
+
This is generally handled in other subsystems like AOTAutograd.
|
| 525 |
+
"""
|
| 526 |
+
outer_size = outer_size if outer_size is not None else t.size()
|
| 527 |
+
outer_stride = outer_stride if outer_stride is not None else t.stride()
|
| 528 |
+
|
| 529 |
+
attrs, ctx = t.__tensor_flatten__()
|
| 530 |
+
transformed_tensors_dict = {}
|
| 531 |
+
for attr in attrs:
|
| 532 |
+
transformed_tensors_dict[attr] = callback(attr, getattr(t, attr))
|
| 533 |
+
sub = type(t).__tensor_unflatten__(
|
| 534 |
+
transformed_tensors_dict, ctx, outer_size, outer_stride
|
| 535 |
+
)
|
| 536 |
+
|
| 537 |
+
# NB: Purposefully guard here to simplify the inner / outer symbols.
|
| 538 |
+
# Using sym_eq() for symbolic comparison can result in an expression that's too
|
| 539 |
+
# difficult to guard on, so we use == here.
|
| 540 |
+
if sub.shape != outer_size:
|
| 541 |
+
raise AssertionError(
|
| 542 |
+
f"Expected return value from {type(t)}__tensor_unflatten__() to have "
|
| 543 |
+
f"shape equal to {outer_size}, but got: {sub.shape}"
|
| 544 |
+
)
|
| 545 |
+
if sub.stride() != outer_stride:
|
| 546 |
+
raise AssertionError(
|
| 547 |
+
f"Expected return value from {type(t)}__tensor_unflatten__() to have "
|
| 548 |
+
f"stride equal to {outer_stride}, but got: {sub.stride()}"
|
| 549 |
+
)
|
| 550 |
+
|
| 551 |
+
return sub
|
| 552 |
+
|
| 553 |
+
|
| 554 |
+
def _correct_storage_aliasing(func, schema_info, args, outs) -> None:
|
| 555 |
+
"""
|
| 556 |
+
Given: an OpOverload, a SchemaInfo (cached information from torchgen about schema),
|
| 557 |
+
and the inputs/outputs to the OpOverload,
|
| 558 |
+
this function checks to see if func is a view operator
|
| 559 |
+
(by checking if any of the outputs in the op's schema
|
| 560 |
+
are immutable aliases of inputs).
|
| 561 |
+
If so, this function manually aliases the storage of the output tensor
|
| 562 |
+
with its corresponding input tensor alias.
|
| 563 |
+
It does this by unsafely overwriting the storage field of the output tensor
|
| 564 |
+
to be the same storage as the input.
|
| 565 |
+
"""
|
| 566 |
+
if not isinstance(func, torch._ops.OpOverload):
|
| 567 |
+
raise AssertionError(f"func must be an OpOverload, got {type(args)}")
|
| 568 |
+
if not isinstance(args, tuple):
|
| 569 |
+
raise AssertionError(f"args must be a tuple, got {type(args)}")
|
| 570 |
+
if not isinstance(outs, (list, tuple)):
|
| 571 |
+
raise AssertionError(f"outs must be a list or tuple, got {type(args)}")
|
| 572 |
+
|
| 573 |
+
def alias_non_inplace_storage(arg, ret) -> None:
|
| 574 |
+
# This is hopefully a reasonable assert:
|
| 575 |
+
# subclasses that rely on this API for output aliasing
|
| 576 |
+
# should always return wrapper tensor subclasses for us to manually alias.
|
| 577 |
+
# in theory if a subclass that needs this API wants to sometimes return
|
| 578 |
+
# plain tensors, we could remove the assert and just not perform the aliasing,
|
| 579 |
+
# but it seems safer to learn more about this case first.
|
| 580 |
+
#
|
| 581 |
+
# Performance note: This is all just to assert that the argument and result
|
| 582 |
+
# types match, checking that is cheaper than is_traceable_wrapper_subclass_type,
|
| 583 |
+
# and multiple returns are relatively unlikely, so just check up front!
|
| 584 |
+
arg_type = type(arg)
|
| 585 |
+
ret_type = type(ret)
|
| 586 |
+
if arg_type is not ret_type and (
|
| 587 |
+
is_traceable_wrapper_subclass_type(arg_type)
|
| 588 |
+
or is_traceable_wrapper_subclass_type(ret_type)
|
| 589 |
+
):
|
| 590 |
+
ret_list = ret if isinstance(ret, list) else [ret]
|
| 591 |
+
for r in ret_list:
|
| 592 |
+
if type(arg) is not type(r):
|
| 593 |
+
raise AssertionError(
|
| 594 |
+
f"Called {str(func)} with input of type {type(arg)}\n"
|
| 595 |
+
f"and output of type {type(ret)}. But expected types to match."
|
| 596 |
+
)
|
| 597 |
+
# Need to call a non-dispatcher helper, because we explicitly do **not**
|
| 598 |
+
# want our subclass to intercept the set_() call.
|
| 599 |
+
# instead, our subclass should directly have its storage swapped out.
|
| 600 |
+
# we **explicitly** don't want to reset the sizes on ret, if the storage implies a size change.
|
| 601 |
+
# Why?
|
| 602 |
+
# The purpose of this API is *not* to change the size/strides of our output- we assume it's already correct.
|
| 603 |
+
# We just want to "fix up" the storage aliasing, without modifying or output's metadata.
|
| 604 |
+
# Example: out = inp.expand(inp.shape[0], inp.shape[0])
|
| 605 |
+
# This requires swapping the storage of out to be the same as inp,
|
| 606 |
+
# but we do *not* want it to change the sizes/strides that were compute for out.
|
| 607 |
+
|
| 608 |
+
if isinstance(ret, list):
|
| 609 |
+
for r in ret:
|
| 610 |
+
torch._functionalize_unsafe_set(r, arg)
|
| 611 |
+
else:
|
| 612 |
+
if not isinstance(ret, torch.Tensor):
|
| 613 |
+
raise AssertionError(f"expected torch.Tensor, got {type(ret)}")
|
| 614 |
+
torch._functionalize_unsafe_set(ret, arg)
|
| 615 |
+
|
| 616 |
+
for arg_idx, return_idx in schema_info.read_only_alias_match_indexes:
|
| 617 |
+
alias_non_inplace_storage(args[arg_idx], outs[return_idx])
|
| 618 |
+
|
| 619 |
+
|
| 620 |
+
def _get_write_alias(x) -> str | None:
|
| 621 |
+
alias_set = x.alias_set
|
| 622 |
+
if not alias_set or not x.is_write:
|
| 623 |
+
return None
|
| 624 |
+
# torchscript allows for complicated alias sets, but our dispatcher ops only really involve simple aliasing
|
| 625 |
+
if len(alias_set) != 1:
|
| 626 |
+
raise AssertionError("Expected alias_set to contain exactly one element")
|
| 627 |
+
# timeit says next(iter(alias_set)) is faster than list(alias_set)[0] even for
|
| 628 |
+
# set of size 1 on Python 3.13.
|
| 629 |
+
return next(iter(alias_set))
|
| 630 |
+
|
| 631 |
+
|
| 632 |
+
# This abstracts over the fact that in return_and_correct_aliasing,
|
| 633 |
+
# we sometimes use torchgen schema parsing (for aten ops, since torchscript's schema parsing is sometimes buggy),
|
| 634 |
+
# and sometimes use torchscript schema parsing (for custom ops, for which torchgen parsing is untested).
|
| 635 |
+
@dataclass
|
| 636 |
+
class AliasInfo:
|
| 637 |
+
alias_set: set[str]
|
| 638 |
+
is_write: bool
|
| 639 |
+
name: str | None
|
| 640 |
+
|
| 641 |
+
|
| 642 |
+
@dataclass
|
| 643 |
+
class SchemaInfo:
|
| 644 |
+
args: list[AliasInfo]
|
| 645 |
+
outs: list[AliasInfo]
|
| 646 |
+
|
| 647 |
+
is_inplace_view_op: bool
|
| 648 |
+
|
| 649 |
+
# [_get_write_alias(x) for x in outs]. Guaranteed to contain no Nones; we coerce
|
| 650 |
+
# all-Nones result to empty list instead, and we don't support
|
| 651 |
+
# some-but-not-all-Nones.
|
| 652 |
+
outs_write_aliases: list[str] | None
|
| 653 |
+
|
| 654 |
+
# List of (arg_idx, return_idx) where args[arg_idx].alias_set &
|
| 655 |
+
# outs[out_idx].alias_set is not empty, and not args[arg_idx].is_write.
|
| 656 |
+
read_only_alias_match_indexes: list[tuple[int, int]]
|
| 657 |
+
|
| 658 |
+
|
| 659 |
+
# Given an OpOverload, returns schema information on it.
|
| 660 |
+
# This is cached for efficiency, since it can involve running torchgen
|
| 661 |
+
@functools.cache
|
| 662 |
+
def get_alias_info(func) -> SchemaInfo:
|
| 663 |
+
# For ATen ops: use torchgen (since torchscript parser doesn't handle alias annotations
|
| 664 |
+
# properly for some ops that output tensorlists)
|
| 665 |
+
if func.namespace == "aten":
|
| 666 |
+
torchgen_schema_str = str(func._schema)
|
| 667 |
+
if not torchgen_schema_str.startswith("aten::"):
|
| 668 |
+
raise AssertionError(
|
| 669 |
+
"Expected torchgen schema string to start with 'aten::'"
|
| 670 |
+
)
|
| 671 |
+
# remove the aten:: namespace, which is added by the torchscript parser,
|
| 672 |
+
# and torchgen doesn't know how to handle
|
| 673 |
+
torchgen_schema_str = torchgen_schema_str[6:]
|
| 674 |
+
import re
|
| 675 |
+
|
| 676 |
+
# the torchscript parser ends up converting int[2]=1 into int[2]=[1, 1],
|
| 677 |
+
# which torchgen chokes on.
|
| 678 |
+
torchgen_schema_str = re.sub(r"=\[[0, ]+\]", "=0", torchgen_schema_str)
|
| 679 |
+
torchgen_schema_str = re.sub(r"=\[[1, ]+\]", "=1", torchgen_schema_str)
|
| 680 |
+
# for aten::rot90 / aten:fft_*
|
| 681 |
+
torchgen_schema_str = re.sub(
|
| 682 |
+
r"=\[(-?[0-9]+), (-?[0-9]+)\]", r"=[\1,\2]", torchgen_schema_str
|
| 683 |
+
)
|
| 684 |
+
torchgen_schema = torchgen.model.FunctionSchema.parse(torchgen_schema_str)
|
| 685 |
+
arg_schemas = [
|
| 686 |
+
AliasInfo(
|
| 687 |
+
alias_set=(
|
| 688 |
+
set() if a.annotation is None else set(a.annotation.alias_set)
|
| 689 |
+
),
|
| 690 |
+
is_write=a.annotation is not None and a.annotation.is_write,
|
| 691 |
+
name=a.name,
|
| 692 |
+
)
|
| 693 |
+
for a in torchgen_schema.arguments.flat_all
|
| 694 |
+
]
|
| 695 |
+
out_schemas = [
|
| 696 |
+
AliasInfo(
|
| 697 |
+
alias_set=(
|
| 698 |
+
set() if a.annotation is None else set(a.annotation.alias_set)
|
| 699 |
+
),
|
| 700 |
+
is_write=a.annotation is not None and a.annotation.is_write,
|
| 701 |
+
name=a.name,
|
| 702 |
+
)
|
| 703 |
+
for a in torchgen_schema.returns
|
| 704 |
+
]
|
| 705 |
+
else:
|
| 706 |
+
# For non-aten ops, torchgen is untested so we rely on torchscript schema parsing
|
| 707 |
+
arg_schemas = [
|
| 708 |
+
AliasInfo(
|
| 709 |
+
alias_set=(
|
| 710 |
+
set() if a.alias_info is None else set(a.alias_info.before_set)
|
| 711 |
+
),
|
| 712 |
+
is_write=a.alias_info is not None and a.alias_info.is_write,
|
| 713 |
+
name=a.name,
|
| 714 |
+
)
|
| 715 |
+
for a in func._schema.arguments
|
| 716 |
+
]
|
| 717 |
+
out_schemas = [
|
| 718 |
+
AliasInfo(
|
| 719 |
+
alias_set=(
|
| 720 |
+
set() if a.alias_info is None else set(a.alias_info.before_set)
|
| 721 |
+
),
|
| 722 |
+
is_write=a.alias_info is not None and a.alias_info.is_write,
|
| 723 |
+
name=a.name,
|
| 724 |
+
)
|
| 725 |
+
for a in func._schema.returns
|
| 726 |
+
]
|
| 727 |
+
read_only_alias_match_indexes = []
|
| 728 |
+
for arg_idx, schema_arg in enumerate(arg_schemas):
|
| 729 |
+
for return_idx, schema_out in enumerate(out_schemas):
|
| 730 |
+
is_read_only_alias_match = (
|
| 731 |
+
schema_arg.alias_set & schema_out.alias_set
|
| 732 |
+
) and not schema_arg.is_write
|
| 733 |
+
if is_read_only_alias_match:
|
| 734 |
+
read_only_alias_match_indexes.append((arg_idx, return_idx))
|
| 735 |
+
|
| 736 |
+
outs_write_aliases_list: list[str | None] = [
|
| 737 |
+
_get_write_alias(r) for r in out_schemas
|
| 738 |
+
]
|
| 739 |
+
non_nones = sum(x is not None for x in outs_write_aliases_list)
|
| 740 |
+
if non_nones == 0:
|
| 741 |
+
outs_write_aliases: list[str] | None = None
|
| 742 |
+
elif non_nones != len(outs_write_aliases_list):
|
| 743 |
+
# simplifying assumption: we don't have **any** ops with return types like "-> (Tensor(a!), Tensor)"
|
| 744 |
+
raise RuntimeError("Unsupported schema: " + str(func._schema))
|
| 745 |
+
else:
|
| 746 |
+
outs_write_aliases = cast(list[str], outs_write_aliases_list)
|
| 747 |
+
|
| 748 |
+
schema_info = SchemaInfo(
|
| 749 |
+
args=arg_schemas,
|
| 750 |
+
outs=out_schemas,
|
| 751 |
+
# This check is surprisingly expensive because pybind11 enum_s are
|
| 752 |
+
# inefficient. Just cache it.
|
| 753 |
+
is_inplace_view_op=torch.Tag.inplace_view in func.tags,
|
| 754 |
+
outs_write_aliases=outs_write_aliases,
|
| 755 |
+
read_only_alias_match_indexes=read_only_alias_match_indexes,
|
| 756 |
+
)
|
| 757 |
+
return schema_info
|
| 758 |
+
|
| 759 |
+
|
| 760 |
+
def autograd_would_have_decomposed(
|
| 761 |
+
func: torch._ops.OpOverload, flat_args: Sequence[torch.Tensor | object]
|
| 762 |
+
) -> bool:
|
| 763 |
+
"""
|
| 764 |
+
Suppose that an operator has CompositeImplicitAutograd decomp registered.
|
| 765 |
+
Would autograd have used this decomposition? It will only use it if there
|
| 766 |
+
isn't an explicit backend registration for the device as well. This function
|
| 767 |
+
will tell if this would have occurred.
|
| 768 |
+
|
| 769 |
+
Why do we need to apply these decompositions later? When inference mode is
|
| 770 |
+
on, the autograd key is bypassed entirely, so a lower level mode cannot rely
|
| 771 |
+
on the decomposition have been applied. It's easy to accidentally never apply
|
| 772 |
+
the decomposition, resulting in an operator showing up in a graph that
|
| 773 |
+
is unexpected.
|
| 774 |
+
|
| 775 |
+
Why do we need to AVOID applying the decomposition when autograd wouldn't
|
| 776 |
+
have decomposed? If autograd doesn't decompose, this means in eager mode
|
| 777 |
+
we would have run the fused kernel. It must be possible to trace this
|
| 778 |
+
fused kernel directly into the graph for fidelity with eager (NB: a user
|
| 779 |
+
has the option of then further decomposing at proxy tensor mode via
|
| 780 |
+
decomposition table, but we must preserve it to proxy mode to have the
|
| 781 |
+
choice.)
|
| 782 |
+
|
| 783 |
+
Why does functionalization need to also perform the test here? This is
|
| 784 |
+
because some CompositeImplicitAutograd decompositions are not functional.
|
| 785 |
+
If we are eventually going to decompose, we need to do this while we can
|
| 786 |
+
still turn functionalization back on, so those decompositions get functionalized.
|
| 787 |
+
So an early decomposition in functionalization may still be necessary. Note that
|
| 788 |
+
if proxy tensor decomposition process could turn functionalization back on, this
|
| 789 |
+
wouldn't be necessary, and maybe that is a useful thing to do anyway because
|
| 790 |
+
the decomposition table is user specified and a user could violate the functional
|
| 791 |
+
decomp requirement with a bad decomp. If this happened, then you could always
|
| 792 |
+
pass through functionalization.
|
| 793 |
+
"""
|
| 794 |
+
has_backend_registration = False
|
| 795 |
+
for a in flat_args:
|
| 796 |
+
if isinstance(a, torch.Tensor):
|
| 797 |
+
backend_key = torch._C._parse_dispatch_key(
|
| 798 |
+
torch._C._dispatch_key_for_device(a.device.type)
|
| 799 |
+
)
|
| 800 |
+
assert backend_key is not None
|
| 801 |
+
# TODO: use func.has_kernel_for_dispatch_key(backend_key)
|
| 802 |
+
# but this one checks py_impl and CompositeImplicitAutograd
|
| 803 |
+
# incorrectly shows up as has backend reg here
|
| 804 |
+
has_backend_registration = torch._C._dispatch_has_kernel_for_dispatch_key(
|
| 805 |
+
func.name(), backend_key
|
| 806 |
+
)
|
| 807 |
+
|
| 808 |
+
# in theory we should take all backend keys and take the highest priority one
|
| 809 |
+
# to properly mimic the dispatcher,
|
| 810 |
+
# this just grabs the first tensor and takes its device key
|
| 811 |
+
break
|
| 812 |
+
return not has_backend_registration
|
| 813 |
+
|
| 814 |
+
|
| 815 |
+
def return_and_correct_aliasing(func, args, kwargs, out):
|
| 816 |
+
"""
|
| 817 |
+
This function should be used by wrapper tensor ``__torch_dispatch__`` subclasses
|
| 818 |
+
that would like to work with torch.compile. It ensures that the subclass
|
| 819 |
+
properly implements the aliasing behavior of every op,
|
| 820 |
+
which is needed for correctness in AOTAutograd.
|
| 821 |
+
This function will handle:
|
| 822 |
+
|
| 823 |
+
* When we see a view op, we will alias the storages of any
|
| 824 |
+
input and output tensor subclasses
|
| 825 |
+
|
| 826 |
+
* When we see an inplace or out= op, we will directly
|
| 827 |
+
return the corresponding input tensor, instead of returning
|
| 828 |
+
a (potentially) fresh output tensor.
|
| 829 |
+
"""
|
| 830 |
+
|
| 831 |
+
# Caching here because torchgen parsing is definitely not fast, and this function is called
|
| 832 |
+
# once for every op in the graph during functionalization.
|
| 833 |
+
schema_info = get_alias_info(func)
|
| 834 |
+
|
| 835 |
+
def get_arg_from_alias(output_alias, schema_info, args, kwargs):
|
| 836 |
+
new_args, new_kwargs = torch.fx.operator_schemas.normalize_function( # type: ignore[misc]
|
| 837 |
+
func, args=args, kwargs=kwargs
|
| 838 |
+
)
|
| 839 |
+
|
| 840 |
+
arg_indices = [
|
| 841 |
+
i for i, a in enumerate(schema_info.args) if output_alias in a.alias_set
|
| 842 |
+
]
|
| 843 |
+
# For any dispatcher op with an output alias, we expect it to map to exactly one alias in the schema's input arguments.
|
| 844 |
+
if len(arg_indices) != 1:
|
| 845 |
+
raise AssertionError(
|
| 846 |
+
"Expected exactly one argument index for the given output alias"
|
| 847 |
+
)
|
| 848 |
+
idx = arg_indices[0]
|
| 849 |
+
arg_info = schema_info.args[idx]
|
| 850 |
+
if arg_info.name is not None and arg_info.name in new_kwargs:
|
| 851 |
+
return new_kwargs[arg_info.name]
|
| 852 |
+
return new_args[idx]
|
| 853 |
+
|
| 854 |
+
# Fix up the storages of any outs so that they point to the same storage as the input,
|
| 855 |
+
# if func is a view op.
|
| 856 |
+
_correct_storage_aliasing(
|
| 857 |
+
func, schema_info, args, (out,) if not isinstance(out, tuple) else out
|
| 858 |
+
)
|
| 859 |
+
|
| 860 |
+
# For inplace_view ops in particular, we'll try hard to make sure that the wrapper subclass's
|
| 861 |
+
# metadata is set correctly.
|
| 862 |
+
if schema_info.is_inplace_view_op:
|
| 863 |
+
# no_dispatch() to make sure that we secretly change the metadata on the wrapper,
|
| 864 |
+
# but don't end up dispatching the op anywhere else.
|
| 865 |
+
mutated_args = [
|
| 866 |
+
x
|
| 867 |
+
for i, x in enumerate(args)
|
| 868 |
+
if _get_write_alias(schema_info.args[i]) is not None
|
| 869 |
+
]
|
| 870 |
+
# Assumption: we have a very small number of inplace_view ops that follow a strict schema:
|
| 871 |
+
# there is only a single argument that gets its metadata mutated.
|
| 872 |
+
if len(mutated_args) != 1:
|
| 873 |
+
raise AssertionError(
|
| 874 |
+
"expected exactly one mutated arg for inplace_view ops"
|
| 875 |
+
)
|
| 876 |
+
# This check exists because we generally *do* want to update the metadata of any wrapper subclasses,
|
| 877 |
+
# but FunctionalTensor is special: it overrides all size/stride calls to plumb to the inner tensor.
|
| 878 |
+
# so we don't actually need to update the metadata (and attempting to do so causes errors)
|
| 879 |
+
from torch._subclasses.functional_tensor import FunctionalTensor
|
| 880 |
+
|
| 881 |
+
if not isinstance(mutated_args[0], FunctionalTensor):
|
| 882 |
+
with torch.utils._mode_utils.no_dispatch():
|
| 883 |
+
# See Note: [Fake Tensor Dispatch Keys]
|
| 884 |
+
# we're borrowing the way it modifies dispatch key TLS.
|
| 885 |
+
meta_in_tls = torch._C._meta_in_tls_dispatch_include()
|
| 886 |
+
torch._C._set_meta_in_tls_dispatch_include(True)
|
| 887 |
+
try:
|
| 888 |
+
func(*args, **kwargs)
|
| 889 |
+
finally:
|
| 890 |
+
torch._C._set_meta_in_tls_dispatch_include(meta_in_tls)
|
| 891 |
+
|
| 892 |
+
# Next: we need to make sure to return inputs directly, if the output is a mutable alias (e.g. add_()).
|
| 893 |
+
|
| 894 |
+
schema_info_outs_write_aliases = schema_info.outs_write_aliases
|
| 895 |
+
# simple case: none of our outputs have mutable aliases, so we can return the output as-is
|
| 896 |
+
if schema_info_outs_write_aliases is None:
|
| 897 |
+
return out
|
| 898 |
+
|
| 899 |
+
if len(schema_info_outs_write_aliases) == 1:
|
| 900 |
+
return get_arg_from_alias(
|
| 901 |
+
schema_info_outs_write_aliases[0], schema_info, args, kwargs
|
| 902 |
+
)
|
| 903 |
+
|
| 904 |
+
# In the multi-return case, all aten ops return a tuple / list, so cast accordingly.
|
| 905 |
+
outs_to_return = type(out)(
|
| 906 |
+
[
|
| 907 |
+
(get_arg_from_alias(write_alias, schema_info, args, kwargs))
|
| 908 |
+
for write_alias in schema_info_outs_write_aliases
|
| 909 |
+
]
|
| 910 |
+
)
|
| 911 |
+
return outs_to_return
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/_pytree.py
ADDED
|
@@ -0,0 +1,2216 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Contains utility functions for working with nested python data structures.
|
| 3 |
+
|
| 4 |
+
A *pytree* is Python nested data structure. It is a tree in the sense that
|
| 5 |
+
nodes are Python collections (e.g., list, tuple, dict) and the leaves are
|
| 6 |
+
Python values. Furthermore, a pytree should not contain reference cycles.
|
| 7 |
+
|
| 8 |
+
pytrees are useful for working with nested collections of Tensors. For example,
|
| 9 |
+
one can use `tree_map` to map a function over all Tensors inside some nested
|
| 10 |
+
collection of Tensors and `tree_leaves` to get a flat list of all Tensors
|
| 11 |
+
inside some nested collection. pytrees are helpful for implementing nested
|
| 12 |
+
collection support for PyTorch APIs.
|
| 13 |
+
|
| 14 |
+
This pytree implementation is not very performant due to Python overhead
|
| 15 |
+
To improve the performance we can move parts of the implementation to C++.
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
import dataclasses
|
| 19 |
+
import functools
|
| 20 |
+
import importlib
|
| 21 |
+
import importlib.metadata
|
| 22 |
+
import json
|
| 23 |
+
import sys
|
| 24 |
+
import threading
|
| 25 |
+
import types
|
| 26 |
+
import warnings
|
| 27 |
+
from collections import defaultdict, deque, namedtuple, OrderedDict
|
| 28 |
+
from collections.abc import Callable, Hashable, Iterable, Mapping, Sequence
|
| 29 |
+
from enum import Enum
|
| 30 |
+
from typing import (
|
| 31 |
+
Any,
|
| 32 |
+
cast,
|
| 33 |
+
ClassVar,
|
| 34 |
+
Final,
|
| 35 |
+
Generic,
|
| 36 |
+
NoReturn,
|
| 37 |
+
overload,
|
| 38 |
+
Protocol,
|
| 39 |
+
TYPE_CHECKING,
|
| 40 |
+
TypeAlias,
|
| 41 |
+
TypeVar,
|
| 42 |
+
Union,
|
| 43 |
+
)
|
| 44 |
+
from typing_extensions import deprecated, NamedTuple, Self, TypeIs
|
| 45 |
+
|
| 46 |
+
from torch.torch_version import TorchVersion as _TorchVersion
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
if TYPE_CHECKING:
|
| 50 |
+
import torch.utils._cxx_pytree as cxx_pytree
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
__all__ = [
|
| 54 |
+
"PyTree",
|
| 55 |
+
"Context",
|
| 56 |
+
"FlattenFunc",
|
| 57 |
+
"UnflattenFunc",
|
| 58 |
+
"DumpableContext",
|
| 59 |
+
"ToDumpableContextFn",
|
| 60 |
+
"FromDumpableContextFn",
|
| 61 |
+
"PyTreeSpec",
|
| 62 |
+
"TreeSpec",
|
| 63 |
+
"LeafSpec",
|
| 64 |
+
"keystr",
|
| 65 |
+
"key_get",
|
| 66 |
+
"register_pytree_node",
|
| 67 |
+
"tree_is_leaf",
|
| 68 |
+
"tree_flatten",
|
| 69 |
+
"tree_flatten_with_path",
|
| 70 |
+
"tree_unflatten",
|
| 71 |
+
"tree_iter",
|
| 72 |
+
"tree_leaves",
|
| 73 |
+
"tree_leaves_with_path",
|
| 74 |
+
"tree_structure",
|
| 75 |
+
"tree_map",
|
| 76 |
+
"tree_map_with_path",
|
| 77 |
+
"tree_map_",
|
| 78 |
+
"tree_map_only",
|
| 79 |
+
"tree_map_only_",
|
| 80 |
+
"tree_all",
|
| 81 |
+
"tree_any",
|
| 82 |
+
"tree_all_only",
|
| 83 |
+
"tree_any_only",
|
| 84 |
+
"treespec_dumps",
|
| 85 |
+
"treespec_loads",
|
| 86 |
+
"treespec_pprint",
|
| 87 |
+
"is_namedtuple",
|
| 88 |
+
"is_namedtuple_class",
|
| 89 |
+
"is_namedtuple_instance",
|
| 90 |
+
"is_structseq",
|
| 91 |
+
"is_structseq_class",
|
| 92 |
+
"is_structseq_instance",
|
| 93 |
+
]
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
T = TypeVar("T")
|
| 97 |
+
S = TypeVar("S")
|
| 98 |
+
U = TypeVar("U")
|
| 99 |
+
R = TypeVar("R")
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
DEFAULT_TREESPEC_SERIALIZATION_PROTOCOL = 1
|
| 103 |
+
NO_SERIALIZED_TYPE_NAME_FOUND = "NO_SERIALIZED_TYPE_NAME_FOUND"
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
class KeyEntry(Protocol):
|
| 107 |
+
def __hash__(self) -> int: ...
|
| 108 |
+
|
| 109 |
+
def __eq__(self, other: object) -> bool: ...
|
| 110 |
+
|
| 111 |
+
def __str__(self) -> str: ...
|
| 112 |
+
|
| 113 |
+
def get(self, parent: Any) -> Any: ...
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
class EnumEncoder(json.JSONEncoder):
|
| 117 |
+
def default(self, obj: object) -> str | dict[str, Any]:
|
| 118 |
+
if isinstance(obj, Enum):
|
| 119 |
+
return {
|
| 120 |
+
"__enum__": True,
|
| 121 |
+
"fqn": f"{obj.__class__.__module__}:{obj.__class__.__qualname__}",
|
| 122 |
+
"name": obj.name,
|
| 123 |
+
}
|
| 124 |
+
return cast(str, super().default(obj))
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
Context = Any
|
| 128 |
+
PyTree = Any
|
| 129 |
+
FlattenFunc = Callable[[PyTree], tuple[list[Any], Context]]
|
| 130 |
+
UnflattenFunc = Callable[[Iterable[Any], Context], PyTree]
|
| 131 |
+
DumpableContext = Any # Any json dumpable text
|
| 132 |
+
ToDumpableContextFn = Callable[[Context], DumpableContext]
|
| 133 |
+
FromDumpableContextFn = Callable[[DumpableContext], Context]
|
| 134 |
+
ToStrFunc = Callable[["TreeSpec", list[str]], str]
|
| 135 |
+
MaybeFromStrFunc = Callable[[str], tuple[Any, Context, str] | None]
|
| 136 |
+
KeyPath = tuple[KeyEntry, ...]
|
| 137 |
+
FlattenWithKeysFunc = Callable[[PyTree], tuple[list[tuple[KeyEntry, Any]], Any]]
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
# A NodeDef holds two callables:
|
| 141 |
+
# - flatten_fn should take the collection and return a flat list of values.
|
| 142 |
+
# It can also return some context that is used in reconstructing the
|
| 143 |
+
# collection.
|
| 144 |
+
# - unflatten_fn should take a flat list of values and some context
|
| 145 |
+
# (returned by flatten_fn). It returns the collection by reconstructing
|
| 146 |
+
# it from the list and the context.
|
| 147 |
+
# - flatten_with_keys_fn, which is a callable that takes a
|
| 148 |
+
# pytree and returns a list of (keypath, value) pairs and a context.
|
| 149 |
+
class NodeDef(NamedTuple):
|
| 150 |
+
type: type[Any]
|
| 151 |
+
flatten_fn: FlattenFunc
|
| 152 |
+
unflatten_fn: UnflattenFunc
|
| 153 |
+
flatten_with_keys_fn: FlattenWithKeysFunc | None
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
_NODE_REGISTRY_LOCK = threading.RLock()
|
| 157 |
+
SUPPORTED_NODES: dict[type[Any], NodeDef] = {}
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
# _SerializeNodeDef holds the following:
|
| 161 |
+
# - typ: the type of the node (e.g., "Dict", "List", etc)
|
| 162 |
+
# - serialized_type_name: the fully qualified name of the type, e.g. "collections.OrderedDict"
|
| 163 |
+
# - to_dumpable_context takes a TreeSpec, and returns a serialized string format of the
|
| 164 |
+
# context, and the version number
|
| 165 |
+
# - from_dumpable_context takes in a string representation of the context, and the
|
| 166 |
+
# version, and returns the deserialized context
|
| 167 |
+
class _SerializeNodeDef(NamedTuple):
|
| 168 |
+
typ: type[Any]
|
| 169 |
+
serialized_type_name: str
|
| 170 |
+
to_dumpable_context: ToDumpableContextFn | None
|
| 171 |
+
from_dumpable_context: FromDumpableContextFn | None
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
SUPPORTED_SERIALIZED_TYPES: dict[type[Any], _SerializeNodeDef] = {}
|
| 175 |
+
SERIALIZED_TYPE_TO_PYTHON_TYPE: dict[str, type[Any]] = {}
|
| 176 |
+
|
| 177 |
+
# NB: we try really hard to not import _cxx_pytree (which depends on optree)
|
| 178 |
+
# as much as possible. This is for isolation: a user who is not using C++ pytree
|
| 179 |
+
# shouldn't pay for it, and it helps makes things like cpython upgrades easier.
|
| 180 |
+
_optree_minimum_version = _TorchVersion("0.13.0")
|
| 181 |
+
try:
|
| 182 |
+
_optree_version = importlib.metadata.version("optree")
|
| 183 |
+
except importlib.metadata.PackageNotFoundError:
|
| 184 |
+
# No optree package found
|
| 185 |
+
_cxx_pytree_dynamo_traceable = _cxx_pytree_exists = False
|
| 186 |
+
_optree_version = _TorchVersion("0.0.0a0")
|
| 187 |
+
else:
|
| 188 |
+
_optree_version = _TorchVersion(_optree_version)
|
| 189 |
+
if _optree_version < _optree_minimum_version:
|
| 190 |
+
# optree package less than our required minimum version.
|
| 191 |
+
# Pretend the optree package doesn't exist.
|
| 192 |
+
# NB: We will raise ImportError if the user directly tries to
|
| 193 |
+
# `import torch.utils._cxx_pytree` (look in that file for the check).
|
| 194 |
+
_cxx_pytree_dynamo_traceable = _cxx_pytree_exists = False
|
| 195 |
+
else:
|
| 196 |
+
_cxx_pytree_dynamo_traceable = _cxx_pytree_exists = True
|
| 197 |
+
|
| 198 |
+
_cxx_pytree_imported = False
|
| 199 |
+
_cxx_pytree_pending_imports: list[Any] = []
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def register_pytree_node(
|
| 203 |
+
cls: type[Any],
|
| 204 |
+
flatten_fn: FlattenFunc,
|
| 205 |
+
unflatten_fn: UnflattenFunc,
|
| 206 |
+
*,
|
| 207 |
+
serialized_type_name: str | None = None,
|
| 208 |
+
to_dumpable_context: ToDumpableContextFn | None = None,
|
| 209 |
+
from_dumpable_context: FromDumpableContextFn | None = None,
|
| 210 |
+
flatten_with_keys_fn: FlattenWithKeysFunc | None = None,
|
| 211 |
+
) -> None:
|
| 212 |
+
"""Register a container-like type as pytree node.
|
| 213 |
+
|
| 214 |
+
Note:
|
| 215 |
+
:func:`register_dataclass` is a simpler way of registering a container-like
|
| 216 |
+
type as a pytree node.
|
| 217 |
+
|
| 218 |
+
Args:
|
| 219 |
+
cls: the type to register
|
| 220 |
+
flatten_fn: A callable that takes a pytree and returns a flattened
|
| 221 |
+
representation of the pytree and additional context to represent the
|
| 222 |
+
flattened pytree.
|
| 223 |
+
unflatten_fn: A callable that takes a flattened version of the pytree,
|
| 224 |
+
additional context, and returns an unflattened pytree.
|
| 225 |
+
serialized_type_name: A keyword argument used to specify the fully qualified
|
| 226 |
+
name used when serializing the tree spec.
|
| 227 |
+
to_dumpable_context: An optional keyword argument to custom specify how
|
| 228 |
+
to convert the context of the pytree to a custom json dumpable
|
| 229 |
+
representation. This is used for json serialization, which is being
|
| 230 |
+
used in torch.export right now.
|
| 231 |
+
from_dumpable_context: An optional keyword argument to custom specify how
|
| 232 |
+
to convert the custom json dumpable representation of the context
|
| 233 |
+
back to the original context. This is used for json deserialization,
|
| 234 |
+
which is being used in torch.export right now.
|
| 235 |
+
flatten_with_keys_fn: An optional keyword argument to specify how to
|
| 236 |
+
access each pytree leaf's keypath when flattening and tree-mapping.
|
| 237 |
+
Like ``flatten_fn``, but in place of a List[leaf], it should return
|
| 238 |
+
a List[(keypath, leaf)].
|
| 239 |
+
"""
|
| 240 |
+
with _NODE_REGISTRY_LOCK:
|
| 241 |
+
if cls in SUPPORTED_NODES:
|
| 242 |
+
raise ValueError(f"{cls} is already registered as pytree node.")
|
| 243 |
+
|
| 244 |
+
_private_register_pytree_node(
|
| 245 |
+
cls,
|
| 246 |
+
flatten_fn,
|
| 247 |
+
unflatten_fn,
|
| 248 |
+
serialized_type_name=serialized_type_name,
|
| 249 |
+
to_dumpable_context=to_dumpable_context,
|
| 250 |
+
from_dumpable_context=from_dumpable_context,
|
| 251 |
+
flatten_with_keys_fn=flatten_with_keys_fn,
|
| 252 |
+
)
|
| 253 |
+
|
| 254 |
+
if not _cxx_pytree_exists:
|
| 255 |
+
return
|
| 256 |
+
|
| 257 |
+
if _cxx_pytree_imported:
|
| 258 |
+
import torch.utils._cxx_pytree as cxx_pytree
|
| 259 |
+
|
| 260 |
+
cxx_pytree._private_register_pytree_node(
|
| 261 |
+
cls,
|
| 262 |
+
flatten_fn,
|
| 263 |
+
unflatten_fn,
|
| 264 |
+
serialized_type_name=serialized_type_name,
|
| 265 |
+
to_dumpable_context=to_dumpable_context,
|
| 266 |
+
from_dumpable_context=from_dumpable_context,
|
| 267 |
+
)
|
| 268 |
+
else:
|
| 269 |
+
args = (cls, flatten_fn, unflatten_fn)
|
| 270 |
+
kwargs = {
|
| 271 |
+
"serialized_type_name": serialized_type_name,
|
| 272 |
+
"to_dumpable_context": to_dumpable_context,
|
| 273 |
+
"from_dumpable_context": from_dumpable_context,
|
| 274 |
+
}
|
| 275 |
+
_cxx_pytree_pending_imports.append((args, kwargs))
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
def register_dataclass(
|
| 279 |
+
cls: type[Any],
|
| 280 |
+
*,
|
| 281 |
+
field_names: list[str] | None = None,
|
| 282 |
+
drop_field_names: list[str] | None = None,
|
| 283 |
+
serialized_type_name: str | None = None,
|
| 284 |
+
) -> None:
|
| 285 |
+
"""
|
| 286 |
+
Registers a type that has the semantics of a ``dataclasses.dataclass`` type
|
| 287 |
+
as a pytree node.
|
| 288 |
+
|
| 289 |
+
This is a simpler API than :func:`register_pytree_node` for registering
|
| 290 |
+
a dataclass or a custom class with the semantics of a dataclass.
|
| 291 |
+
|
| 292 |
+
Args:
|
| 293 |
+
cls: The python type to register. The class must have the semantics of a
|
| 294 |
+
dataclass; in particular, it must be constructed by passing the fields
|
| 295 |
+
in.
|
| 296 |
+
field_names (Optional[List[str]]): A list of field names that correspond
|
| 297 |
+
to the **non-constant data** in this class. This list must contain
|
| 298 |
+
all the fields that are used to initialize the class. This argument
|
| 299 |
+
is optional if ``cls`` is a dataclass, in which case the fields will
|
| 300 |
+
be taken from ``dataclasses.fields()``.
|
| 301 |
+
drop_field_names (Optional[List[str]]): A list of field names that
|
| 302 |
+
should not be included in the pytree.
|
| 303 |
+
serialized_type_name: A keyword argument used to specify the fully
|
| 304 |
+
qualified name used when serializing the tree spec. This is only
|
| 305 |
+
needed for serializing the treespec in torch.export.
|
| 306 |
+
|
| 307 |
+
Example:
|
| 308 |
+
|
| 309 |
+
>>> from torch import Tensor
|
| 310 |
+
>>> from dataclasses import dataclass
|
| 311 |
+
>>> import torch.utils._pytree as pytree
|
| 312 |
+
>>>
|
| 313 |
+
>>> @dataclass
|
| 314 |
+
>>> class Point:
|
| 315 |
+
>>> x: Tensor
|
| 316 |
+
>>> y: Tensor
|
| 317 |
+
>>>
|
| 318 |
+
>>> pytree.register_dataclass(Point)
|
| 319 |
+
>>>
|
| 320 |
+
>>> point = Point(torch.tensor(0), torch.tensor(1))
|
| 321 |
+
>>> point = pytree.tree_map(lambda x: x + 1, point)
|
| 322 |
+
>>> assert torch.allclose(point.x, torch.tensor(1))
|
| 323 |
+
>>> assert torch.allclose(point.y, torch.tensor(2))
|
| 324 |
+
|
| 325 |
+
"""
|
| 326 |
+
drop_field_names = drop_field_names or []
|
| 327 |
+
|
| 328 |
+
if not dataclasses.is_dataclass(cls):
|
| 329 |
+
if field_names is None:
|
| 330 |
+
raise ValueError(
|
| 331 |
+
"field_names must be specified with a list of all fields used to "
|
| 332 |
+
f"initialize {cls}, as it is not a dataclass."
|
| 333 |
+
)
|
| 334 |
+
elif field_names is None:
|
| 335 |
+
field_names = [f.name for f in dataclasses.fields(cls) if f.init]
|
| 336 |
+
else:
|
| 337 |
+
dataclass_init_fields = {f.name for f in dataclasses.fields(cls) if f.init}
|
| 338 |
+
dataclass_init_fields.difference_update(drop_field_names)
|
| 339 |
+
|
| 340 |
+
if dataclass_init_fields != set(field_names):
|
| 341 |
+
error_msg = "field_names does not include all dataclass fields.\n"
|
| 342 |
+
|
| 343 |
+
if missing := dataclass_init_fields - set(field_names):
|
| 344 |
+
error_msg += (
|
| 345 |
+
f"Missing fields in `field_names`: {missing}. If you want "
|
| 346 |
+
"to include these fields in the pytree, please add them "
|
| 347 |
+
"to `field_names`, otherwise please add them to "
|
| 348 |
+
"`drop_field_names`.\n"
|
| 349 |
+
)
|
| 350 |
+
|
| 351 |
+
if unexpected := set(field_names) - dataclass_init_fields:
|
| 352 |
+
error_msg += (
|
| 353 |
+
f"Unexpected fields in `field_names`: {unexpected}. "
|
| 354 |
+
"Please remove these fields, or add them to `drop_field_names`.\n"
|
| 355 |
+
)
|
| 356 |
+
|
| 357 |
+
raise ValueError(error_msg)
|
| 358 |
+
|
| 359 |
+
def _flatten_fn(obj: Any) -> tuple[list[Any], Context]:
|
| 360 |
+
flattened = []
|
| 361 |
+
flat_names = []
|
| 362 |
+
none_names = []
|
| 363 |
+
for name in field_names:
|
| 364 |
+
val = getattr(obj, name)
|
| 365 |
+
if val is not None:
|
| 366 |
+
flattened.append(val)
|
| 367 |
+
flat_names.append(name)
|
| 368 |
+
else:
|
| 369 |
+
none_names.append(name)
|
| 370 |
+
return flattened, [flat_names, none_names]
|
| 371 |
+
|
| 372 |
+
def _unflatten_fn(values: Iterable[Any], context: Context) -> Any:
|
| 373 |
+
flat_names, none_names = context
|
| 374 |
+
return cls(
|
| 375 |
+
**dict(zip(flat_names, values, strict=True)), **dict.fromkeys(none_names)
|
| 376 |
+
)
|
| 377 |
+
|
| 378 |
+
def _flatten_fn_with_keys(obj: Any) -> tuple[list[Any], Context]:
|
| 379 |
+
flattened, (flat_names, _none_names) = _flatten_fn(obj) # type: ignore[misc]
|
| 380 |
+
return [
|
| 381 |
+
(GetAttrKey(k), v) for k, v in zip(flat_names, flattened, strict=True)
|
| 382 |
+
], flat_names
|
| 383 |
+
|
| 384 |
+
_private_register_pytree_node(
|
| 385 |
+
cls,
|
| 386 |
+
_flatten_fn,
|
| 387 |
+
_unflatten_fn,
|
| 388 |
+
serialized_type_name=serialized_type_name,
|
| 389 |
+
flatten_with_keys_fn=_flatten_fn_with_keys,
|
| 390 |
+
)
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
CONSTANT_NODES: set[type] = set()
|
| 394 |
+
|
| 395 |
+
|
| 396 |
+
def register_constant(cls: type[Any]) -> None:
|
| 397 |
+
"""Registers a type as a pytree node with no leaves.
|
| 398 |
+
|
| 399 |
+
In a :func:`torch.compile` region, if instances of these types get passed to
|
| 400 |
+
:func:`torch._dynamo.nonstrict_trace`-ed function, they treated as a
|
| 401 |
+
constant (sometimes referred to as "static"):
|
| 402 |
+
|
| 403 |
+
1. if the instance object existed before the :func:`torch.compile` region,
|
| 404 |
+
we _assume_ no mutation will happen to it inside the :func:`torch.compile`
|
| 405 |
+
region, require that it has non-default `__eq__` and `__hash__` methods, and
|
| 406 |
+
we guard on the instance based on its `__eq__` method, i.e., if a new
|
| 407 |
+
instance fails to match any instances from the previous compilations,
|
| 408 |
+
:func:`torch.compile` will recompile the function using the new instance.
|
| 409 |
+
|
| 410 |
+
2. else if the instance object is created inside the :func:`torch.compile`
|
| 411 |
+
region, we currently don't support using it in a
|
| 412 |
+
:func:`torch._dynamo.nonstrict_trace`-ed function.
|
| 413 |
+
|
| 414 |
+
In general, if your class holds Tensors or dynamic int/float/bool (values that
|
| 415 |
+
may change from run-to-run of a function being compiled), then you probably
|
| 416 |
+
do not want to register it as a constant.
|
| 417 |
+
|
| 418 |
+
Otherwise if you want to pass instance of a class to a
|
| 419 |
+
:func:`torch._dynamo.nonstrict_trace`-ed function, but you either can't use
|
| 420 |
+
:func:`register_pytree_node` on the class, or the class is "constant" enough
|
| 421 |
+
that you don't want to bother using :func:`register_pytree_node`, you should
|
| 422 |
+
consider using this function.
|
| 423 |
+
|
| 424 |
+
Args:
|
| 425 |
+
cls: the type to register as a constant. This type must be hashable.
|
| 426 |
+
|
| 427 |
+
Example:
|
| 428 |
+
|
| 429 |
+
>>> from dataclasses import dataclass
|
| 430 |
+
>>> import torch.utils._pytree as pytree
|
| 431 |
+
>>>
|
| 432 |
+
>>> @dataclass(frozen=True)
|
| 433 |
+
>>> class Config:
|
| 434 |
+
>>> norm: str
|
| 435 |
+
>>>
|
| 436 |
+
>>> pytree.register_constant(Config)
|
| 437 |
+
>>>
|
| 438 |
+
>>> config = Config("l2")
|
| 439 |
+
>>> values, spec = pytree.tree_flatten(config)
|
| 440 |
+
>>> assert len(values) == 0
|
| 441 |
+
|
| 442 |
+
"""
|
| 443 |
+
if cls.__eq__ is object.__eq__: # type: ignore[comparison-overlap]
|
| 444 |
+
raise TypeError(
|
| 445 |
+
"register_constant(cls) expects `cls` to have a non-default `__eq__` implementation."
|
| 446 |
+
)
|
| 447 |
+
|
| 448 |
+
# Class with a custom `__eq__` without `__hash__` won't inherit the default
|
| 449 |
+
# `__hash__` from object; see https://stackoverflow.com/a/1608907.
|
| 450 |
+
if cls.__hash__ is None: # type: ignore[comparison-overlap]
|
| 451 |
+
raise TypeError(
|
| 452 |
+
"register_constant(cls) expects `cls` to have a non-default `__hash__` implementation."
|
| 453 |
+
)
|
| 454 |
+
|
| 455 |
+
def _flatten(x): # type: ignore[no-untyped-def]
|
| 456 |
+
return [], ConstantNode(x)
|
| 457 |
+
|
| 458 |
+
def _unflatten(_, context): # type: ignore[no-untyped-def]
|
| 459 |
+
return context.value
|
| 460 |
+
|
| 461 |
+
def _flatten_with_keys(x): # type: ignore[no-untyped-def]
|
| 462 |
+
return [], ConstantNode(x)
|
| 463 |
+
|
| 464 |
+
with _NODE_REGISTRY_LOCK:
|
| 465 |
+
_private_register_pytree_node(
|
| 466 |
+
cls,
|
| 467 |
+
_flatten,
|
| 468 |
+
_unflatten,
|
| 469 |
+
flatten_with_keys_fn=_flatten_with_keys,
|
| 470 |
+
)
|
| 471 |
+
CONSTANT_NODES.add(cls)
|
| 472 |
+
|
| 473 |
+
|
| 474 |
+
def is_constant_class(cls: type[Any]) -> bool:
|
| 475 |
+
return isinstance(cls, type) and cls in CONSTANT_NODES
|
| 476 |
+
|
| 477 |
+
|
| 478 |
+
@dataclasses.dataclass(frozen=True)
|
| 479 |
+
class ConstantNode:
|
| 480 |
+
value: Any
|
| 481 |
+
|
| 482 |
+
|
| 483 |
+
def _is_constant_holder(spec: "TreeSpec") -> bool:
|
| 484 |
+
"""Checks if the spec is from a pytree registered with register_constant"""
|
| 485 |
+
return isinstance(spec._context, ConstantNode)
|
| 486 |
+
|
| 487 |
+
|
| 488 |
+
def _retrieve_constant(spec: "TreeSpec") -> Any:
|
| 489 |
+
"""Given a spec from a pytree registered with register_constant, retrieves the constant"""
|
| 490 |
+
if not _is_constant_holder(spec):
|
| 491 |
+
raise AssertionError("spec does not correspond to a registered constant pytree")
|
| 492 |
+
return tree_unflatten([], spec)
|
| 493 |
+
|
| 494 |
+
|
| 495 |
+
def _register_namedtuple(
|
| 496 |
+
cls: type[Any],
|
| 497 |
+
*,
|
| 498 |
+
serialized_type_name: str,
|
| 499 |
+
) -> None:
|
| 500 |
+
"""
|
| 501 |
+
Registers a namedtuple as a valid pytree node. By default namedtuples are
|
| 502 |
+
valid pytree nodes, but they are not serializable. This API provides the
|
| 503 |
+
argument `serialized_type_name` which allows these namedtuples to be
|
| 504 |
+
serialized.
|
| 505 |
+
|
| 506 |
+
Args:
|
| 507 |
+
cls: the dataclass type to register
|
| 508 |
+
serialized_type_name: The serialized name for the dataclass. This is
|
| 509 |
+
required if you want to serialize the pytree TreeSpec containing this
|
| 510 |
+
namedtuple.
|
| 511 |
+
"""
|
| 512 |
+
_private_register_pytree_node(
|
| 513 |
+
cls,
|
| 514 |
+
_namedtuple_flatten,
|
| 515 |
+
_namedtuple_unflatten,
|
| 516 |
+
serialized_type_name=serialized_type_name,
|
| 517 |
+
to_dumpable_context=_namedtuple_serialize,
|
| 518 |
+
from_dumpable_context=_namedtuple_deserialize,
|
| 519 |
+
flatten_with_keys_fn=_namedtuple_flatten_with_keys,
|
| 520 |
+
)
|
| 521 |
+
|
| 522 |
+
|
| 523 |
+
@deprecated(
|
| 524 |
+
"`torch.utils._pytree._register_pytree_node` is deprecated. "
|
| 525 |
+
"Please use `torch.utils._pytree.register_pytree_node` instead.",
|
| 526 |
+
category=FutureWarning,
|
| 527 |
+
)
|
| 528 |
+
def _register_pytree_node(
|
| 529 |
+
cls: type[Any],
|
| 530 |
+
flatten_fn: FlattenFunc,
|
| 531 |
+
unflatten_fn: UnflattenFunc,
|
| 532 |
+
to_str_fn: ToStrFunc | None = None, # deprecated
|
| 533 |
+
maybe_from_str_fn: MaybeFromStrFunc | None = None, # deprecated
|
| 534 |
+
*,
|
| 535 |
+
serialized_type_name: str | None = None,
|
| 536 |
+
to_dumpable_context: ToDumpableContextFn | None = None,
|
| 537 |
+
from_dumpable_context: FromDumpableContextFn | None = None,
|
| 538 |
+
flatten_with_keys_fn: FlattenWithKeysFunc | None = None,
|
| 539 |
+
) -> None:
|
| 540 |
+
"""Register a container-like type as pytree node for the Python pytree only.
|
| 541 |
+
|
| 542 |
+
Args:
|
| 543 |
+
cls: the type to register
|
| 544 |
+
flatten_fn: A callable that takes a pytree and returns a flattened
|
| 545 |
+
representation of the pytree and additional context to represent the
|
| 546 |
+
flattened pytree.
|
| 547 |
+
unflatten_fn: A callable that takes a flattened version of the pytree,
|
| 548 |
+
additional context, and returns an unflattened pytree.
|
| 549 |
+
serialized_type_name: A keyword argument used to specify the fully qualified
|
| 550 |
+
name used when serializing the tree spec.
|
| 551 |
+
to_dumpable_context: An optional keyword argument to custom specify how
|
| 552 |
+
to convert the context of the pytree to a custom json dumpable
|
| 553 |
+
representation. This is used for json serialization, which is being
|
| 554 |
+
used in torch.export right now.
|
| 555 |
+
from_dumpable_context: An optional keyword argument to custom specify how
|
| 556 |
+
to convert the custom json dumpable representation of the context
|
| 557 |
+
back to the original context. This is used for json deserialization,
|
| 558 |
+
which is being used in torch.export right now.
|
| 559 |
+
flatten_with_keys_fn: An optional keyword argument to specify how to
|
| 560 |
+
access each pytree leaf's keypath when flattening and tree-mapping.
|
| 561 |
+
Like ``flatten_fn``, but in place of a List[leaf], it should return
|
| 562 |
+
a List[(keypath, leaf)].
|
| 563 |
+
"""
|
| 564 |
+
if to_str_fn is not None or maybe_from_str_fn is not None:
|
| 565 |
+
warnings.warn(
|
| 566 |
+
"`to_str_fn` and `maybe_from_str_fn` is deprecated. "
|
| 567 |
+
"Please use `to_dumpable_context` and `from_dumpable_context` instead.",
|
| 568 |
+
FutureWarning,
|
| 569 |
+
stacklevel=2,
|
| 570 |
+
)
|
| 571 |
+
|
| 572 |
+
_private_register_pytree_node(
|
| 573 |
+
cls,
|
| 574 |
+
flatten_fn,
|
| 575 |
+
unflatten_fn,
|
| 576 |
+
serialized_type_name=serialized_type_name,
|
| 577 |
+
to_dumpable_context=to_dumpable_context,
|
| 578 |
+
from_dumpable_context=from_dumpable_context,
|
| 579 |
+
flatten_with_keys_fn=flatten_with_keys_fn,
|
| 580 |
+
)
|
| 581 |
+
|
| 582 |
+
|
| 583 |
+
def _deregister_pytree_node(
|
| 584 |
+
cls: type[Any],
|
| 585 |
+
) -> None:
|
| 586 |
+
"""This is an internal function that is used to deregister a pytree node type
|
| 587 |
+
for the Python pytree only. This should be only used inside PyTorch.
|
| 588 |
+
"""
|
| 589 |
+
with _NODE_REGISTRY_LOCK:
|
| 590 |
+
del SUPPORTED_NODES[cls]
|
| 591 |
+
node_def = SUPPORTED_SERIALIZED_TYPES[cls]
|
| 592 |
+
del SERIALIZED_TYPE_TO_PYTHON_TYPE[node_def.serialized_type_name]
|
| 593 |
+
del SUPPORTED_SERIALIZED_TYPES[cls]
|
| 594 |
+
CONSTANT_NODES.discard(cls)
|
| 595 |
+
|
| 596 |
+
|
| 597 |
+
def _private_register_pytree_node(
|
| 598 |
+
cls: type[Any],
|
| 599 |
+
flatten_fn: FlattenFunc,
|
| 600 |
+
unflatten_fn: UnflattenFunc,
|
| 601 |
+
*,
|
| 602 |
+
serialized_type_name: str | None = None,
|
| 603 |
+
to_dumpable_context: ToDumpableContextFn | None = None,
|
| 604 |
+
from_dumpable_context: FromDumpableContextFn | None = None,
|
| 605 |
+
flatten_with_keys_fn: FlattenWithKeysFunc | None = None,
|
| 606 |
+
) -> None:
|
| 607 |
+
"""This is an internal function that is used to register a pytree node type
|
| 608 |
+
for the Python pytree only. End-users should use :func:`register_pytree_node`
|
| 609 |
+
instead.
|
| 610 |
+
"""
|
| 611 |
+
from torch._library.opaque_object import is_opaque_type
|
| 612 |
+
|
| 613 |
+
if is_opaque_type(cls):
|
| 614 |
+
raise ValueError(
|
| 615 |
+
f"{cls} cannot be registered as a pytree as it has been "
|
| 616 |
+
"registered as an opaque object. Opaque objects must be pytree leaves."
|
| 617 |
+
)
|
| 618 |
+
|
| 619 |
+
with _NODE_REGISTRY_LOCK:
|
| 620 |
+
if cls in SUPPORTED_NODES:
|
| 621 |
+
# TODO: change this warning to an error after OSS/internal stabilize
|
| 622 |
+
warnings.warn(
|
| 623 |
+
f"{cls} is already registered as pytree node. "
|
| 624 |
+
"Overwriting the previous registration.",
|
| 625 |
+
stacklevel=2,
|
| 626 |
+
)
|
| 627 |
+
|
| 628 |
+
node_def = NodeDef(cls, flatten_fn, unflatten_fn, flatten_with_keys_fn)
|
| 629 |
+
SUPPORTED_NODES[cls] = node_def
|
| 630 |
+
|
| 631 |
+
if (to_dumpable_context is None) ^ (from_dumpable_context is None):
|
| 632 |
+
raise ValueError(
|
| 633 |
+
f"Both to_dumpable_context and from_dumpable_context for {cls} must "
|
| 634 |
+
"be None or registered."
|
| 635 |
+
)
|
| 636 |
+
|
| 637 |
+
if serialized_type_name is None:
|
| 638 |
+
serialized_type_name = NO_SERIALIZED_TYPE_NAME_FOUND
|
| 639 |
+
|
| 640 |
+
serialize_node_def = _SerializeNodeDef(
|
| 641 |
+
cls,
|
| 642 |
+
serialized_type_name,
|
| 643 |
+
to_dumpable_context,
|
| 644 |
+
from_dumpable_context,
|
| 645 |
+
)
|
| 646 |
+
SUPPORTED_SERIALIZED_TYPES[cls] = serialize_node_def
|
| 647 |
+
SERIALIZED_TYPE_TO_PYTHON_TYPE[serialized_type_name] = cls
|
| 648 |
+
|
| 649 |
+
|
| 650 |
+
@dataclasses.dataclass(frozen=True)
|
| 651 |
+
class SequenceKey(Generic[T]):
|
| 652 |
+
idx: int
|
| 653 |
+
|
| 654 |
+
def __str__(self) -> str:
|
| 655 |
+
return f"[{self.idx!r}]"
|
| 656 |
+
|
| 657 |
+
def get(self, sequence: Sequence[T]) -> T:
|
| 658 |
+
return sequence[self.idx]
|
| 659 |
+
|
| 660 |
+
|
| 661 |
+
K = TypeVar("K", bound=Hashable)
|
| 662 |
+
|
| 663 |
+
|
| 664 |
+
@dataclasses.dataclass(frozen=True)
|
| 665 |
+
class MappingKey(Generic[K, T]):
|
| 666 |
+
key: K
|
| 667 |
+
|
| 668 |
+
def __str__(self) -> str:
|
| 669 |
+
return f"[{self.key!r}]"
|
| 670 |
+
|
| 671 |
+
def get(self, mapping: Mapping[K, T]) -> T:
|
| 672 |
+
return mapping[self.key]
|
| 673 |
+
|
| 674 |
+
|
| 675 |
+
@dataclasses.dataclass(frozen=True)
|
| 676 |
+
class GetAttrKey:
|
| 677 |
+
name: str
|
| 678 |
+
|
| 679 |
+
def __str__(self) -> str:
|
| 680 |
+
return f".{self.name}"
|
| 681 |
+
|
| 682 |
+
def get(self, obj: Any) -> Any:
|
| 683 |
+
return getattr(obj, self.name)
|
| 684 |
+
|
| 685 |
+
|
| 686 |
+
# Reference: https://github.com/metaopt/optree/blob/main/optree/typing.py
|
| 687 |
+
def is_namedtuple(obj: object | type) -> bool:
|
| 688 |
+
"""Return whether the object is an instance of namedtuple or a subclass of namedtuple."""
|
| 689 |
+
cls = obj if isinstance(obj, type) else type(obj)
|
| 690 |
+
return is_namedtuple_class(cls)
|
| 691 |
+
|
| 692 |
+
|
| 693 |
+
# Reference: https://github.com/metaopt/optree/blob/main/optree/typing.py
|
| 694 |
+
def is_namedtuple_class(cls: type) -> bool:
|
| 695 |
+
"""Return whether the class is a subclass of namedtuple."""
|
| 696 |
+
return (
|
| 697 |
+
isinstance(cls, type)
|
| 698 |
+
and issubclass(cls, tuple)
|
| 699 |
+
and isinstance(getattr(cls, "_fields", None), tuple)
|
| 700 |
+
and all(type(field) is str for field in cls._fields) # type: ignore[attr-defined]
|
| 701 |
+
and callable(getattr(cls, "_make", None))
|
| 702 |
+
and callable(getattr(cls, "_asdict", None))
|
| 703 |
+
)
|
| 704 |
+
|
| 705 |
+
|
| 706 |
+
# Reference: https://github.com/metaopt/optree/blob/main/optree/typing.py
|
| 707 |
+
def is_namedtuple_instance(obj: object) -> bool:
|
| 708 |
+
"""Return whether the object is an instance of namedtuple."""
|
| 709 |
+
return is_namedtuple_class(type(obj))
|
| 710 |
+
|
| 711 |
+
|
| 712 |
+
_T_co = TypeVar("_T_co", covariant=True)
|
| 713 |
+
|
| 714 |
+
|
| 715 |
+
# Reference: https://github.com/metaopt/optree/blob/main/optree/typing.py
|
| 716 |
+
class structseq(tuple[_T_co, ...]):
|
| 717 |
+
"""A generic type stub for CPython's ``PyStructSequence`` type."""
|
| 718 |
+
|
| 719 |
+
__slots__: ClassVar[tuple[()]] = ()
|
| 720 |
+
|
| 721 |
+
n_fields: Final[int] # type: ignore[misc]
|
| 722 |
+
n_sequence_fields: Final[int] # type: ignore[misc]
|
| 723 |
+
n_unnamed_fields: Final[int] # type: ignore[misc]
|
| 724 |
+
|
| 725 |
+
def __init_subclass__(cls) -> NoReturn:
|
| 726 |
+
"""Prohibit subclassing."""
|
| 727 |
+
raise TypeError("type 'structseq' is not an acceptable base type")
|
| 728 |
+
|
| 729 |
+
def __new__(
|
| 730 |
+
cls: type[Self],
|
| 731 |
+
sequence: Iterable[_T_co],
|
| 732 |
+
# pyrefly: ignore [bad-function-definition]
|
| 733 |
+
dict: dict[str, Any] = ...,
|
| 734 |
+
) -> Self:
|
| 735 |
+
raise NotImplementedError
|
| 736 |
+
|
| 737 |
+
|
| 738 |
+
# Reference: https://github.com/metaopt/optree/blob/main/optree/typing.py
|
| 739 |
+
def is_structseq(obj: object | type) -> bool:
|
| 740 |
+
"""Return whether the object is an instance of PyStructSequence or a class of PyStructSequence."""
|
| 741 |
+
cls = obj if isinstance(obj, type) else type(obj)
|
| 742 |
+
return is_structseq_class(cls)
|
| 743 |
+
|
| 744 |
+
|
| 745 |
+
# Set if the type allows subclassing (see CPython's Include/object.h)
|
| 746 |
+
Py_TPFLAGS_BASETYPE: int = 1 << 10
|
| 747 |
+
|
| 748 |
+
|
| 749 |
+
# Reference: https://github.com/metaopt/optree/blob/main/optree/typing.py
|
| 750 |
+
def is_structseq_class(cls: type) -> bool:
|
| 751 |
+
"""Return whether the class is a class of PyStructSequence."""
|
| 752 |
+
return (
|
| 753 |
+
isinstance(cls, type)
|
| 754 |
+
# Check direct inheritance from `tuple` rather than `issubclass(cls, tuple)`
|
| 755 |
+
and cls.__bases__ == (tuple,)
|
| 756 |
+
# Check PyStructSequence members
|
| 757 |
+
and isinstance(getattr(cls, "n_fields", None), int)
|
| 758 |
+
and isinstance(getattr(cls, "n_sequence_fields", None), int)
|
| 759 |
+
and isinstance(getattr(cls, "n_unnamed_fields", None), int)
|
| 760 |
+
# Check the type does not allow subclassing
|
| 761 |
+
and not bool(cls.__flags__ & Py_TPFLAGS_BASETYPE) # only works for CPython
|
| 762 |
+
)
|
| 763 |
+
|
| 764 |
+
|
| 765 |
+
# Reference: https://github.com/metaopt/optree/blob/main/optree/typing.py
|
| 766 |
+
def is_structseq_instance(obj: object) -> bool:
|
| 767 |
+
"""Return whether the object is an instance of PyStructSequence."""
|
| 768 |
+
return is_structseq_class(type(obj))
|
| 769 |
+
|
| 770 |
+
|
| 771 |
+
def _tuple_flatten(d: tuple[T, ...]) -> tuple[list[T], Context]:
|
| 772 |
+
return list(d), None
|
| 773 |
+
|
| 774 |
+
|
| 775 |
+
def _tuple_flatten_with_keys(
|
| 776 |
+
d: tuple[T, ...],
|
| 777 |
+
) -> tuple[list[tuple[KeyEntry, T]], Context]:
|
| 778 |
+
values, context = _tuple_flatten(d)
|
| 779 |
+
# pyrefly: ignore [bad-return]
|
| 780 |
+
return [(SequenceKey(i), v) for i, v in enumerate(values)], context
|
| 781 |
+
|
| 782 |
+
|
| 783 |
+
def _tuple_unflatten(values: Iterable[T], context: Context) -> tuple[T, ...]:
|
| 784 |
+
return tuple(values)
|
| 785 |
+
|
| 786 |
+
|
| 787 |
+
def _list_flatten(d: list[T]) -> tuple[list[T], Context]:
|
| 788 |
+
return d, None
|
| 789 |
+
|
| 790 |
+
|
| 791 |
+
def _list_flatten_with_keys(d: list[T]) -> tuple[list[tuple[KeyEntry, T]], Context]:
|
| 792 |
+
values, context = _list_flatten(d)
|
| 793 |
+
# pyrefly: ignore [bad-return]
|
| 794 |
+
return [(SequenceKey(i), v) for i, v in enumerate(values)], context
|
| 795 |
+
|
| 796 |
+
|
| 797 |
+
def _list_unflatten(values: Iterable[T], context: Context) -> list[T]:
|
| 798 |
+
return list(values)
|
| 799 |
+
|
| 800 |
+
|
| 801 |
+
def _dict_flatten(d: dict[Any, T]) -> tuple[list[T], Context]:
|
| 802 |
+
return list(d.values()), list(d.keys())
|
| 803 |
+
|
| 804 |
+
|
| 805 |
+
def _dict_flatten_with_keys(
|
| 806 |
+
d: dict[Any, T],
|
| 807 |
+
) -> tuple[list[tuple[KeyEntry, T]], Context]:
|
| 808 |
+
values, context = _dict_flatten(d)
|
| 809 |
+
# pyrefly: ignore [bad-return]
|
| 810 |
+
return [(MappingKey(k), v) for k, v in zip(context, values, strict=True)], context
|
| 811 |
+
|
| 812 |
+
|
| 813 |
+
def _dict_unflatten(values: Iterable[T], context: Context) -> dict[Any, T]:
|
| 814 |
+
return dict(zip(context, values, strict=True))
|
| 815 |
+
|
| 816 |
+
|
| 817 |
+
def _namedtuple_flatten(d: NamedTuple) -> tuple[list[Any], Context]:
|
| 818 |
+
return list(d), type(d)
|
| 819 |
+
|
| 820 |
+
|
| 821 |
+
def _namedtuple_flatten_with_keys(
|
| 822 |
+
d: NamedTuple,
|
| 823 |
+
) -> tuple[list[tuple[KeyEntry, Any]], Context]:
|
| 824 |
+
values, context = _namedtuple_flatten(d)
|
| 825 |
+
# pyrefly: ignore [bad-return]
|
| 826 |
+
return (
|
| 827 |
+
[
|
| 828 |
+
(GetAttrKey(field), v)
|
| 829 |
+
for field, v in zip(context._fields, values, strict=True)
|
| 830 |
+
],
|
| 831 |
+
context,
|
| 832 |
+
)
|
| 833 |
+
|
| 834 |
+
|
| 835 |
+
def _namedtuple_unflatten(values: Iterable[T], context: Context) -> NamedTuple:
|
| 836 |
+
return cast(NamedTuple, context(*values))
|
| 837 |
+
|
| 838 |
+
|
| 839 |
+
def _namedtuple_serialize(context: Context) -> DumpableContext:
|
| 840 |
+
if context not in SUPPORTED_SERIALIZED_TYPES:
|
| 841 |
+
raise NotImplementedError(
|
| 842 |
+
f"Can't serialize TreeSpec of namedtuple class {context} because we "
|
| 843 |
+
"didn't register a serializated_type_name. Please register using "
|
| 844 |
+
"`_register_namedtuple`."
|
| 845 |
+
)
|
| 846 |
+
|
| 847 |
+
serialize_node_def = SUPPORTED_SERIALIZED_TYPES[context]
|
| 848 |
+
serialized_type_name = serialize_node_def.serialized_type_name
|
| 849 |
+
|
| 850 |
+
if serialized_type_name == NO_SERIALIZED_TYPE_NAME_FOUND:
|
| 851 |
+
raise NotImplementedError(
|
| 852 |
+
f"Can't serialize TreeSpec of namedtuple class {context} because we "
|
| 853 |
+
"couldn't find a serializated_type_name. Please register using "
|
| 854 |
+
"`_register_namedtuple`."
|
| 855 |
+
)
|
| 856 |
+
return serialized_type_name
|
| 857 |
+
|
| 858 |
+
|
| 859 |
+
def _namedtuple_deserialize(dumpable_context: DumpableContext) -> Context:
|
| 860 |
+
if dumpable_context not in SERIALIZED_TYPE_TO_PYTHON_TYPE:
|
| 861 |
+
raise NotImplementedError(
|
| 862 |
+
f"Can't deserialize TreeSpec of namedtuple class {dumpable_context} "
|
| 863 |
+
"because we couldn't find a serializated name."
|
| 864 |
+
)
|
| 865 |
+
|
| 866 |
+
typ = SERIALIZED_TYPE_TO_PYTHON_TYPE[dumpable_context]
|
| 867 |
+
return typ
|
| 868 |
+
|
| 869 |
+
|
| 870 |
+
def _ordereddict_flatten(d: OrderedDict[Any, T]) -> tuple[list[T], Context]:
|
| 871 |
+
return list(d.values()), list(d.keys())
|
| 872 |
+
|
| 873 |
+
|
| 874 |
+
def _ordereddict_flatten_with_keys(
|
| 875 |
+
d: OrderedDict[Any, T],
|
| 876 |
+
) -> tuple[list[tuple[KeyEntry, T]], Context]:
|
| 877 |
+
values, context = _ordereddict_flatten(d)
|
| 878 |
+
# pyrefly: ignore [bad-return]
|
| 879 |
+
return [(MappingKey(k), v) for k, v in zip(context, values, strict=True)], context
|
| 880 |
+
|
| 881 |
+
|
| 882 |
+
def _ordereddict_unflatten(
|
| 883 |
+
values: Iterable[T],
|
| 884 |
+
context: Context,
|
| 885 |
+
) -> OrderedDict[Any, T]:
|
| 886 |
+
return OrderedDict((key, value) for key, value in zip(context, values, strict=True))
|
| 887 |
+
|
| 888 |
+
|
| 889 |
+
_odict_flatten = _ordereddict_flatten
|
| 890 |
+
_odict_unflatten = _ordereddict_unflatten
|
| 891 |
+
|
| 892 |
+
|
| 893 |
+
def _defaultdict_flatten(d: defaultdict[Any, T]) -> tuple[list[T], Context]:
|
| 894 |
+
values, dict_context = _dict_flatten(d)
|
| 895 |
+
return values, [d.default_factory, dict_context]
|
| 896 |
+
|
| 897 |
+
|
| 898 |
+
def _defaultdict_flatten_with_keys(
|
| 899 |
+
d: defaultdict[Any, T],
|
| 900 |
+
) -> tuple[list[tuple[KeyEntry, T]], Context]:
|
| 901 |
+
values, context = _defaultdict_flatten(d)
|
| 902 |
+
_, dict_context = context
|
| 903 |
+
# pyrefly: ignore [bad-return]
|
| 904 |
+
return [
|
| 905 |
+
(MappingKey(k), v) for k, v in zip(dict_context, values, strict=True)
|
| 906 |
+
], context
|
| 907 |
+
|
| 908 |
+
|
| 909 |
+
def _defaultdict_unflatten(
|
| 910 |
+
values: Iterable[T],
|
| 911 |
+
context: Context,
|
| 912 |
+
) -> defaultdict[Any, T]:
|
| 913 |
+
default_factory, dict_context = context
|
| 914 |
+
return defaultdict(default_factory, _dict_unflatten(values, dict_context))
|
| 915 |
+
|
| 916 |
+
|
| 917 |
+
def _defaultdict_serialize(context: Context) -> DumpableContext:
|
| 918 |
+
default_factory, dict_context = context
|
| 919 |
+
json_defaultdict = {
|
| 920 |
+
"default_factory_module": default_factory.__module__,
|
| 921 |
+
"default_factory_name": default_factory.__qualname__,
|
| 922 |
+
"dict_context": dict_context,
|
| 923 |
+
}
|
| 924 |
+
return json_defaultdict
|
| 925 |
+
|
| 926 |
+
|
| 927 |
+
def _defaultdict_deserialize(dumpable_context: DumpableContext) -> Context:
|
| 928 |
+
if not isinstance(dumpable_context, dict):
|
| 929 |
+
raise AssertionError("dumpable_context must be a dict")
|
| 930 |
+
|
| 931 |
+
expected_keys = {
|
| 932 |
+
"default_factory_module",
|
| 933 |
+
"default_factory_name",
|
| 934 |
+
"dict_context",
|
| 935 |
+
}
|
| 936 |
+
if set(dumpable_context) != expected_keys:
|
| 937 |
+
raise AssertionError(
|
| 938 |
+
f"dumpable_context keys must be {expected_keys}, got {set(dumpable_context)}"
|
| 939 |
+
)
|
| 940 |
+
|
| 941 |
+
default_factory_module = dumpable_context["default_factory_module"]
|
| 942 |
+
default_factory_name = dumpable_context["default_factory_name"]
|
| 943 |
+
if not isinstance(default_factory_module, str):
|
| 944 |
+
raise AssertionError("default_factory_module must be a string")
|
| 945 |
+
if not isinstance(default_factory_name, str):
|
| 946 |
+
raise AssertionError("default_factory_name must be a string")
|
| 947 |
+
module = importlib.import_module(default_factory_module)
|
| 948 |
+
default_factory = getattr(module, default_factory_name)
|
| 949 |
+
|
| 950 |
+
dict_context = dumpable_context["dict_context"]
|
| 951 |
+
return [default_factory, dict_context]
|
| 952 |
+
|
| 953 |
+
|
| 954 |
+
def _deque_flatten(d: deque[T]) -> tuple[list[T], Context]:
|
| 955 |
+
return list(d), d.maxlen
|
| 956 |
+
|
| 957 |
+
|
| 958 |
+
def _deque_flatten_with_keys(
|
| 959 |
+
d: deque[T],
|
| 960 |
+
) -> tuple[list[tuple[KeyEntry, T]], Context]:
|
| 961 |
+
values, context = _deque_flatten(d)
|
| 962 |
+
# pyrefly: ignore [bad-return]
|
| 963 |
+
return [(SequenceKey(i), v) for i, v in enumerate(values)], context
|
| 964 |
+
|
| 965 |
+
|
| 966 |
+
def _deque_unflatten(values: Iterable[T], context: Context) -> deque[T]:
|
| 967 |
+
return deque(values, maxlen=context)
|
| 968 |
+
|
| 969 |
+
|
| 970 |
+
_private_register_pytree_node(
|
| 971 |
+
tuple,
|
| 972 |
+
_tuple_flatten,
|
| 973 |
+
_tuple_unflatten,
|
| 974 |
+
serialized_type_name="builtins.tuple",
|
| 975 |
+
flatten_with_keys_fn=_tuple_flatten_with_keys,
|
| 976 |
+
)
|
| 977 |
+
_private_register_pytree_node(
|
| 978 |
+
list,
|
| 979 |
+
_list_flatten,
|
| 980 |
+
_list_unflatten,
|
| 981 |
+
serialized_type_name="builtins.list",
|
| 982 |
+
flatten_with_keys_fn=_list_flatten_with_keys,
|
| 983 |
+
)
|
| 984 |
+
_private_register_pytree_node(
|
| 985 |
+
dict,
|
| 986 |
+
_dict_flatten,
|
| 987 |
+
_dict_unflatten,
|
| 988 |
+
serialized_type_name="builtins.dict",
|
| 989 |
+
flatten_with_keys_fn=_dict_flatten_with_keys,
|
| 990 |
+
)
|
| 991 |
+
_private_register_pytree_node(
|
| 992 |
+
namedtuple, # type: ignore[arg-type]
|
| 993 |
+
_namedtuple_flatten,
|
| 994 |
+
_namedtuple_unflatten,
|
| 995 |
+
serialized_type_name="collections.namedtuple",
|
| 996 |
+
to_dumpable_context=_namedtuple_serialize,
|
| 997 |
+
from_dumpable_context=_namedtuple_deserialize,
|
| 998 |
+
flatten_with_keys_fn=_namedtuple_flatten_with_keys,
|
| 999 |
+
)
|
| 1000 |
+
_private_register_pytree_node(
|
| 1001 |
+
OrderedDict,
|
| 1002 |
+
_ordereddict_flatten,
|
| 1003 |
+
_ordereddict_unflatten,
|
| 1004 |
+
serialized_type_name="collections.OrderedDict",
|
| 1005 |
+
flatten_with_keys_fn=_ordereddict_flatten_with_keys,
|
| 1006 |
+
)
|
| 1007 |
+
_private_register_pytree_node(
|
| 1008 |
+
defaultdict,
|
| 1009 |
+
_defaultdict_flatten,
|
| 1010 |
+
_defaultdict_unflatten,
|
| 1011 |
+
serialized_type_name="collections.defaultdict",
|
| 1012 |
+
to_dumpable_context=_defaultdict_serialize,
|
| 1013 |
+
from_dumpable_context=_defaultdict_deserialize,
|
| 1014 |
+
flatten_with_keys_fn=_defaultdict_flatten_with_keys,
|
| 1015 |
+
)
|
| 1016 |
+
_private_register_pytree_node(
|
| 1017 |
+
deque,
|
| 1018 |
+
_deque_flatten,
|
| 1019 |
+
_deque_unflatten,
|
| 1020 |
+
serialized_type_name="collections.deque",
|
| 1021 |
+
flatten_with_keys_fn=_deque_flatten_with_keys,
|
| 1022 |
+
)
|
| 1023 |
+
|
| 1024 |
+
|
| 1025 |
+
STANDARD_DICT_TYPES: frozenset[type] = frozenset({dict, OrderedDict, defaultdict})
|
| 1026 |
+
BUILTIN_TYPES: frozenset[type] = frozenset(
|
| 1027 |
+
{
|
| 1028 |
+
tuple,
|
| 1029 |
+
list,
|
| 1030 |
+
dict,
|
| 1031 |
+
namedtuple, # type: ignore[arg-type]
|
| 1032 |
+
OrderedDict,
|
| 1033 |
+
defaultdict,
|
| 1034 |
+
deque,
|
| 1035 |
+
},
|
| 1036 |
+
)
|
| 1037 |
+
|
| 1038 |
+
|
| 1039 |
+
@deprecated(
|
| 1040 |
+
"torch.utils._pytree._is_namedtuple_instance is private and will be removed in a future release. "
|
| 1041 |
+
"Please use torch.utils._pytree.is_namedtuple_instance instead.",
|
| 1042 |
+
category=FutureWarning,
|
| 1043 |
+
)
|
| 1044 |
+
def _is_namedtuple_instance(tree: Any) -> bool:
|
| 1045 |
+
return is_namedtuple_instance(tree)
|
| 1046 |
+
|
| 1047 |
+
|
| 1048 |
+
def _get_node_type(tree: Any) -> Any:
|
| 1049 |
+
node_type = type(tree)
|
| 1050 |
+
# All namedtuple types are implicitly registered as pytree nodes.
|
| 1051 |
+
# XXX: Other parts of the codebase expect namedtuple types always return
|
| 1052 |
+
# `namedtuple` instead of the actual namedtuple type. Even if the type
|
| 1053 |
+
# is explicitly registered.
|
| 1054 |
+
if is_namedtuple_class(node_type):
|
| 1055 |
+
return namedtuple
|
| 1056 |
+
return node_type
|
| 1057 |
+
|
| 1058 |
+
|
| 1059 |
+
# A leaf is defined as anything that is not a Node.
|
| 1060 |
+
def tree_is_leaf(
|
| 1061 |
+
tree: PyTree,
|
| 1062 |
+
is_leaf: Callable[[PyTree], bool] | None = None,
|
| 1063 |
+
) -> bool:
|
| 1064 |
+
"""Check if a pytree is a leaf.
|
| 1065 |
+
|
| 1066 |
+
>>> tree_is_leaf(1)
|
| 1067 |
+
True
|
| 1068 |
+
>>> tree_is_leaf(None)
|
| 1069 |
+
True
|
| 1070 |
+
>>> tree_is_leaf([1, 2, 3])
|
| 1071 |
+
False
|
| 1072 |
+
>>> tree_is_leaf((1, 2, 3), is_leaf=lambda x: isinstance(x, tuple))
|
| 1073 |
+
True
|
| 1074 |
+
>>> tree_is_leaf({"a": 1, "b": 2, "c": 3})
|
| 1075 |
+
False
|
| 1076 |
+
>>> tree_is_leaf({"a": 1, "b": 2, "c": None})
|
| 1077 |
+
False
|
| 1078 |
+
"""
|
| 1079 |
+
if is_leaf is not None and is_leaf(tree):
|
| 1080 |
+
return True
|
| 1081 |
+
return _get_node_type(tree) not in SUPPORTED_NODES
|
| 1082 |
+
|
| 1083 |
+
|
| 1084 |
+
@deprecated(
|
| 1085 |
+
"torch.utils._pytree._is_leaf is private and will be removed in a future release. "
|
| 1086 |
+
"Please use torch.utils._pytree.tree_is_leaf instead.",
|
| 1087 |
+
category=FutureWarning,
|
| 1088 |
+
)
|
| 1089 |
+
def _is_leaf(tree: PyTree, is_leaf: Callable[[PyTree], bool] | None = None) -> bool:
|
| 1090 |
+
return tree_is_leaf(tree, is_leaf=is_leaf)
|
| 1091 |
+
|
| 1092 |
+
|
| 1093 |
+
# A TreeSpec represents the structure of a pytree. It holds:
|
| 1094 |
+
# "type": the type of root Node of the pytree
|
| 1095 |
+
# context: some context that is useful in unflattening the pytree
|
| 1096 |
+
# children(): specs for each child of the root Node
|
| 1097 |
+
# num_nodes: the total number of nodes
|
| 1098 |
+
# num_leaves: the number of leaves
|
| 1099 |
+
# num_children: the number of children of the root Node (i.e., len(children()))
|
| 1100 |
+
# is_leaf(): whether the root Node is a leaf
|
| 1101 |
+
@dataclasses.dataclass(init=False, frozen=True, eq=True, repr=False)
|
| 1102 |
+
class TreeSpec:
|
| 1103 |
+
type: Any
|
| 1104 |
+
_context: Context
|
| 1105 |
+
_children: list[Self]
|
| 1106 |
+
|
| 1107 |
+
num_nodes: int = dataclasses.field(init=False)
|
| 1108 |
+
num_leaves: int = dataclasses.field(init=False)
|
| 1109 |
+
num_children: int = dataclasses.field(init=False)
|
| 1110 |
+
|
| 1111 |
+
def __init__(
|
| 1112 |
+
self,
|
| 1113 |
+
type: Any,
|
| 1114 |
+
context: Context, # keep for backward compatibility
|
| 1115 |
+
children_specs: list[Self], # keep for backward compatibility
|
| 1116 |
+
) -> None:
|
| 1117 |
+
object.__setattr__(self, "type", type)
|
| 1118 |
+
object.__setattr__(self, "_context", context)
|
| 1119 |
+
object.__setattr__(self, "_children", children_specs)
|
| 1120 |
+
self.__post_init__()
|
| 1121 |
+
|
| 1122 |
+
def __post_init__(self) -> None:
|
| 1123 |
+
if self.type is None:
|
| 1124 |
+
assert self._context is None
|
| 1125 |
+
assert len(self._children) == 0
|
| 1126 |
+
num_nodes = 1
|
| 1127 |
+
num_leaves = 1
|
| 1128 |
+
num_children = 0
|
| 1129 |
+
else:
|
| 1130 |
+
num_nodes = 1
|
| 1131 |
+
num_leaves = 0
|
| 1132 |
+
for child in self._children:
|
| 1133 |
+
num_nodes += child.num_nodes
|
| 1134 |
+
num_leaves += child.num_leaves
|
| 1135 |
+
num_children = len(self._children)
|
| 1136 |
+
object.__setattr__(self, "num_nodes", num_nodes)
|
| 1137 |
+
object.__setattr__(self, "num_leaves", num_leaves)
|
| 1138 |
+
object.__setattr__(self, "num_children", num_children)
|
| 1139 |
+
|
| 1140 |
+
def __repr__(self, indent: int = 0) -> str:
|
| 1141 |
+
repr_prefix: str = f"TreeSpec({self.type.__name__}, {self._context}, ["
|
| 1142 |
+
children_specs_str: str = ""
|
| 1143 |
+
if self.num_children > 0:
|
| 1144 |
+
indent += 2
|
| 1145 |
+
children_specs_str += self._children[0].__repr__(indent)
|
| 1146 |
+
children_specs_str += "," if self.num_children > 1 else ""
|
| 1147 |
+
children_specs_str += ",".join(
|
| 1148 |
+
[
|
| 1149 |
+
"\n" + " " * indent + child.__repr__(indent)
|
| 1150 |
+
for child in self._children[1:]
|
| 1151 |
+
]
|
| 1152 |
+
)
|
| 1153 |
+
repr_suffix: str = f"{children_specs_str}])"
|
| 1154 |
+
return repr_prefix + repr_suffix
|
| 1155 |
+
|
| 1156 |
+
def __eq__(self, other: PyTree) -> bool:
|
| 1157 |
+
if self is other:
|
| 1158 |
+
return True
|
| 1159 |
+
elif other.__class__ is self.__class__:
|
| 1160 |
+
if str(self.type) != str(other.type):
|
| 1161 |
+
return False
|
| 1162 |
+
if self._context != other._context:
|
| 1163 |
+
return False
|
| 1164 |
+
elif self._children != other._children:
|
| 1165 |
+
return False
|
| 1166 |
+
return True
|
| 1167 |
+
return NotImplemented
|
| 1168 |
+
|
| 1169 |
+
@property
|
| 1170 |
+
def context(self) -> Context:
|
| 1171 |
+
return self._context
|
| 1172 |
+
|
| 1173 |
+
@property
|
| 1174 |
+
@deprecated(
|
| 1175 |
+
"`treespec.children_specs` is deprecated. "
|
| 1176 |
+
"Use `treespec.child(index)` to access a single child, "
|
| 1177 |
+
"or `treespec.children()` to get all children.",
|
| 1178 |
+
category=FutureWarning,
|
| 1179 |
+
)
|
| 1180 |
+
def children_specs(self) -> list[Self]:
|
| 1181 |
+
return self._children
|
| 1182 |
+
|
| 1183 |
+
def is_leaf(self) -> bool:
|
| 1184 |
+
return self.num_nodes == 1 and self.num_leaves == 1
|
| 1185 |
+
|
| 1186 |
+
def children(self) -> list[Self]:
|
| 1187 |
+
return self._children.copy()
|
| 1188 |
+
|
| 1189 |
+
def child(self, index: int) -> Self:
|
| 1190 |
+
return self._children[index]
|
| 1191 |
+
|
| 1192 |
+
def flatten_up_to(self, tree: PyTree) -> list[PyTree]:
|
| 1193 |
+
def helper(treespec: TreeSpec, node: PyTree, subtrees: list[PyTree]) -> None:
|
| 1194 |
+
if treespec.is_leaf():
|
| 1195 |
+
subtrees.append(node)
|
| 1196 |
+
return
|
| 1197 |
+
|
| 1198 |
+
node_type = _get_node_type(node)
|
| 1199 |
+
if treespec.type not in BUILTIN_TYPES:
|
| 1200 |
+
# Always require custom node types to match exactly
|
| 1201 |
+
if node_type != treespec.type:
|
| 1202 |
+
raise ValueError(
|
| 1203 |
+
f"Type mismatch; "
|
| 1204 |
+
f"expected {treespec.type!r}, but got {node_type!r}.",
|
| 1205 |
+
)
|
| 1206 |
+
flatten_fn = SUPPORTED_NODES[node_type].flatten_fn
|
| 1207 |
+
children, context = flatten_fn(node)
|
| 1208 |
+
if len(children) != treespec.num_children:
|
| 1209 |
+
raise ValueError(
|
| 1210 |
+
f"Node arity mismatch; "
|
| 1211 |
+
f"expected {treespec.num_children}, but got {len(children)}.",
|
| 1212 |
+
)
|
| 1213 |
+
if context != treespec._context:
|
| 1214 |
+
raise ValueError(
|
| 1215 |
+
f"Node context mismatch for custom node type {treespec.type!r}.",
|
| 1216 |
+
)
|
| 1217 |
+
else:
|
| 1218 |
+
# For builtin dictionary types, we allow some flexibility
|
| 1219 |
+
# Otherwise, we require exact matches
|
| 1220 |
+
both_standard_dict = (
|
| 1221 |
+
treespec.type in STANDARD_DICT_TYPES
|
| 1222 |
+
and node_type in STANDARD_DICT_TYPES
|
| 1223 |
+
)
|
| 1224 |
+
if not both_standard_dict and node_type != treespec.type:
|
| 1225 |
+
raise ValueError(
|
| 1226 |
+
f"Node type mismatch; "
|
| 1227 |
+
f"expected {treespec.type!r}, but got {node_type!r}.",
|
| 1228 |
+
)
|
| 1229 |
+
if len(node) != treespec.num_children:
|
| 1230 |
+
raise ValueError(
|
| 1231 |
+
f"Node arity mismatch; "
|
| 1232 |
+
f"expected {treespec.num_children}, but got {len(node)}.",
|
| 1233 |
+
)
|
| 1234 |
+
|
| 1235 |
+
if both_standard_dict:
|
| 1236 |
+
# dictionary types are compatible with each other
|
| 1237 |
+
dict_context = (
|
| 1238 |
+
treespec._context
|
| 1239 |
+
if treespec.type is not defaultdict
|
| 1240 |
+
# ignore mismatch of `default_factory` for defaultdict
|
| 1241 |
+
else treespec._context[1]
|
| 1242 |
+
)
|
| 1243 |
+
expected_keys = dict_context
|
| 1244 |
+
got_key_set = set(node)
|
| 1245 |
+
expected_key_set = set(expected_keys)
|
| 1246 |
+
if got_key_set != expected_key_set:
|
| 1247 |
+
missing_keys = expected_key_set.difference(got_key_set)
|
| 1248 |
+
extra_keys = got_key_set.difference(expected_key_set)
|
| 1249 |
+
message = ""
|
| 1250 |
+
if missing_keys:
|
| 1251 |
+
message += f"; missing key(s): {missing_keys}"
|
| 1252 |
+
if extra_keys:
|
| 1253 |
+
message += f"; extra key(s): {extra_keys}"
|
| 1254 |
+
raise ValueError(f"Node keys mismatch{message}.")
|
| 1255 |
+
children = [node[key] for key in expected_keys]
|
| 1256 |
+
else:
|
| 1257 |
+
# node_type is treespec.type
|
| 1258 |
+
flatten_fn = SUPPORTED_NODES[node_type].flatten_fn
|
| 1259 |
+
children, context = flatten_fn(node)
|
| 1260 |
+
if (
|
| 1261 |
+
node_type is not deque # ignore mismatch of `maxlen` for deque
|
| 1262 |
+
) and context != treespec._context:
|
| 1263 |
+
raise ValueError(
|
| 1264 |
+
f"Node context mismatch for node type {treespec.type!r}; "
|
| 1265 |
+
f"expected {treespec._context!r}, but got {context!r}.", # namedtuple type mismatch
|
| 1266 |
+
)
|
| 1267 |
+
|
| 1268 |
+
for subtree, subspec in zip(children, treespec._children, strict=True):
|
| 1269 |
+
helper(subspec, subtree, subtrees)
|
| 1270 |
+
|
| 1271 |
+
subtrees: list[PyTree] = []
|
| 1272 |
+
helper(self, tree, subtrees)
|
| 1273 |
+
return subtrees
|
| 1274 |
+
|
| 1275 |
+
def unflatten(self, leaves: Iterable[Any]) -> PyTree:
|
| 1276 |
+
if not isinstance(leaves, (list, tuple)):
|
| 1277 |
+
leaves = list(leaves)
|
| 1278 |
+
if len(leaves) != self.num_leaves:
|
| 1279 |
+
raise ValueError(
|
| 1280 |
+
f"treespec.unflatten(leaves): `leaves` has length {len(leaves)} "
|
| 1281 |
+
f"but the spec refers to a pytree that holds {self.num_leaves} "
|
| 1282 |
+
f"items ({self}).",
|
| 1283 |
+
)
|
| 1284 |
+
if self.is_leaf():
|
| 1285 |
+
return leaves[0]
|
| 1286 |
+
|
| 1287 |
+
unflatten_fn = SUPPORTED_NODES[self.type].unflatten_fn
|
| 1288 |
+
|
| 1289 |
+
# Recursively unflatten the children
|
| 1290 |
+
start = 0
|
| 1291 |
+
end = 0
|
| 1292 |
+
child_pytrees = []
|
| 1293 |
+
for child_spec in self._children:
|
| 1294 |
+
end += child_spec.num_leaves
|
| 1295 |
+
child_pytrees.append(child_spec.unflatten(leaves[start:end]))
|
| 1296 |
+
start = end
|
| 1297 |
+
|
| 1298 |
+
return unflatten_fn(child_pytrees, self._context)
|
| 1299 |
+
|
| 1300 |
+
def __hash__(self) -> int:
|
| 1301 |
+
node_type = self.type
|
| 1302 |
+
if node_type is defaultdict:
|
| 1303 |
+
default_factory, dict_context = self._context
|
| 1304 |
+
hashable_context = (default_factory, tuple(dict_context))
|
| 1305 |
+
elif node_type in (dict, OrderedDict):
|
| 1306 |
+
hashable_context = tuple(self._context)
|
| 1307 |
+
elif node_type is None or node_type in BUILTIN_TYPES:
|
| 1308 |
+
hashable_context = self._context
|
| 1309 |
+
elif isinstance(self._context, ConstantNode):
|
| 1310 |
+
hashable_context = self._context.value
|
| 1311 |
+
else:
|
| 1312 |
+
# The context for user-defined node types might not be hashable.
|
| 1313 |
+
# Ignore it for hashing.
|
| 1314 |
+
# This does not break the correctness that equal objects imply the
|
| 1315 |
+
# same hash. This might increase the hash collision rate, but we
|
| 1316 |
+
# don't care about that.
|
| 1317 |
+
hashable_context = None
|
| 1318 |
+
return hash((node_type, hashable_context, tuple(self._children)))
|
| 1319 |
+
|
| 1320 |
+
|
| 1321 |
+
PyTreeSpec: TypeAlias = TreeSpec
|
| 1322 |
+
|
| 1323 |
+
|
| 1324 |
+
# NOTE: subclassing a dataclass is subtle. In order to enable reasoning about
|
| 1325 |
+
# this class with `dataclasses.fields`, etc., while having a simplified
|
| 1326 |
+
# constructor that takes no argument, we wrap with `dataclass(init=True, ...)`
|
| 1327 |
+
# again, with fields that have `init=False`.
|
| 1328 |
+
@deprecated(
|
| 1329 |
+
"`isinstance(treespec, LeafSpec)` is deprecated, "
|
| 1330 |
+
"use `isinstance(treespec, TreeSpec) and treespec.is_leaf()` instead.",
|
| 1331 |
+
category=FutureWarning,
|
| 1332 |
+
)
|
| 1333 |
+
@dataclasses.dataclass(init=True, frozen=True, eq=False, repr=False)
|
| 1334 |
+
class LeafSpec(TreeSpec):
|
| 1335 |
+
type: Any = dataclasses.field(default=None, init=False)
|
| 1336 |
+
_context: Context = dataclasses.field(default=None, init=False)
|
| 1337 |
+
_children: list[Self] = dataclasses.field(default_factory=list, init=False)
|
| 1338 |
+
|
| 1339 |
+
def __post_init__(self) -> None:
|
| 1340 |
+
# Override `__post_init__` for `num_leaves` derivation.
|
| 1341 |
+
object.__setattr__(self, "num_nodes", 1)
|
| 1342 |
+
object.__setattr__(self, "num_leaves", 1)
|
| 1343 |
+
object.__setattr__(self, "num_children", 0)
|
| 1344 |
+
|
| 1345 |
+
def __repr__(self, indent: int = 0) -> str:
|
| 1346 |
+
return "*"
|
| 1347 |
+
|
| 1348 |
+
|
| 1349 |
+
# All leaves are equivalent, so represent with a single object to save on
|
| 1350 |
+
# object construction time
|
| 1351 |
+
with warnings.catch_warnings():
|
| 1352 |
+
warnings.filterwarnings(
|
| 1353 |
+
"ignore", category=FutureWarning, module=__name__, append=False
|
| 1354 |
+
)
|
| 1355 |
+
_LEAF_SPEC = LeafSpec()
|
| 1356 |
+
|
| 1357 |
+
|
| 1358 |
+
def treespec_leaf() -> LeafSpec:
|
| 1359 |
+
"""Make a treespec representing a leaf node."""
|
| 1360 |
+
return _LEAF_SPEC
|
| 1361 |
+
|
| 1362 |
+
|
| 1363 |
+
def treespec_tuple(iterable: Iterable[TreeSpec] = (), /) -> TreeSpec:
|
| 1364 |
+
"""Make a tuple treespec from an iterable of child treespecs."""
|
| 1365 |
+
children = list(iterable)
|
| 1366 |
+
if any(not isinstance(child, TreeSpec) for child in children):
|
| 1367 |
+
raise ValueError(f"Expected a tuple of TreeSpec values, got: {children!r}.")
|
| 1368 |
+
return TreeSpec(tuple, None, children)
|
| 1369 |
+
|
| 1370 |
+
|
| 1371 |
+
def treespec_dict(
|
| 1372 |
+
mapping: Mapping[Any, TreeSpec] | Iterable[tuple[Any, TreeSpec]] = (),
|
| 1373 |
+
/,
|
| 1374 |
+
**kwargs: TreeSpec,
|
| 1375 |
+
) -> TreeSpec:
|
| 1376 |
+
"""Make a dict treespec from a dict of child treespecs."""
|
| 1377 |
+
dct = dict(mapping, **kwargs)
|
| 1378 |
+
if any(not isinstance(child, TreeSpec) for child in dct.values()):
|
| 1379 |
+
raise ValueError(f"Expected a dictionary of TreeSpec values, got: {dct!r}.")
|
| 1380 |
+
return TreeSpec(dict, list(dct.keys()), list(dct.values()))
|
| 1381 |
+
|
| 1382 |
+
|
| 1383 |
+
def _is_pytreespec_instance(
|
| 1384 |
+
obj: Any,
|
| 1385 |
+
) -> TypeIs[Union[TreeSpec, "cxx_pytree.PyTreeSpec"]]:
|
| 1386 |
+
if isinstance(obj, TreeSpec):
|
| 1387 |
+
return True
|
| 1388 |
+
if "torch.utils._cxx_pytree" in sys.modules:
|
| 1389 |
+
# The C++ pytree module is not always available, so we check if it is loaded.
|
| 1390 |
+
# If the C++ pytree module is loaded, we can check if the treespec
|
| 1391 |
+
# is an instance of the C++ TreeSpec class.
|
| 1392 |
+
import torch.utils._cxx_pytree as cxx_pytree
|
| 1393 |
+
|
| 1394 |
+
if isinstance(obj, cxx_pytree.PyTreeSpec):
|
| 1395 |
+
return True
|
| 1396 |
+
if "torch._dynamo.polyfills.pytree" in sys.modules:
|
| 1397 |
+
# The PyTorch Dynamo pytree module is not always available, so we check if it is loaded.
|
| 1398 |
+
# If the PyTorch Dynamo pytree module is loaded, we can check if the treespec
|
| 1399 |
+
# is an instance of the PyTorch Dynamo TreeSpec class.
|
| 1400 |
+
import torch._dynamo.polyfills.pytree as dynamo_pytree
|
| 1401 |
+
|
| 1402 |
+
return isinstance(obj, dynamo_pytree.PyTreeSpec)
|
| 1403 |
+
return False
|
| 1404 |
+
|
| 1405 |
+
|
| 1406 |
+
def _ensure_python_treespec_instance(
|
| 1407 |
+
treespec: Union[TreeSpec, "cxx_pytree.PyTreeSpec"],
|
| 1408 |
+
) -> TreeSpec:
|
| 1409 |
+
if isinstance(treespec, TreeSpec):
|
| 1410 |
+
return treespec
|
| 1411 |
+
|
| 1412 |
+
if not _is_pytreespec_instance(treespec):
|
| 1413 |
+
raise TypeError(
|
| 1414 |
+
f"Expected `treespec` to be an instance of "
|
| 1415 |
+
f"PyTreeSpec but got item of type {type(treespec)}."
|
| 1416 |
+
)
|
| 1417 |
+
dummy_tree = treespec.unflatten([0] * treespec.num_leaves)
|
| 1418 |
+
return tree_structure(dummy_tree)
|
| 1419 |
+
|
| 1420 |
+
|
| 1421 |
+
def tree_flatten(
|
| 1422 |
+
tree: PyTree,
|
| 1423 |
+
is_leaf: Callable[[PyTree], bool] | None = None,
|
| 1424 |
+
) -> tuple[list[Any], TreeSpec]:
|
| 1425 |
+
"""Flattens a pytree into a list of values and a TreeSpec that can be used
|
| 1426 |
+
to reconstruct the pytree.
|
| 1427 |
+
"""
|
| 1428 |
+
|
| 1429 |
+
def helper(node: PyTree, leaves: list[Any]) -> TreeSpec:
|
| 1430 |
+
if tree_is_leaf(node, is_leaf=is_leaf):
|
| 1431 |
+
leaves.append(node)
|
| 1432 |
+
return _LEAF_SPEC
|
| 1433 |
+
|
| 1434 |
+
node_type = _get_node_type(node)
|
| 1435 |
+
flatten_fn = SUPPORTED_NODES[node_type].flatten_fn
|
| 1436 |
+
children, context = flatten_fn(node)
|
| 1437 |
+
|
| 1438 |
+
# Recursively flatten the children
|
| 1439 |
+
subspecs = [helper(child, leaves) for child in children]
|
| 1440 |
+
return TreeSpec(node_type, context, subspecs)
|
| 1441 |
+
|
| 1442 |
+
leaves: list[Any] = []
|
| 1443 |
+
treespec = helper(tree, leaves)
|
| 1444 |
+
return leaves, treespec
|
| 1445 |
+
|
| 1446 |
+
|
| 1447 |
+
def tree_unflatten(leaves: Iterable[Any], treespec: TreeSpec) -> PyTree:
|
| 1448 |
+
"""Given a list of values and a TreeSpec, builds a pytree.
|
| 1449 |
+
This is the inverse operation of `tree_flatten`.
|
| 1450 |
+
"""
|
| 1451 |
+
if not _is_pytreespec_instance(treespec):
|
| 1452 |
+
if not _is_pytreespec_instance(leaves):
|
| 1453 |
+
raise TypeError(
|
| 1454 |
+
f"Expected `treespec` to be an instance of "
|
| 1455 |
+
f"PyTreeSpec but got item of type {type(treespec)}."
|
| 1456 |
+
)
|
| 1457 |
+
# Allow passing the PyTreeSpec instance as the first argument
|
| 1458 |
+
leaves, treespec = treespec, leaves
|
| 1459 |
+
return treespec.unflatten(leaves)
|
| 1460 |
+
|
| 1461 |
+
|
| 1462 |
+
def tree_iter(
|
| 1463 |
+
tree: PyTree,
|
| 1464 |
+
is_leaf: Callable[[PyTree], bool] | None = None,
|
| 1465 |
+
) -> Iterable[Any]:
|
| 1466 |
+
"""Get an iterator over the leaves of a pytree."""
|
| 1467 |
+
if tree_is_leaf(tree, is_leaf=is_leaf):
|
| 1468 |
+
yield tree
|
| 1469 |
+
else:
|
| 1470 |
+
node_type = _get_node_type(tree)
|
| 1471 |
+
flatten_fn = SUPPORTED_NODES[node_type].flatten_fn
|
| 1472 |
+
child_pytrees, _ = flatten_fn(tree)
|
| 1473 |
+
|
| 1474 |
+
# Recursively flatten the children
|
| 1475 |
+
for child in child_pytrees:
|
| 1476 |
+
yield from tree_iter(child, is_leaf=is_leaf)
|
| 1477 |
+
|
| 1478 |
+
|
| 1479 |
+
def tree_leaves(
|
| 1480 |
+
tree: PyTree,
|
| 1481 |
+
is_leaf: Callable[[PyTree], bool] | None = None,
|
| 1482 |
+
) -> list[Any]:
|
| 1483 |
+
"""Get a list of leaves of a pytree."""
|
| 1484 |
+
return list(tree_iter(tree, is_leaf=is_leaf))
|
| 1485 |
+
|
| 1486 |
+
|
| 1487 |
+
def tree_structure(
|
| 1488 |
+
tree: PyTree,
|
| 1489 |
+
is_leaf: Callable[[PyTree], bool] | None = None,
|
| 1490 |
+
) -> TreeSpec:
|
| 1491 |
+
"""Get the TreeSpec for a pytree."""
|
| 1492 |
+
return tree_flatten(tree, is_leaf=is_leaf)[1]
|
| 1493 |
+
|
| 1494 |
+
|
| 1495 |
+
def tree_map(
|
| 1496 |
+
func: Callable[..., Any],
|
| 1497 |
+
tree: PyTree,
|
| 1498 |
+
*rests: PyTree,
|
| 1499 |
+
is_leaf: Callable[[PyTree], bool] | None = None,
|
| 1500 |
+
) -> PyTree:
|
| 1501 |
+
"""Map a multi-input function over pytree args to produce a new pytree.
|
| 1502 |
+
|
| 1503 |
+
See also :func:`tree_map_`.
|
| 1504 |
+
|
| 1505 |
+
>>> tree_map(lambda x: x + 1, {"x": 7, "y": (42, 64)})
|
| 1506 |
+
{'x': 8, 'y': (43, 65)}
|
| 1507 |
+
>>> tree_map(lambda x: x is None, {"x": 7, "y": (42, 64), "z": None})
|
| 1508 |
+
{'x': False, 'y': (False, False), 'z': True}
|
| 1509 |
+
|
| 1510 |
+
If multiple inputs are given, the structure of the tree is taken from the first input;
|
| 1511 |
+
subsequent inputs need only have ``tree`` as a prefix:
|
| 1512 |
+
|
| 1513 |
+
>>> tree_map(lambda x, y: [x] + y, [5, 6], [[7, 9], [1, 2]])
|
| 1514 |
+
[[5, 7, 9], [6, 1, 2]]
|
| 1515 |
+
|
| 1516 |
+
Args:
|
| 1517 |
+
func (callable): A function that takes ``1 + len(rests)`` arguments, to be applied at the
|
| 1518 |
+
corresponding leaves of the pytrees.
|
| 1519 |
+
tree (pytree): A pytree to be mapped over, with each leaf providing the first positional
|
| 1520 |
+
argument to function ``func``.
|
| 1521 |
+
rests (tuple of pytree): A tuple of pytrees, each of which has the same structure as
|
| 1522 |
+
``tree`` or has ``tree`` as a prefix.
|
| 1523 |
+
is_leaf (callable, optional): An extra leaf predicate function that will be called at each
|
| 1524 |
+
flattening step. The function should have a single argument with signature
|
| 1525 |
+
``is_leaf(node) -> bool``. If it returns :data:`True`, the whole subtree being treated
|
| 1526 |
+
as a leaf. Otherwise, the default pytree registry will be used to determine a node is a
|
| 1527 |
+
leaf or not. If the function is not specified, the default pytree registry will be used.
|
| 1528 |
+
|
| 1529 |
+
Returns:
|
| 1530 |
+
A new pytree with the same structure as ``tree`` but with the value at each leaf given by
|
| 1531 |
+
``func(x, *xs)`` where ``x`` is the value at the corresponding leaf in ``tree`` and ``xs``
|
| 1532 |
+
is the tuple of values at corresponding nodes in ``rests``.
|
| 1533 |
+
"""
|
| 1534 |
+
leaves, treespec = tree_flatten(tree, is_leaf=is_leaf)
|
| 1535 |
+
flat_args = [leaves] + [treespec.flatten_up_to(r) for r in rests]
|
| 1536 |
+
return treespec.unflatten(map(func, *flat_args))
|
| 1537 |
+
|
| 1538 |
+
|
| 1539 |
+
def tree_map_(
|
| 1540 |
+
func: Callable[..., Any],
|
| 1541 |
+
tree: PyTree,
|
| 1542 |
+
*rests: PyTree,
|
| 1543 |
+
is_leaf: Callable[[PyTree], bool] | None = None,
|
| 1544 |
+
) -> PyTree:
|
| 1545 |
+
"""Like :func:`tree_map`, but do an inplace call on each leaf and return the original tree.
|
| 1546 |
+
|
| 1547 |
+
See also :func:`tree_map`.
|
| 1548 |
+
|
| 1549 |
+
Args:
|
| 1550 |
+
func (callable): A function that takes ``1 + len(rests)`` arguments, to be applied at the
|
| 1551 |
+
corresponding leaves of the pytrees.
|
| 1552 |
+
tree (pytree): A pytree to be mapped over, with each leaf providing the first positional
|
| 1553 |
+
argument to function ``func``.
|
| 1554 |
+
rests (tuple of pytree): A tuple of pytrees, each of which has the same structure as
|
| 1555 |
+
``tree`` or has ``tree`` as a prefix.
|
| 1556 |
+
is_leaf (callable, optional): An extra leaf predicate function that will be called at each
|
| 1557 |
+
flattening step. The function should have a single argument with signature
|
| 1558 |
+
``is_leaf(node) -> bool``. If it returns :data:`True`, the whole subtree being treated
|
| 1559 |
+
as a leaf. Otherwise, the default pytree registry will be used to determine a node is a
|
| 1560 |
+
leaf or not. If the function is not specified, the default pytree registry will be used.
|
| 1561 |
+
|
| 1562 |
+
Returns:
|
| 1563 |
+
The original ``tree`` with the value at each leaf is given by the side-effect of function
|
| 1564 |
+
``func(x, *xs)`` (not the return value) where ``x`` is the value at the corresponding leaf
|
| 1565 |
+
in ``tree`` and ``xs`` is the tuple of values at values at corresponding nodes in ``rests``.
|
| 1566 |
+
"""
|
| 1567 |
+
leaves, treespec = tree_flatten(tree, is_leaf=is_leaf)
|
| 1568 |
+
flat_args = [leaves] + [treespec.flatten_up_to(r) for r in rests]
|
| 1569 |
+
deque(map(func, *flat_args), maxlen=0) # consume and exhaust the iterable
|
| 1570 |
+
return tree
|
| 1571 |
+
|
| 1572 |
+
|
| 1573 |
+
Type2 = tuple[type[T], type[S]]
|
| 1574 |
+
Type3 = tuple[type[T], type[S], type[U]]
|
| 1575 |
+
TypeAny = type[Any] | tuple[type[Any], ...] | types.UnionType
|
| 1576 |
+
|
| 1577 |
+
Fn2 = Callable[[T | S], R]
|
| 1578 |
+
Fn3 = Callable[[T | S | U], R]
|
| 1579 |
+
Fn = Callable[[T], R]
|
| 1580 |
+
FnAny = Callable[[Any], R]
|
| 1581 |
+
|
| 1582 |
+
MapOnlyFn = Callable[[T], Callable[[Any], Any]]
|
| 1583 |
+
|
| 1584 |
+
|
| 1585 |
+
# These specializations help with type inference on the lambda passed to this
|
| 1586 |
+
# function
|
| 1587 |
+
@overload
|
| 1588 |
+
def map_only(type_or_types_or_pred: type[T], /) -> MapOnlyFn[Fn[T, Any]]: ...
|
| 1589 |
+
|
| 1590 |
+
|
| 1591 |
+
@overload
|
| 1592 |
+
def map_only(type_or_types_or_pred: Type2[T, S], /) -> MapOnlyFn[Fn2[T, S, Any]]: ...
|
| 1593 |
+
|
| 1594 |
+
|
| 1595 |
+
@overload
|
| 1596 |
+
def map_only(
|
| 1597 |
+
type_or_types_or_pred: Type3[T, S, U], /
|
| 1598 |
+
) -> MapOnlyFn[Fn3[T, S, U, Any]]: ...
|
| 1599 |
+
|
| 1600 |
+
|
| 1601 |
+
# This specialization is needed for the implementations below that call
|
| 1602 |
+
@overload
|
| 1603 |
+
def map_only(type_or_types_or_pred: TypeAny, /) -> MapOnlyFn[FnAny[Any]]: ...
|
| 1604 |
+
|
| 1605 |
+
|
| 1606 |
+
@overload
|
| 1607 |
+
def map_only(
|
| 1608 |
+
type_or_types_or_pred: Callable[[Any], bool], /
|
| 1609 |
+
) -> MapOnlyFn[FnAny[Any]]: ...
|
| 1610 |
+
|
| 1611 |
+
|
| 1612 |
+
def map_only(
|
| 1613 |
+
type_or_types_or_pred: TypeAny | Callable[[Any], bool], /
|
| 1614 |
+
) -> MapOnlyFn[FnAny[Any]]:
|
| 1615 |
+
"""
|
| 1616 |
+
Suppose you are writing a tree_map over tensors, leaving everything
|
| 1617 |
+
else unchanged. Ordinarily you would have to write:
|
| 1618 |
+
|
| 1619 |
+
def go(t):
|
| 1620 |
+
if isinstance(t, Tensor):
|
| 1621 |
+
return ...
|
| 1622 |
+
else:
|
| 1623 |
+
return t
|
| 1624 |
+
|
| 1625 |
+
With this function, you only need to write:
|
| 1626 |
+
|
| 1627 |
+
@map_only(Tensor)
|
| 1628 |
+
def go(t):
|
| 1629 |
+
return ...
|
| 1630 |
+
|
| 1631 |
+
You can also directly use 'tree_map_only'
|
| 1632 |
+
"""
|
| 1633 |
+
if isinstance(type_or_types_or_pred, (type, tuple, types.UnionType)):
|
| 1634 |
+
|
| 1635 |
+
def pred(x: Any) -> bool:
|
| 1636 |
+
return isinstance(x, type_or_types_or_pred) # type: ignore[arg-type]
|
| 1637 |
+
|
| 1638 |
+
elif callable(type_or_types_or_pred):
|
| 1639 |
+
pred = type_or_types_or_pred # type: ignore[assignment]
|
| 1640 |
+
else:
|
| 1641 |
+
raise TypeError("Argument must be a type, a tuple of types, or a callable.")
|
| 1642 |
+
|
| 1643 |
+
def wrapper(func: Callable[[T], Any]) -> Callable[[Any], Any]:
|
| 1644 |
+
@functools.wraps(func)
|
| 1645 |
+
def wrapped(x: T) -> Any:
|
| 1646 |
+
if pred(x):
|
| 1647 |
+
return func(x)
|
| 1648 |
+
return x
|
| 1649 |
+
|
| 1650 |
+
return wrapped
|
| 1651 |
+
|
| 1652 |
+
return wrapper
|
| 1653 |
+
|
| 1654 |
+
|
| 1655 |
+
@overload
|
| 1656 |
+
def tree_map_only(
|
| 1657 |
+
type_or_types_or_pred: type[T],
|
| 1658 |
+
/,
|
| 1659 |
+
func: Fn[T, Any],
|
| 1660 |
+
tree: PyTree,
|
| 1661 |
+
is_leaf: Callable[[PyTree], bool] | None = None,
|
| 1662 |
+
) -> PyTree: ...
|
| 1663 |
+
|
| 1664 |
+
|
| 1665 |
+
@overload
|
| 1666 |
+
def tree_map_only(
|
| 1667 |
+
type_or_types_or_pred: Type2[T, S],
|
| 1668 |
+
/,
|
| 1669 |
+
func: Fn2[T, S, Any],
|
| 1670 |
+
tree: PyTree,
|
| 1671 |
+
is_leaf: Callable[[PyTree], bool] | None = None,
|
| 1672 |
+
) -> PyTree: ...
|
| 1673 |
+
|
| 1674 |
+
|
| 1675 |
+
@overload
|
| 1676 |
+
def tree_map_only(
|
| 1677 |
+
type_or_types_or_pred: Type3[T, S, U],
|
| 1678 |
+
/,
|
| 1679 |
+
func: Fn3[T, S, U, Any],
|
| 1680 |
+
tree: PyTree,
|
| 1681 |
+
is_leaf: Callable[[PyTree], bool] | None = None,
|
| 1682 |
+
) -> PyTree: ...
|
| 1683 |
+
|
| 1684 |
+
|
| 1685 |
+
@overload
|
| 1686 |
+
def tree_map_only(
|
| 1687 |
+
type_or_types_or_pred: TypeAny,
|
| 1688 |
+
/,
|
| 1689 |
+
func: FnAny[Any],
|
| 1690 |
+
tree: PyTree,
|
| 1691 |
+
is_leaf: Callable[[PyTree], bool] | None = None,
|
| 1692 |
+
) -> PyTree: ...
|
| 1693 |
+
|
| 1694 |
+
|
| 1695 |
+
@overload
|
| 1696 |
+
def tree_map_only(
|
| 1697 |
+
type_or_types_or_pred: Callable[[Any], bool],
|
| 1698 |
+
/,
|
| 1699 |
+
func: FnAny[Any],
|
| 1700 |
+
tree: PyTree,
|
| 1701 |
+
is_leaf: Callable[[PyTree], bool] | None = None,
|
| 1702 |
+
) -> PyTree: ...
|
| 1703 |
+
|
| 1704 |
+
|
| 1705 |
+
def tree_map_only(
|
| 1706 |
+
type_or_types_or_pred: TypeAny | Callable[[Any], bool],
|
| 1707 |
+
/,
|
| 1708 |
+
func: FnAny[Any],
|
| 1709 |
+
tree: PyTree,
|
| 1710 |
+
is_leaf: Callable[[PyTree], bool] | None = None,
|
| 1711 |
+
) -> PyTree:
|
| 1712 |
+
return tree_map(map_only(type_or_types_or_pred)(func), tree, is_leaf=is_leaf)
|
| 1713 |
+
|
| 1714 |
+
|
| 1715 |
+
@overload
|
| 1716 |
+
def tree_map_only_(
|
| 1717 |
+
type_or_types_or_pred: type[T],
|
| 1718 |
+
/,
|
| 1719 |
+
func: Fn[T, Any],
|
| 1720 |
+
tree: PyTree,
|
| 1721 |
+
is_leaf: Callable[[PyTree], bool] | None = None,
|
| 1722 |
+
) -> PyTree: ...
|
| 1723 |
+
|
| 1724 |
+
|
| 1725 |
+
@overload
|
| 1726 |
+
def tree_map_only_(
|
| 1727 |
+
type_or_types_or_pred: Type2[T, S],
|
| 1728 |
+
/,
|
| 1729 |
+
func: Fn2[T, S, Any],
|
| 1730 |
+
tree: PyTree,
|
| 1731 |
+
is_leaf: Callable[[PyTree], bool] | None = None,
|
| 1732 |
+
) -> PyTree: ...
|
| 1733 |
+
|
| 1734 |
+
|
| 1735 |
+
@overload
|
| 1736 |
+
def tree_map_only_(
|
| 1737 |
+
type_or_types_or_pred: Type3[T, S, U],
|
| 1738 |
+
/,
|
| 1739 |
+
func: Fn3[T, S, U, Any],
|
| 1740 |
+
tree: PyTree,
|
| 1741 |
+
is_leaf: Callable[[PyTree], bool] | None = None,
|
| 1742 |
+
) -> PyTree: ...
|
| 1743 |
+
|
| 1744 |
+
|
| 1745 |
+
@overload
|
| 1746 |
+
def tree_map_only_(
|
| 1747 |
+
type_or_types_or_pred: TypeAny,
|
| 1748 |
+
/,
|
| 1749 |
+
func: FnAny[Any],
|
| 1750 |
+
tree: PyTree,
|
| 1751 |
+
is_leaf: Callable[[PyTree], bool] | None = None,
|
| 1752 |
+
) -> PyTree: ...
|
| 1753 |
+
|
| 1754 |
+
|
| 1755 |
+
@overload
|
| 1756 |
+
def tree_map_only_(
|
| 1757 |
+
type_or_types_or_pred: Callable[[Any], bool],
|
| 1758 |
+
/,
|
| 1759 |
+
func: FnAny[Any],
|
| 1760 |
+
tree: PyTree,
|
| 1761 |
+
is_leaf: Callable[[PyTree], bool] | None = None,
|
| 1762 |
+
) -> PyTree: ...
|
| 1763 |
+
|
| 1764 |
+
|
| 1765 |
+
def tree_map_only_(
|
| 1766 |
+
type_or_types_or_pred: TypeAny | Callable[[Any], bool],
|
| 1767 |
+
/,
|
| 1768 |
+
func: FnAny[Any],
|
| 1769 |
+
tree: PyTree,
|
| 1770 |
+
is_leaf: Callable[[PyTree], bool] | None = None,
|
| 1771 |
+
) -> PyTree:
|
| 1772 |
+
return tree_map_(map_only(type_or_types_or_pred)(func), tree, is_leaf=is_leaf)
|
| 1773 |
+
|
| 1774 |
+
|
| 1775 |
+
def tree_all(
|
| 1776 |
+
pred: Callable[[Any], bool],
|
| 1777 |
+
tree: PyTree,
|
| 1778 |
+
is_leaf: Callable[[PyTree], bool] | None = None,
|
| 1779 |
+
) -> bool:
|
| 1780 |
+
flat_args = tree_iter(tree, is_leaf=is_leaf)
|
| 1781 |
+
return all(map(pred, flat_args))
|
| 1782 |
+
|
| 1783 |
+
|
| 1784 |
+
def tree_any(
|
| 1785 |
+
pred: Callable[[Any], bool],
|
| 1786 |
+
tree: PyTree,
|
| 1787 |
+
is_leaf: Callable[[PyTree], bool] | None = None,
|
| 1788 |
+
) -> bool:
|
| 1789 |
+
flat_args = tree_iter(tree, is_leaf=is_leaf)
|
| 1790 |
+
return any(map(pred, flat_args))
|
| 1791 |
+
|
| 1792 |
+
|
| 1793 |
+
@overload
|
| 1794 |
+
def tree_all_only(
|
| 1795 |
+
type_or_types: type[T],
|
| 1796 |
+
/,
|
| 1797 |
+
pred: Fn[T, bool],
|
| 1798 |
+
tree: PyTree,
|
| 1799 |
+
is_leaf: Callable[[PyTree], bool] | None = None,
|
| 1800 |
+
) -> bool: ...
|
| 1801 |
+
|
| 1802 |
+
|
| 1803 |
+
@overload
|
| 1804 |
+
def tree_all_only(
|
| 1805 |
+
type_or_types: Type2[T, S],
|
| 1806 |
+
/,
|
| 1807 |
+
pred: Fn2[T, S, bool],
|
| 1808 |
+
tree: PyTree,
|
| 1809 |
+
is_leaf: Callable[[PyTree], bool] | None = None,
|
| 1810 |
+
) -> bool: ...
|
| 1811 |
+
|
| 1812 |
+
|
| 1813 |
+
@overload
|
| 1814 |
+
def tree_all_only(
|
| 1815 |
+
type_or_types: Type3[T, S, U],
|
| 1816 |
+
/,
|
| 1817 |
+
pred: Fn3[T, S, U, bool],
|
| 1818 |
+
tree: PyTree,
|
| 1819 |
+
is_leaf: Callable[[PyTree], bool] | None = None,
|
| 1820 |
+
) -> bool: ...
|
| 1821 |
+
|
| 1822 |
+
|
| 1823 |
+
def tree_all_only(
|
| 1824 |
+
type_or_types: TypeAny,
|
| 1825 |
+
/,
|
| 1826 |
+
pred: FnAny[bool],
|
| 1827 |
+
tree: PyTree,
|
| 1828 |
+
is_leaf: Callable[[PyTree], bool] | None = None,
|
| 1829 |
+
) -> bool:
|
| 1830 |
+
flat_args = tree_iter(tree, is_leaf=is_leaf)
|
| 1831 |
+
return all(pred(x) for x in flat_args if isinstance(x, type_or_types))
|
| 1832 |
+
|
| 1833 |
+
|
| 1834 |
+
@overload
|
| 1835 |
+
def tree_any_only(
|
| 1836 |
+
type_or_types: type[T],
|
| 1837 |
+
/,
|
| 1838 |
+
pred: Fn[T, bool],
|
| 1839 |
+
tree: PyTree,
|
| 1840 |
+
is_leaf: Callable[[PyTree], bool] | None = None,
|
| 1841 |
+
) -> bool: ...
|
| 1842 |
+
|
| 1843 |
+
|
| 1844 |
+
@overload
|
| 1845 |
+
def tree_any_only(
|
| 1846 |
+
type_or_types: Type2[T, S],
|
| 1847 |
+
/,
|
| 1848 |
+
pred: Fn2[T, S, bool],
|
| 1849 |
+
tree: PyTree,
|
| 1850 |
+
is_leaf: Callable[[PyTree], bool] | None = None,
|
| 1851 |
+
) -> bool: ...
|
| 1852 |
+
|
| 1853 |
+
|
| 1854 |
+
@overload
|
| 1855 |
+
def tree_any_only(
|
| 1856 |
+
type_or_types: Type3[T, S, U],
|
| 1857 |
+
/,
|
| 1858 |
+
pred: Fn3[T, S, U, bool],
|
| 1859 |
+
tree: PyTree,
|
| 1860 |
+
is_leaf: Callable[[PyTree], bool] | None = None,
|
| 1861 |
+
) -> bool: ...
|
| 1862 |
+
|
| 1863 |
+
|
| 1864 |
+
def tree_any_only(
|
| 1865 |
+
type_or_types: TypeAny,
|
| 1866 |
+
/,
|
| 1867 |
+
pred: FnAny[bool],
|
| 1868 |
+
tree: PyTree,
|
| 1869 |
+
is_leaf: Callable[[PyTree], bool] | None = None,
|
| 1870 |
+
) -> bool:
|
| 1871 |
+
flat_args = tree_iter(tree, is_leaf=is_leaf)
|
| 1872 |
+
return any(pred(x) for x in flat_args if isinstance(x, type_or_types))
|
| 1873 |
+
|
| 1874 |
+
|
| 1875 |
+
# Broadcasts a pytree to the provided TreeSpec and returns the flattened
|
| 1876 |
+
# values. If this is not possible, then this function returns None.
|
| 1877 |
+
#
|
| 1878 |
+
# For example, given pytree=0 and spec=TreeSpec(list, None, [LeafSpec(), LeafSpec()]),
|
| 1879 |
+
# would return [0, 0]. This is useful for part of the vmap implementation:
|
| 1880 |
+
# a user can pass in vmap(fn, in_dims)(*inputs). `in_dims` should be
|
| 1881 |
+
# broadcastable to the tree structure of `inputs` and we use
|
| 1882 |
+
# _broadcast_to_and_flatten to check this.
|
| 1883 |
+
def _broadcast_to_and_flatten(
|
| 1884 |
+
tree: PyTree,
|
| 1885 |
+
treespec: TreeSpec,
|
| 1886 |
+
is_leaf: Callable[[PyTree], bool] | None = None,
|
| 1887 |
+
) -> list[Any] | None:
|
| 1888 |
+
def broadcast_prefix(
|
| 1889 |
+
prefix_tree: PyTree,
|
| 1890 |
+
full_tree: PyTree,
|
| 1891 |
+
is_leaf: Callable[[PyTree], bool] | None = None,
|
| 1892 |
+
) -> list[Any]:
|
| 1893 |
+
result: list[Any] = []
|
| 1894 |
+
|
| 1895 |
+
def add_leaves(x: Any, subtree: PyTree) -> None:
|
| 1896 |
+
subtreespec = tree_structure(subtree, is_leaf=is_leaf)
|
| 1897 |
+
result.extend([x] * subtreespec.num_leaves)
|
| 1898 |
+
|
| 1899 |
+
tree_map_(
|
| 1900 |
+
add_leaves,
|
| 1901 |
+
prefix_tree,
|
| 1902 |
+
full_tree,
|
| 1903 |
+
is_leaf=is_leaf,
|
| 1904 |
+
)
|
| 1905 |
+
return result
|
| 1906 |
+
|
| 1907 |
+
full_tree = tree_unflatten([0] * treespec.num_leaves, treespec)
|
| 1908 |
+
try:
|
| 1909 |
+
return broadcast_prefix(tree, full_tree, is_leaf=is_leaf)
|
| 1910 |
+
except ValueError:
|
| 1911 |
+
return None
|
| 1912 |
+
|
| 1913 |
+
|
| 1914 |
+
@dataclasses.dataclass
|
| 1915 |
+
class _TreeSpecSchema:
|
| 1916 |
+
"""
|
| 1917 |
+
_TreeSpecSchema is the schema used to serialize the TreeSpec
|
| 1918 |
+
It contains the following fields:
|
| 1919 |
+
- type: A string name of the type. null for the case of a LeafSpec.
|
| 1920 |
+
- context: Any format which is json dumpable
|
| 1921 |
+
- children_spec: A list of children serialized specs.
|
| 1922 |
+
"""
|
| 1923 |
+
|
| 1924 |
+
type: str | None
|
| 1925 |
+
context: DumpableContext
|
| 1926 |
+
children_spec: list["_TreeSpecSchema"]
|
| 1927 |
+
|
| 1928 |
+
|
| 1929 |
+
class _ProtocolFn(NamedTuple):
|
| 1930 |
+
treespec_to_json: Callable[[TreeSpec], DumpableContext]
|
| 1931 |
+
json_to_treespec: Callable[[DumpableContext], TreeSpec]
|
| 1932 |
+
|
| 1933 |
+
|
| 1934 |
+
_SUPPORTED_PROTOCOLS: dict[int, _ProtocolFn] = {}
|
| 1935 |
+
|
| 1936 |
+
|
| 1937 |
+
def _treespec_to_json(treespec: TreeSpec) -> _TreeSpecSchema:
|
| 1938 |
+
if treespec.is_leaf():
|
| 1939 |
+
return _TreeSpecSchema(None, None, [])
|
| 1940 |
+
|
| 1941 |
+
if treespec.type not in SUPPORTED_SERIALIZED_TYPES:
|
| 1942 |
+
raise NotImplementedError(
|
| 1943 |
+
f"Serializing {treespec.type} in pytree is not registered.",
|
| 1944 |
+
)
|
| 1945 |
+
|
| 1946 |
+
serialize_node_def = SUPPORTED_SERIALIZED_TYPES[treespec.type]
|
| 1947 |
+
|
| 1948 |
+
serialized_type_name = serialize_node_def.serialized_type_name
|
| 1949 |
+
|
| 1950 |
+
if serialized_type_name == NO_SERIALIZED_TYPE_NAME_FOUND:
|
| 1951 |
+
raise NotImplementedError(
|
| 1952 |
+
f"No registered serialization name for {treespec.type} found. "
|
| 1953 |
+
"Please update your _register_pytree_node call with a `serialized_type_name` kwarg."
|
| 1954 |
+
)
|
| 1955 |
+
|
| 1956 |
+
if serialize_node_def.to_dumpable_context is None:
|
| 1957 |
+
try:
|
| 1958 |
+
serialized_context = json.dumps(treespec._context, cls=EnumEncoder)
|
| 1959 |
+
except TypeError as e:
|
| 1960 |
+
raise TypeError(
|
| 1961 |
+
"Unable to serialize context. "
|
| 1962 |
+
"Please make the context json dump-able, or register a "
|
| 1963 |
+
"custom serializer using _register_pytree_node."
|
| 1964 |
+
) from e
|
| 1965 |
+
else:
|
| 1966 |
+
serialized_context = serialize_node_def.to_dumpable_context(treespec._context)
|
| 1967 |
+
|
| 1968 |
+
child_schemas = [_treespec_to_json(child) for child in treespec._children]
|
| 1969 |
+
|
| 1970 |
+
return _TreeSpecSchema(serialized_type_name, serialized_context, child_schemas)
|
| 1971 |
+
|
| 1972 |
+
|
| 1973 |
+
def enum_object_hook(obj: dict[str, Any]) -> Enum | dict[str, Any]:
|
| 1974 |
+
if "__enum__" in obj:
|
| 1975 |
+
modname, _, classname = obj["fqn"].partition(":")
|
| 1976 |
+
mod = importlib.import_module(modname)
|
| 1977 |
+
enum_cls = mod
|
| 1978 |
+
for attr in classname.split("."):
|
| 1979 |
+
enum_cls = getattr(enum_cls, attr)
|
| 1980 |
+
enum_cls = cast(type[Enum], enum_cls)
|
| 1981 |
+
# pyrefly: ignore [unsupported-operation]
|
| 1982 |
+
return enum_cls[obj["name"]]
|
| 1983 |
+
return obj
|
| 1984 |
+
|
| 1985 |
+
|
| 1986 |
+
def _json_to_treespec(json_schema: DumpableContext) -> TreeSpec:
|
| 1987 |
+
if (
|
| 1988 |
+
json_schema["type"] is None
|
| 1989 |
+
and json_schema["context"] is None
|
| 1990 |
+
and len(json_schema["children_spec"]) == 0
|
| 1991 |
+
):
|
| 1992 |
+
return _LEAF_SPEC
|
| 1993 |
+
|
| 1994 |
+
if json_schema["type"] not in SERIALIZED_TYPE_TO_PYTHON_TYPE:
|
| 1995 |
+
raise NotImplementedError(
|
| 1996 |
+
f"Deserializing {json_schema['type']} in pytree is not registered.",
|
| 1997 |
+
)
|
| 1998 |
+
|
| 1999 |
+
typ = SERIALIZED_TYPE_TO_PYTHON_TYPE[json_schema["type"]]
|
| 2000 |
+
serialize_node_def = SUPPORTED_SERIALIZED_TYPES[typ]
|
| 2001 |
+
|
| 2002 |
+
if serialize_node_def.from_dumpable_context is None:
|
| 2003 |
+
try:
|
| 2004 |
+
context = json.loads(json_schema["context"], object_hook=enum_object_hook)
|
| 2005 |
+
except TypeError as ex:
|
| 2006 |
+
raise TypeError(
|
| 2007 |
+
"Unable to deserialize context. "
|
| 2008 |
+
"Please make the context json load-able, or register a "
|
| 2009 |
+
"custom serializer using _register_pytree_node.",
|
| 2010 |
+
) from ex
|
| 2011 |
+
else:
|
| 2012 |
+
context = serialize_node_def.from_dumpable_context(json_schema["context"])
|
| 2013 |
+
|
| 2014 |
+
children_specs = [
|
| 2015 |
+
_json_to_treespec(child_string) for child_string in json_schema["children_spec"]
|
| 2016 |
+
]
|
| 2017 |
+
|
| 2018 |
+
return TreeSpec(typ, context, children_specs)
|
| 2019 |
+
|
| 2020 |
+
|
| 2021 |
+
_SUPPORTED_PROTOCOLS[1] = _ProtocolFn(_treespec_to_json, _json_to_treespec)
|
| 2022 |
+
|
| 2023 |
+
|
| 2024 |
+
def treespec_dumps(treespec: TreeSpec, protocol: int | None = None) -> str:
|
| 2025 |
+
treespec = _ensure_python_treespec_instance(treespec)
|
| 2026 |
+
|
| 2027 |
+
if protocol is None:
|
| 2028 |
+
protocol = DEFAULT_TREESPEC_SERIALIZATION_PROTOCOL
|
| 2029 |
+
|
| 2030 |
+
if protocol in _SUPPORTED_PROTOCOLS:
|
| 2031 |
+
json_spec = _SUPPORTED_PROTOCOLS[protocol].treespec_to_json(treespec)
|
| 2032 |
+
else:
|
| 2033 |
+
raise ValueError(
|
| 2034 |
+
f"Unknown protocol {protocol}. "
|
| 2035 |
+
f"Available protocols: {list(_SUPPORTED_PROTOCOLS.keys())}",
|
| 2036 |
+
)
|
| 2037 |
+
|
| 2038 |
+
str_spec = json.dumps((protocol, dataclasses.asdict(json_spec)), cls=EnumEncoder)
|
| 2039 |
+
return str_spec
|
| 2040 |
+
|
| 2041 |
+
|
| 2042 |
+
@functools.lru_cache
|
| 2043 |
+
def treespec_loads(serialized: str) -> TreeSpec:
|
| 2044 |
+
protocol, json_schema = json.loads(serialized)
|
| 2045 |
+
|
| 2046 |
+
if protocol in _SUPPORTED_PROTOCOLS:
|
| 2047 |
+
return _SUPPORTED_PROTOCOLS[protocol].json_to_treespec(json_schema)
|
| 2048 |
+
raise ValueError(
|
| 2049 |
+
f"Unknown protocol {protocol}. "
|
| 2050 |
+
f"Available protocols: {list(_SUPPORTED_PROTOCOLS.keys())}",
|
| 2051 |
+
)
|
| 2052 |
+
|
| 2053 |
+
|
| 2054 |
+
class _DummyLeaf:
|
| 2055 |
+
def __repr__(self) -> str:
|
| 2056 |
+
return "*"
|
| 2057 |
+
|
| 2058 |
+
|
| 2059 |
+
def treespec_pprint(treespec: TreeSpec) -> str:
|
| 2060 |
+
dummy_tree = tree_unflatten(
|
| 2061 |
+
[_DummyLeaf() for _ in range(treespec.num_leaves)],
|
| 2062 |
+
treespec,
|
| 2063 |
+
)
|
| 2064 |
+
return repr(dummy_tree)
|
| 2065 |
+
|
| 2066 |
+
|
| 2067 |
+
# TODO(angelayi): remove this function after OSS/internal stabilize
|
| 2068 |
+
@deprecated(
|
| 2069 |
+
"`pytree_to_str` is deprecated. Please use `treespec_dumps` instead.",
|
| 2070 |
+
category=FutureWarning,
|
| 2071 |
+
)
|
| 2072 |
+
def pytree_to_str(treespec: TreeSpec) -> str:
|
| 2073 |
+
return treespec_dumps(treespec)
|
| 2074 |
+
|
| 2075 |
+
|
| 2076 |
+
# TODO(angelayi): remove this function after OSS/internal stabilize
|
| 2077 |
+
@deprecated(
|
| 2078 |
+
"`str_to_pytree` is deprecated. Please use `treespec_loads` instead.",
|
| 2079 |
+
category=FutureWarning,
|
| 2080 |
+
)
|
| 2081 |
+
def str_to_pytree(json: str) -> TreeSpec:
|
| 2082 |
+
return treespec_loads(json)
|
| 2083 |
+
|
| 2084 |
+
|
| 2085 |
+
def arg_tree_leaves(*args: PyTree, **kwargs: PyTree) -> list[Any]:
|
| 2086 |
+
"""Get a flat list of arguments to this function
|
| 2087 |
+
|
| 2088 |
+
A slightly faster version of tree_leaves((args, kwargs))
|
| 2089 |
+
"""
|
| 2090 |
+
leaves: list[Any] = []
|
| 2091 |
+
for a in args:
|
| 2092 |
+
leaves.extend(tree_iter(a))
|
| 2093 |
+
for a in kwargs.values():
|
| 2094 |
+
leaves.extend(tree_iter(a))
|
| 2095 |
+
return leaves
|
| 2096 |
+
|
| 2097 |
+
|
| 2098 |
+
def tree_flatten_with_path(
|
| 2099 |
+
tree: PyTree,
|
| 2100 |
+
is_leaf: Callable[[PyTree], bool] | None = None,
|
| 2101 |
+
) -> tuple[list[tuple[KeyPath, Any]], TreeSpec]:
|
| 2102 |
+
"""Flattens a pytree like :func:`tree_flatten`, but also returns each leaf's key path.
|
| 2103 |
+
|
| 2104 |
+
Args:
|
| 2105 |
+
tree: a pytree to flatten. If it contains a custom type, that type must be
|
| 2106 |
+
registered with an appropriate `tree_flatten_with_path_fn` when registered
|
| 2107 |
+
with :func:`register_pytree_node`.
|
| 2108 |
+
is_leaf: An extra leaf predicate function that will be called at each
|
| 2109 |
+
flattening step. The function should have a single argument with signature
|
| 2110 |
+
``is_leaf(node) -> bool``. If it returns :data:`True`, the whole subtree being treated
|
| 2111 |
+
as a leaf. Otherwise, the default pytree registry will be used to determine a node is a
|
| 2112 |
+
leaf or not. If the function is not specified, the default pytree registry will be used.
|
| 2113 |
+
Returns:
|
| 2114 |
+
A tuple where the first element is a list of (key path, leaf) pairs, and the
|
| 2115 |
+
second element is a :class:`TreeSpec` representing the structure of the flattened
|
| 2116 |
+
tree.
|
| 2117 |
+
"""
|
| 2118 |
+
_, treespec = tree_flatten(tree, is_leaf)
|
| 2119 |
+
return list(_generate_key_paths((), tree, is_leaf)), treespec
|
| 2120 |
+
|
| 2121 |
+
|
| 2122 |
+
def tree_leaves_with_path(
|
| 2123 |
+
tree: PyTree,
|
| 2124 |
+
is_leaf: Callable[[PyTree], bool] | None = None,
|
| 2125 |
+
) -> list[tuple[KeyPath, Any]]:
|
| 2126 |
+
"""Gets the leaves of a pytree like ``tree_leaves`` and returns each leaf's key path.
|
| 2127 |
+
|
| 2128 |
+
Args:
|
| 2129 |
+
tree: a pytree. If it contains a custom type, that type must be
|
| 2130 |
+
registered with an appropriate `tree_flatten_with_path_fn` when registered
|
| 2131 |
+
with :func:`register_pytree_node`.
|
| 2132 |
+
is_leaf: An extra leaf predicate function that will be called at each
|
| 2133 |
+
flattening step. The function should have a single argument with signature
|
| 2134 |
+
``is_leaf(node) -> bool``. If it returns :data:`True`, the whole subtree being treated
|
| 2135 |
+
as a leaf. Otherwise, the default pytree registry will be used to determine a node is a
|
| 2136 |
+
leaf or not. If the function is not specified, the default pytree registry will be used.
|
| 2137 |
+
Returns:
|
| 2138 |
+
A list of (key path, leaf) pairs.
|
| 2139 |
+
"""
|
| 2140 |
+
return list(_generate_key_paths((), tree, is_leaf))
|
| 2141 |
+
|
| 2142 |
+
|
| 2143 |
+
def _generate_key_paths(
|
| 2144 |
+
key_path: KeyPath,
|
| 2145 |
+
tree: PyTree,
|
| 2146 |
+
is_leaf: Callable[[PyTree], bool] | None = None,
|
| 2147 |
+
) -> Iterable[tuple[KeyPath, Any]]:
|
| 2148 |
+
if is_leaf and is_leaf(tree):
|
| 2149 |
+
yield key_path, tree
|
| 2150 |
+
return
|
| 2151 |
+
|
| 2152 |
+
node_type = _get_node_type(tree)
|
| 2153 |
+
handler = SUPPORTED_NODES.get(node_type)
|
| 2154 |
+
if not handler:
|
| 2155 |
+
# This is a leaf
|
| 2156 |
+
yield key_path, tree
|
| 2157 |
+
return
|
| 2158 |
+
|
| 2159 |
+
flatten_with_keys = handler.flatten_with_keys_fn
|
| 2160 |
+
if flatten_with_keys:
|
| 2161 |
+
key_children, _ = flatten_with_keys(tree)
|
| 2162 |
+
for k, c in key_children:
|
| 2163 |
+
yield from _generate_key_paths((*key_path, k), c, is_leaf)
|
| 2164 |
+
else:
|
| 2165 |
+
# We registered this pytree but didn't add a flatten_with_keys_fn, complain.
|
| 2166 |
+
raise ValueError(
|
| 2167 |
+
f"Did not find a flatten_with_keys_fn for type: {node_type}. "
|
| 2168 |
+
"Please pass a flatten_with_keys_fn argument to register_pytree_node."
|
| 2169 |
+
)
|
| 2170 |
+
|
| 2171 |
+
|
| 2172 |
+
def tree_map_with_path(
|
| 2173 |
+
func: Callable[..., Any],
|
| 2174 |
+
tree: PyTree,
|
| 2175 |
+
*rests: PyTree,
|
| 2176 |
+
is_leaf: Callable[[PyTree], bool] | None = None,
|
| 2177 |
+
) -> PyTree:
|
| 2178 |
+
"""Like :func:`tree_map`, but the provided callable takes an additional key path argument.
|
| 2179 |
+
|
| 2180 |
+
Args:
|
| 2181 |
+
func: A function that takes ``2 + len(rests)`` arguments, to be applied at the
|
| 2182 |
+
corresponding leaves of the pytrees. The first positional argument
|
| 2183 |
+
to ``func`` is the key path of the leaf in question. The second
|
| 2184 |
+
positional argument is the value of the leaf.
|
| 2185 |
+
tree: A pytree to be mapped over, with each leaf providing the first positional
|
| 2186 |
+
argument to function ``func``.
|
| 2187 |
+
rests: A tuple of pytrees, each of which has the same structure as
|
| 2188 |
+
``tree`` or has ``tree`` as a prefix.
|
| 2189 |
+
is_leaf: An extra leaf predicate function that will be called at each
|
| 2190 |
+
flattening step. The function should have a single argument with signature
|
| 2191 |
+
``is_leaf(node) -> bool``. If it returns :data:`True`, the whole subtree being treated
|
| 2192 |
+
as a leaf. Otherwise, the default pytree registry will be used to determine a node is a
|
| 2193 |
+
leaf or not. If the function is not specified, the default pytree registry will be used.
|
| 2194 |
+
|
| 2195 |
+
Returns
|
| 2196 |
+
A new pytree with the same structure as ``tree`` but with the value at each leaf given by
|
| 2197 |
+
``func(keypath, x, *xs)`` where ``keypath`` is the key path at the
|
| 2198 |
+
corresponding leaf in ``tree``, ``x`` is the value at that leaf, and
|
| 2199 |
+
``xs`` is the tuple of values at corresponding nodes in ``rests``.
|
| 2200 |
+
"""
|
| 2201 |
+
keypath_leaves, treespec = tree_flatten_with_path(tree, is_leaf)
|
| 2202 |
+
keypath_leaves = list(zip(*keypath_leaves, strict=True))
|
| 2203 |
+
all_keypath_leaves = keypath_leaves + [treespec.flatten_up_to(r) for r in rests]
|
| 2204 |
+
return treespec.unflatten(func(*xs) for xs in zip(*all_keypath_leaves, strict=True))
|
| 2205 |
+
|
| 2206 |
+
|
| 2207 |
+
def keystr(kp: KeyPath) -> str:
|
| 2208 |
+
"""Given a key path, return a pretty-printed representation."""
|
| 2209 |
+
return "".join([str(k) for k in kp])
|
| 2210 |
+
|
| 2211 |
+
|
| 2212 |
+
def key_get(obj: Any, kp: KeyPath) -> Any:
|
| 2213 |
+
"""Given an object and a key path, return the value at the key path."""
|
| 2214 |
+
for k in kp:
|
| 2215 |
+
obj = k.get(obj)
|
| 2216 |
+
return obj
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/_runtime_estimation.py
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
import os
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
from torch._inductor.utils import get_device_tflops, get_gpu_dram_gbps
|
| 6 |
+
from torch.utils._ordered_set import OrderedSet
|
| 7 |
+
|
| 8 |
+
from .flop_counter import flop_registry
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
aten = torch.ops.aten
|
| 12 |
+
|
| 13 |
+
_FLOAT_TYPES = OrderedSet(
|
| 14 |
+
[
|
| 15 |
+
torch.float16,
|
| 16 |
+
torch.bfloat16,
|
| 17 |
+
torch.float32,
|
| 18 |
+
torch.float64,
|
| 19 |
+
]
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
# This value is hard-coded here:
|
| 23 |
+
# https://github.com/pytorch/pytorch/blob/5fba5d83f0703ff8077ab65448a998e9ad6598fd/c10/cuda/CUDACachingAllocator.cpp#L117
|
| 24 |
+
_PYTORCH_MIN_ALLOCATE = (
|
| 25 |
+
2**9 if int(os.environ.get("PYTORCH_NO_CUDA_MEMORY_CACHING", 0)) == 0 else 1
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
# No fall-back kernel needed/exists for view ops
|
| 29 |
+
_VIEW_OPS = OrderedSet(
|
| 30 |
+
[
|
| 31 |
+
aten.lift_fresh,
|
| 32 |
+
aten.t,
|
| 33 |
+
aten.transpose,
|
| 34 |
+
aten.view,
|
| 35 |
+
aten.detach,
|
| 36 |
+
aten._unsafe_view,
|
| 37 |
+
aten.split,
|
| 38 |
+
aten.adjoint,
|
| 39 |
+
aten.as_strided,
|
| 40 |
+
aten.diagonal,
|
| 41 |
+
aten.expand,
|
| 42 |
+
aten.expand_as,
|
| 43 |
+
aten.movedim,
|
| 44 |
+
aten.permute,
|
| 45 |
+
aten.select,
|
| 46 |
+
aten.squeeze,
|
| 47 |
+
aten.mT,
|
| 48 |
+
aten.mH,
|
| 49 |
+
aten.real,
|
| 50 |
+
aten.imag,
|
| 51 |
+
aten.view_as,
|
| 52 |
+
aten.unflatten,
|
| 53 |
+
aten.unfold,
|
| 54 |
+
aten.unbind,
|
| 55 |
+
aten.unsqueeze,
|
| 56 |
+
aten.vsplit,
|
| 57 |
+
aten.hsplit,
|
| 58 |
+
aten.split_with_sizes,
|
| 59 |
+
aten.swapaxes,
|
| 60 |
+
aten.swapdims,
|
| 61 |
+
aten.chunk,
|
| 62 |
+
]
|
| 63 |
+
)
|
| 64 |
+
# We can ignore benchmarking tensor create ops
|
| 65 |
+
_CREATE_OPS = OrderedSet(
|
| 66 |
+
[
|
| 67 |
+
aten.randint,
|
| 68 |
+
aten.randn,
|
| 69 |
+
aten.rand,
|
| 70 |
+
aten.randn_like,
|
| 71 |
+
aten.rand_like,
|
| 72 |
+
aten.randint_like,
|
| 73 |
+
aten.arange,
|
| 74 |
+
aten.ones_like,
|
| 75 |
+
aten.zeros_like,
|
| 76 |
+
]
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
_IGNORE_OPS = _VIEW_OPS | _CREATE_OPS
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def get_compute_time(func_packet, args, kwargs, out, out_dtypes) -> float: # type: ignore[no-untyped-def]
|
| 83 |
+
"""
|
| 84 |
+
Estimates the compute time of an aten operator.
|
| 85 |
+
|
| 86 |
+
Args:
|
| 87 |
+
func_packet: The operator overload packet.
|
| 88 |
+
args: The arguments to the operator.
|
| 89 |
+
kwargs: The keyword arguments to the operator.
|
| 90 |
+
out: The output of the operator.
|
| 91 |
+
out_dtypes: The output data types.
|
| 92 |
+
|
| 93 |
+
Returns:
|
| 94 |
+
float: The estimated compute time in nanoseconds.
|
| 95 |
+
"""
|
| 96 |
+
if func_packet in flop_registry:
|
| 97 |
+
assert len(out_dtypes) == 1, (
|
| 98 |
+
f"Only support single out dtype got {out_dtypes} for {func_packet}"
|
| 99 |
+
)
|
| 100 |
+
dtype = out_dtypes.pop()
|
| 101 |
+
# This actually gives peta-FLOPs/s hence multiply by 1e15 to get the FLOPs/s
|
| 102 |
+
peak_gpu_flops = get_device_tflops(dtype) * 1e15
|
| 103 |
+
# We can expect to achieve 75% of theoretical peak flops
|
| 104 |
+
factor = 0.75
|
| 105 |
+
peak_empirical_flops = factor * peak_gpu_flops
|
| 106 |
+
flop_count_func = flop_registry[func_packet]
|
| 107 |
+
# We divide by a factor of 2 to get the MACs (multiply and accumulate)
|
| 108 |
+
flop_count = flop_count_func(*args, **kwargs, out_val=out) / 2
|
| 109 |
+
# We multiply by 1e9 to get the time in nano seconds
|
| 110 |
+
compute_time = (flop_count / peak_empirical_flops) * 1e9
|
| 111 |
+
return compute_time
|
| 112 |
+
return 0.0
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def get_num_bytes(t: torch.Tensor) -> int:
|
| 116 |
+
"""
|
| 117 |
+
Calculates the memory consumption of a tensor.
|
| 118 |
+
|
| 119 |
+
Args:
|
| 120 |
+
t (torch.Tensor): The input tensor.
|
| 121 |
+
|
| 122 |
+
Returns:
|
| 123 |
+
int: The memory consumption of the tensor in bytes.
|
| 124 |
+
"""
|
| 125 |
+
num_bytes = t.untyped_storage().nbytes()
|
| 126 |
+
mem_consumed = math.ceil(num_bytes / _PYTORCH_MIN_ALLOCATE) * _PYTORCH_MIN_ALLOCATE
|
| 127 |
+
return mem_consumed
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def get_transfer_time(flat_args_kwargs, flat_outs) -> float: # type: ignore[no-untyped-def]
|
| 131 |
+
"""
|
| 132 |
+
Estimates the memory transfer time of input and output tensors.
|
| 133 |
+
|
| 134 |
+
Args:
|
| 135 |
+
flat_args_kwargs (List[torch.Tensor]): The flat list of arguments and keyword arguments.
|
| 136 |
+
flat_outs (List[torch.Tensor]): The flat list of outputs.
|
| 137 |
+
|
| 138 |
+
Returns:
|
| 139 |
+
float: The estimated memory transfer time in nanoseconds.
|
| 140 |
+
"""
|
| 141 |
+
gpu_memory_bandwidth = get_gpu_dram_gbps()
|
| 142 |
+
read_bytes = sum(
|
| 143 |
+
get_num_bytes(t) for t in flat_args_kwargs if isinstance(t, torch.Tensor)
|
| 144 |
+
)
|
| 145 |
+
write_bytes = sum(
|
| 146 |
+
get_num_bytes(t) for t in flat_outs if isinstance(t, torch.Tensor)
|
| 147 |
+
)
|
| 148 |
+
counted_bytes = read_bytes + write_bytes
|
| 149 |
+
# The GPU memory bandwidth is in GB/s so the transfer time is in nanoseconds
|
| 150 |
+
transfer_time = counted_bytes / gpu_memory_bandwidth
|
| 151 |
+
return transfer_time
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/_stats.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# NOTE! PLEASE KEEP THIS FILE *FREE* OF TORCH DEPS! IT SHOULD BE IMPORTABLE ANYWHERE.
|
| 2 |
+
# IF YOU FEEL AN OVERWHELMING URGE TO ADD A TORCH DEP, MAKE A TRAMPOLINE FILE A LA torch._dynamo.utils
|
| 3 |
+
# AND SCRUB AWAY TORCH NOTIONS THERE.
|
| 4 |
+
import collections
|
| 5 |
+
import functools
|
| 6 |
+
from collections import OrderedDict
|
| 7 |
+
from collections.abc import Callable
|
| 8 |
+
from typing import TypeVar
|
| 9 |
+
from typing_extensions import ParamSpec
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
simple_call_counter: OrderedDict[str, int] = collections.OrderedDict()
|
| 13 |
+
|
| 14 |
+
_P = ParamSpec("_P")
|
| 15 |
+
_R = TypeVar("_R")
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def count_label(label: str) -> None:
|
| 19 |
+
prev = simple_call_counter.setdefault(label, 0)
|
| 20 |
+
simple_call_counter[label] = prev + 1
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def count(fn: Callable[_P, _R]) -> Callable[_P, _R]:
|
| 24 |
+
@functools.wraps(fn)
|
| 25 |
+
def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> _R:
|
| 26 |
+
if fn.__qualname__ not in simple_call_counter:
|
| 27 |
+
simple_call_counter[fn.__qualname__] = 0
|
| 28 |
+
simple_call_counter[fn.__qualname__] = simple_call_counter[fn.__qualname__] + 1
|
| 29 |
+
return fn(*args, **kwargs)
|
| 30 |
+
|
| 31 |
+
return wrapper
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/_strobelight/__init__.py
ADDED
|
File without changes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
|
| 7 |
+
import subprocess
|
| 8 |
+
import time
|
| 9 |
+
from collections.abc import Callable, Sequence
|
| 10 |
+
from threading import Lock
|
| 11 |
+
from typing import Any, TypeVar
|
| 12 |
+
from typing_extensions import ParamSpec
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
logger = logging.getLogger("strobelight_function_profiler")
|
| 16 |
+
|
| 17 |
+
console_handler = logging.StreamHandler()
|
| 18 |
+
formatter = logging.Formatter(
|
| 19 |
+
"%(name)s, line %(lineno)d, %(asctime)s, %(levelname)s: %(message)s"
|
| 20 |
+
)
|
| 21 |
+
console_handler.setFormatter(formatter)
|
| 22 |
+
|
| 23 |
+
logger.addHandler(console_handler)
|
| 24 |
+
logger.setLevel(logging.INFO)
|
| 25 |
+
logger.propagate = False
|
| 26 |
+
|
| 27 |
+
_P = ParamSpec("_P")
|
| 28 |
+
_R = TypeVar("_R")
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class StrobelightCLIProfilerError(Exception):
|
| 32 |
+
"""
|
| 33 |
+
Raised when an error happens during strobelight profiling
|
| 34 |
+
"""
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def _pid_namespace_link(pid: int | None = None) -> str:
|
| 38 |
+
"""Returns the link to the process's namespace, example: pid:[4026531836]"""
|
| 39 |
+
PID_NAMESPACE_PATH = "/proc/{}/ns/pid"
|
| 40 |
+
pid = pid or os.getpid()
|
| 41 |
+
return os.readlink(PID_NAMESPACE_PATH.format(pid))
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _pid_namespace(pid: int | None = None) -> int:
|
| 45 |
+
"""Returns the process's namespace id"""
|
| 46 |
+
pid = pid or os.getpid()
|
| 47 |
+
link = _pid_namespace_link(pid)
|
| 48 |
+
return int(link[link.find("[") + 1 : -1])
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def _command_to_string(command: Sequence[str]) -> str:
|
| 52 |
+
return " ".join(command)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class StrobelightCLIFunctionProfiler:
|
| 56 |
+
"""
|
| 57 |
+
Note: this is a meta only tool.
|
| 58 |
+
|
| 59 |
+
StrobelightCLIFunctionProfiler can be used to profile a python function and
|
| 60 |
+
generate a strobelight link with the results. It works on meta servers but
|
| 61 |
+
does not requires an fbcode target.
|
| 62 |
+
When stop_at_error is false(default), error during profiling does not prevent
|
| 63 |
+
the work function from running.
|
| 64 |
+
|
| 65 |
+
Check function_profiler_example.py for an example.
|
| 66 |
+
"""
|
| 67 |
+
|
| 68 |
+
# This lock is used to make sure only one thread is running the profiler at any point.
|
| 69 |
+
_lock = Lock()
|
| 70 |
+
|
| 71 |
+
def __init__(
|
| 72 |
+
self,
|
| 73 |
+
*,
|
| 74 |
+
stop_at_error: bool = False,
|
| 75 |
+
max_profile_duration_sec: int = 60 * 10,
|
| 76 |
+
sample_each: float = 1e7, # sample each sample_each cycles.
|
| 77 |
+
run_user_name: str = "pytorch-strobelight-ondemand",
|
| 78 |
+
timeout_wait_for_running_sec: int = 60,
|
| 79 |
+
timeout_wait_for_finished_sec: int = 60,
|
| 80 |
+
recorded_env_variables: list[str] | None = None,
|
| 81 |
+
sample_tags: list[str] | None = None,
|
| 82 |
+
stack_max_len: int = 127,
|
| 83 |
+
async_stack_max_len: int = 127,
|
| 84 |
+
) -> None:
|
| 85 |
+
self.stop_at_error = stop_at_error
|
| 86 |
+
self.max_profile_duration_sec = max_profile_duration_sec
|
| 87 |
+
self.sample_each = sample_each
|
| 88 |
+
self.run_user_name = run_user_name
|
| 89 |
+
self.timeout_wait_for_running_sec = timeout_wait_for_running_sec
|
| 90 |
+
self.timeout_wait_for_finished_sec = timeout_wait_for_finished_sec
|
| 91 |
+
# Results of the most recent run.
|
| 92 |
+
# Tracks the strobelight run id of the most recent run
|
| 93 |
+
self.current_run_id: int | None = None
|
| 94 |
+
self.sample_tags = sample_tags
|
| 95 |
+
|
| 96 |
+
def _run_async(self) -> None:
|
| 97 |
+
processId = os.getpid()
|
| 98 |
+
namespace = _pid_namespace(processId)
|
| 99 |
+
command = [
|
| 100 |
+
"strobeclient",
|
| 101 |
+
"run",
|
| 102 |
+
"--profiler",
|
| 103 |
+
"pyperf",
|
| 104 |
+
"--event",
|
| 105 |
+
"cycles",
|
| 106 |
+
"--async",
|
| 107 |
+
"--sample-interval",
|
| 108 |
+
f"{int(self.sample_each)}",
|
| 109 |
+
"--duration-ms",
|
| 110 |
+
f"{int(self.max_profile_duration_sec * 1000)}",
|
| 111 |
+
"--pid",
|
| 112 |
+
f"{namespace}:{processId}",
|
| 113 |
+
]
|
| 114 |
+
|
| 115 |
+
if self.sample_tags:
|
| 116 |
+
command.append("--sample-tags")
|
| 117 |
+
command.append(",".join(self.sample_tags))
|
| 118 |
+
|
| 119 |
+
logger.debug("running command: %s", _command_to_string(command))
|
| 120 |
+
result = subprocess.run(command, capture_output=True)
|
| 121 |
+
output = result.stderr.decode("utf-8")
|
| 122 |
+
logger.debug("output:\n{%s}", output)
|
| 123 |
+
|
| 124 |
+
if result.returncode != 0:
|
| 125 |
+
raise StrobelightCLIProfilerError(
|
| 126 |
+
f"failed to start strobelight profiling, error in run_async:{output}"
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
if match := re.search(r"INFO Run Id: (-?\d+)", output):
|
| 130 |
+
self.current_run_id = int(match.group(1))
|
| 131 |
+
return
|
| 132 |
+
|
| 133 |
+
raise StrobelightCLIProfilerError(
|
| 134 |
+
f"failed to start strobelight profiling, unexpected result {output}"
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
def _wait_for_running(self, counter: int = 0) -> None:
|
| 138 |
+
if counter > 20:
|
| 139 |
+
raise StrobelightCLIProfilerError(
|
| 140 |
+
"wait_for_running called more than 20 times"
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
command = ["strobeclient", "getRunStatus", "--run-id", f"{self.current_run_id}"]
|
| 144 |
+
logger.debug("running command: %s", _command_to_string(command))
|
| 145 |
+
result = subprocess.run(command, capture_output=True)
|
| 146 |
+
output = result.stderr.decode("utf-8")
|
| 147 |
+
logger.debug("output:\n{%s}", output)
|
| 148 |
+
|
| 149 |
+
if result.returncode != 0:
|
| 150 |
+
raise StrobelightCLIProfilerError(
|
| 151 |
+
f"failed to start strobelight profiling, error in wait_for_running:{output}"
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
if match := re.search("Profile run status: (.*)", output):
|
| 155 |
+
current_status = match.group(1)
|
| 156 |
+
if current_status == "RUNNING":
|
| 157 |
+
return
|
| 158 |
+
elif current_status == "PREPARING":
|
| 159 |
+
time.sleep(10)
|
| 160 |
+
self._wait_for_running(counter + 1)
|
| 161 |
+
return
|
| 162 |
+
else:
|
| 163 |
+
raise StrobelightCLIProfilerError(f"unexpected {current_status} phase")
|
| 164 |
+
|
| 165 |
+
raise StrobelightCLIProfilerError(f"unexpected output\n: {output} ")
|
| 166 |
+
|
| 167 |
+
def _stop_run(self) -> None:
|
| 168 |
+
command = ["strobeclient", "stopRun", "--run-id", str(self.current_run_id)]
|
| 169 |
+
logger.debug("running command: %s", _command_to_string(command))
|
| 170 |
+
result = subprocess.run(command, capture_output=True)
|
| 171 |
+
output = result.stderr.decode("utf-8")
|
| 172 |
+
logger.debug("output:\n{%s}", output)
|
| 173 |
+
|
| 174 |
+
if result.returncode != 0:
|
| 175 |
+
raise StrobelightCLIProfilerError(
|
| 176 |
+
f"failed to stop strobelight profiling, return code is not 0 :{output}"
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
if match := re.search("INFO ::1:(.*)", output):
|
| 180 |
+
current_status = match.group(1)
|
| 181 |
+
if current_status.__contains__("Success!"):
|
| 182 |
+
return
|
| 183 |
+
else:
|
| 184 |
+
raise StrobelightCLIProfilerError(
|
| 185 |
+
f"failed to stop strobelight profiling, got {current_status} result"
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
raise StrobelightCLIProfilerError(f"unexpected output\n: {output} ")
|
| 189 |
+
|
| 190 |
+
def _get_results(self) -> None:
|
| 191 |
+
command = ["strobeclient", "getRunStatus", "--run-id", str(self.current_run_id)]
|
| 192 |
+
logger.debug("running command: %s", _command_to_string(command))
|
| 193 |
+
result = subprocess.run(command, capture_output=True)
|
| 194 |
+
output = result.stderr.decode("utf-8")
|
| 195 |
+
logger.debug("output:\n{%s}", output)
|
| 196 |
+
|
| 197 |
+
if result.returncode != 0:
|
| 198 |
+
raise StrobelightCLIProfilerError(
|
| 199 |
+
f"failed to extract profiling results, return code is not 0 : {output}"
|
| 200 |
+
)
|
| 201 |
+
|
| 202 |
+
if match := re.search("INFO ::1:(.*)", output):
|
| 203 |
+
current_status = match.group(1)
|
| 204 |
+
if current_status.__contains__("Profile run status: PROCESSING"):
|
| 205 |
+
time.sleep(10)
|
| 206 |
+
self._get_results()
|
| 207 |
+
return
|
| 208 |
+
elif not current_status.__contains__("Profile run finished with SUCCESS"):
|
| 209 |
+
raise StrobelightCLIProfilerError(
|
| 210 |
+
f"failed to extract profiling results, unexpected response {output}"
|
| 211 |
+
)
|
| 212 |
+
|
| 213 |
+
for item in re.findall(
|
| 214 |
+
r"(Total samples(.*)|GraphProfiler(.*)|Icicle view \(python stack\)(.*))",
|
| 215 |
+
output,
|
| 216 |
+
):
|
| 217 |
+
logger.info(item[0])
|
| 218 |
+
|
| 219 |
+
def _stop_strobelight_no_throw(
|
| 220 |
+
self,
|
| 221 |
+
collect_results: bool,
|
| 222 |
+
) -> None:
|
| 223 |
+
try:
|
| 224 |
+
# call stop run
|
| 225 |
+
self._stop_run()
|
| 226 |
+
logger.info("strobelight profiling stopped")
|
| 227 |
+
|
| 228 |
+
logger.debug("collection stopped")
|
| 229 |
+
|
| 230 |
+
if not collect_results:
|
| 231 |
+
return
|
| 232 |
+
|
| 233 |
+
self._get_results()
|
| 234 |
+
except Exception:
|
| 235 |
+
logger.warning("error during stop_strobelight", exc_info=True)
|
| 236 |
+
|
| 237 |
+
# Return true if strobelight started and is running. Never throw.
|
| 238 |
+
def _start_strobelight(self) -> bool:
|
| 239 |
+
strobelight_started = False
|
| 240 |
+
try:
|
| 241 |
+
self._run_async()
|
| 242 |
+
strobelight_started = True
|
| 243 |
+
logger.info("strobelight run id is: %s", self.current_run_id)
|
| 244 |
+
self._wait_for_running()
|
| 245 |
+
logger.info("strobelight profiling running")
|
| 246 |
+
return True
|
| 247 |
+
|
| 248 |
+
except Exception:
|
| 249 |
+
logger.warning("error during start_strobelight:", exc_info=True)
|
| 250 |
+
if strobelight_started:
|
| 251 |
+
self._stop_strobelight_no_throw(collect_results=False)
|
| 252 |
+
return False
|
| 253 |
+
|
| 254 |
+
def profile(
|
| 255 |
+
self, work_function: Callable[_P, _R], *args: _P.args, **kwargs: _P.kwargs
|
| 256 |
+
) -> _R | None:
|
| 257 |
+
self.current_run_id = None
|
| 258 |
+
|
| 259 |
+
if locked := StrobelightCLIFunctionProfiler._lock.acquire(False):
|
| 260 |
+
if not locked:
|
| 261 |
+
if self.stop_at_error:
|
| 262 |
+
raise StrobelightCLIProfilerError("concurrent runs not supported")
|
| 263 |
+
|
| 264 |
+
logger.warning("concurrent runs not supported")
|
| 265 |
+
return work_function(*args, **kwargs)
|
| 266 |
+
|
| 267 |
+
started = self._start_strobelight()
|
| 268 |
+
if not started:
|
| 269 |
+
if self.stop_at_error:
|
| 270 |
+
StrobelightCLIFunctionProfiler._lock.release()
|
| 271 |
+
raise StrobelightCLIProfilerError(
|
| 272 |
+
"failed to start strobelight profiling"
|
| 273 |
+
)
|
| 274 |
+
result = work_function(*args, **kwargs)
|
| 275 |
+
StrobelightCLIFunctionProfiler._lock.release()
|
| 276 |
+
return result
|
| 277 |
+
|
| 278 |
+
try:
|
| 279 |
+
logger.debug("collection started")
|
| 280 |
+
result = work_function(*args, **kwargs)
|
| 281 |
+
self._stop_strobelight_no_throw(collect_results=True)
|
| 282 |
+
StrobelightCLIFunctionProfiler._lock.release()
|
| 283 |
+
return result
|
| 284 |
+
except Exception as error:
|
| 285 |
+
logger.warning("work function throw exception", exc_info=True)
|
| 286 |
+
self._stop_strobelight_no_throw(collect_results=False)
|
| 287 |
+
StrobelightCLIFunctionProfiler._lock.release()
|
| 288 |
+
raise error
|
| 289 |
+
return None
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
# A function decorator that wraps profile, if no profiler is provided one with
|
| 293 |
+
# default args is created. A function can be annotated as:
|
| 294 |
+
# @strobelight()
|
| 295 |
+
# @strobelight(profiler = StrobelightFunctionProfiler(stop_at_error=True,..))
|
| 296 |
+
# @strobelight(stop_at_error=True,...)
|
| 297 |
+
def strobelight(
|
| 298 |
+
profiler: StrobelightCLIFunctionProfiler | None = None, **kwargs: Any
|
| 299 |
+
) -> Callable[[Callable[_P, _R]], Callable[_P, _R | None]]:
|
| 300 |
+
if not profiler:
|
| 301 |
+
profiler = StrobelightCLIFunctionProfiler(**kwargs)
|
| 302 |
+
|
| 303 |
+
def strobelight_inner(
|
| 304 |
+
work_function: Callable[_P, _R],
|
| 305 |
+
) -> Callable[_P, _R | None]:
|
| 306 |
+
@functools.wraps(work_function)
|
| 307 |
+
def wrapper_function(*args: _P.args, **kwargs: _P.kwargs) -> _R | None:
|
| 308 |
+
# pyrefly: ignore [bad-argument-type]
|
| 309 |
+
return profiler.profile(work_function, *args, **kwargs)
|
| 310 |
+
|
| 311 |
+
return wrapper_function
|
| 312 |
+
|
| 313 |
+
return strobelight_inner
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/_sympy/__init__.py
ADDED
|
File without changes
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/_sympy/functions.py
ADDED
|
@@ -0,0 +1,1463 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import functools
|
| 3 |
+
import math
|
| 4 |
+
import operator
|
| 5 |
+
import sys
|
| 6 |
+
from collections.abc import Callable
|
| 7 |
+
from typing import SupportsFloat, TYPE_CHECKING, TypeVar
|
| 8 |
+
from typing_extensions import TypeVarTuple, Unpack
|
| 9 |
+
|
| 10 |
+
import sympy
|
| 11 |
+
from sympy import S
|
| 12 |
+
from sympy.core import sympify
|
| 13 |
+
from sympy.core.expr import Expr
|
| 14 |
+
from sympy.core.function import Application
|
| 15 |
+
from sympy.core.logic import _torf, fuzzy_and, fuzzy_or
|
| 16 |
+
from sympy.core.numbers import equal_valued
|
| 17 |
+
from sympy.core.operations import LatticeOp, ShortCircuit
|
| 18 |
+
from sympy.core.sorting import ordered
|
| 19 |
+
from sympy.core.traversal import walk
|
| 20 |
+
from sympy.printing.precedence import PRECEDENCE
|
| 21 |
+
from sympy.utilities.iterables import sift
|
| 22 |
+
|
| 23 |
+
from torch.torch_version import TorchVersion
|
| 24 |
+
|
| 25 |
+
from .numbers import int_oo
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
if TYPE_CHECKING:
|
| 29 |
+
from collections.abc import Iterable
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
_T = TypeVar("_T", bound=SupportsFloat)
|
| 33 |
+
_Ts = TypeVarTuple("_Ts")
|
| 34 |
+
|
| 35 |
+
# Portions of this file are adapted from the Sympy codebase, which was
|
| 36 |
+
# licensed as follows:
|
| 37 |
+
#
|
| 38 |
+
# Copyright (c) 2006-2023 SymPy Development Team
|
| 39 |
+
#
|
| 40 |
+
# All rights reserved.
|
| 41 |
+
#
|
| 42 |
+
# Redistribution and use in source and binary forms, with or without
|
| 43 |
+
# modification, are permitted provided that the following conditions are met:
|
| 44 |
+
#
|
| 45 |
+
# a. Redistributions of source code must retain the above copyright notice,
|
| 46 |
+
# this list of conditions and the following disclaimer.
|
| 47 |
+
# b. Redistributions in binary form must reproduce the above copyright
|
| 48 |
+
# notice, this list of conditions and the following disclaimer in the
|
| 49 |
+
# documentation and/or other materials provided with the distribution.
|
| 50 |
+
# c. Neither the name of SymPy nor the names of its contributors
|
| 51 |
+
# may be used to endorse or promote products derived from this software
|
| 52 |
+
# without specific prior written permission.
|
| 53 |
+
#
|
| 54 |
+
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
| 55 |
+
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
| 56 |
+
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
| 57 |
+
# ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR
|
| 58 |
+
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
| 59 |
+
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
| 60 |
+
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
| 61 |
+
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
| 62 |
+
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
|
| 63 |
+
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
|
| 64 |
+
# DAMAGE.
|
| 65 |
+
|
| 66 |
+
__all__ = [
|
| 67 |
+
"FloorDiv",
|
| 68 |
+
"ModularIndexing",
|
| 69 |
+
"Where",
|
| 70 |
+
"PythonMod",
|
| 71 |
+
"Mod",
|
| 72 |
+
"CleanDiv",
|
| 73 |
+
"CeilToInt",
|
| 74 |
+
"FloorToInt",
|
| 75 |
+
"CeilDiv",
|
| 76 |
+
"IntTrueDiv",
|
| 77 |
+
"FloatTrueDiv",
|
| 78 |
+
"LShift",
|
| 79 |
+
"RShift",
|
| 80 |
+
"IsNonOverlappingAndDenseIndicator",
|
| 81 |
+
"TruncToFloat",
|
| 82 |
+
"TruncToInt",
|
| 83 |
+
"RoundToInt",
|
| 84 |
+
"RoundDecimal",
|
| 85 |
+
"ToFloat",
|
| 86 |
+
"FloatPow",
|
| 87 |
+
"PowByNatural",
|
| 88 |
+
"Identity",
|
| 89 |
+
]
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def _is_symbols_binary_summation(expr: sympy.Expr) -> bool:
|
| 93 |
+
# No need to check that two args are not the same, since expr is pr-optimized but we do it anyway.
|
| 94 |
+
return (
|
| 95 |
+
expr.is_Add
|
| 96 |
+
and len(expr._args) == 2
|
| 97 |
+
and expr._args[0].is_symbol
|
| 98 |
+
and expr._args[1].is_symbol
|
| 99 |
+
and expr._args[0] is not expr._args[1]
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def _keep_float(
|
| 104 |
+
f: Callable[[Unpack[_Ts]], _T],
|
| 105 |
+
) -> Callable[[Unpack[_Ts]], _T | sympy.Float]:
|
| 106 |
+
@functools.wraps(f)
|
| 107 |
+
def inner(*args: Unpack[_Ts]) -> _T | sympy.Float:
|
| 108 |
+
# pyrefly: ignore [bad-argument-type]
|
| 109 |
+
r: _T | sympy.Float = f(*args)
|
| 110 |
+
if any(isinstance(a, sympy.Float) for a in args) and not isinstance(
|
| 111 |
+
r, sympy.Float
|
| 112 |
+
):
|
| 113 |
+
r = sympy.Float(float(r))
|
| 114 |
+
return r
|
| 115 |
+
|
| 116 |
+
# pyrefly: ignore [bad-return]
|
| 117 |
+
return inner
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def fuzzy_eq(x: bool | None, y: bool | None) -> bool | None:
|
| 121 |
+
if None in (x, y):
|
| 122 |
+
return None
|
| 123 |
+
return x == y
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def simple_floordiv_gcd(p: sympy.Basic, q: sympy.Basic) -> sympy.Basic:
|
| 127 |
+
"""
|
| 128 |
+
Fast path for sympy.gcd, using a simple factoring strategy.
|
| 129 |
+
|
| 130 |
+
We try to rewrite p and q in the form n*e*p1 + n*e*p2 and n*e*q0,
|
| 131 |
+
where n is the greatest common integer factor and e is the largest
|
| 132 |
+
syntactic common factor (i.e., common sub-expression) in p and q.
|
| 133 |
+
Then the gcd returned is n*e, cancelling which we would be left with
|
| 134 |
+
p1 + p2 and q0.
|
| 135 |
+
|
| 136 |
+
Note that further factoring of p1 + p2 and q0 might be possible with
|
| 137 |
+
sympy.factor (which uses domain-specific theories). E.g., we are unable
|
| 138 |
+
to find that x*y + x + y + 1 is divisible by x + 1. More generally,
|
| 139 |
+
when q is of the form q1 + q2 (instead of being already factored) it
|
| 140 |
+
might be necessary to fall back on sympy.gcd.
|
| 141 |
+
"""
|
| 142 |
+
|
| 143 |
+
def integer_coefficient(x: sympy.Basic) -> int:
|
| 144 |
+
integer_coefficients: list[int] = [
|
| 145 |
+
abs(int(arg))
|
| 146 |
+
for arg in sympy.Mul.make_args(x)
|
| 147 |
+
if isinstance(arg, (int, sympy.Integer))
|
| 148 |
+
]
|
| 149 |
+
return math.prod(integer_coefficients)
|
| 150 |
+
|
| 151 |
+
def integer_factor(expr: sympy.Basic) -> int:
|
| 152 |
+
integer_factors: Iterable[int] = map(
|
| 153 |
+
integer_coefficient, sympy.Add.make_args(expr)
|
| 154 |
+
)
|
| 155 |
+
return functools.reduce(math.gcd, integer_factors)
|
| 156 |
+
|
| 157 |
+
gcd: int = math.gcd(integer_factor(p), integer_factor(q))
|
| 158 |
+
p, q = p / gcd, q / gcd # type: ignore[operator, assignment] # remove in py3.12
|
| 159 |
+
|
| 160 |
+
base_splits: list[tuple[sympy.Basic, ...]] = list(
|
| 161 |
+
map(sympy.Mul.make_args, sympy.Add.make_args(p))
|
| 162 |
+
)
|
| 163 |
+
divisor_split: tuple[sympy.Basic, ...] = sympy.Mul.make_args(q)
|
| 164 |
+
for x in divisor_split:
|
| 165 |
+
if all(x in base_split for base_split in base_splits):
|
| 166 |
+
gcd = gcd * x # type: ignore[operator] # remove in py3.12
|
| 167 |
+
return gcd # type: ignore[return-value] # remove in py3.12
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
# It would be nice to have assertions on whether or not inputs is_integer
|
| 171 |
+
# However, with bugs like https://github.com/sympy/sympy/issues/26620 sympy
|
| 172 |
+
# sometimes inconsistently reports floats an integers.
|
| 173 |
+
#
|
| 174 |
+
# What we can assume from sympy is that if something is an int, it
|
| 175 |
+
# definitely is is_integer, but if it is a float it may or may not
|
| 176 |
+
# be is_integer. So we are unable to do strong asserts that things
|
| 177 |
+
# are NOT integers.
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
# TODO: In Triton, // rounds to zero, but in Python, it is floor division.
|
| 181 |
+
# When we can prove both arguments are non-negative, we should just have a
|
| 182 |
+
# GenericFloorDiv (name pending) which can codegen efficiently in Python/C,
|
| 183 |
+
# and then PythonFloorDiv and CIntDiv which have the appropriate rounding
|
| 184 |
+
# semantics.
|
| 185 |
+
#
|
| 186 |
+
# Right now, FloorDiv de facto changes behavior if arguments are negative or
|
| 187 |
+
# not, this can potentially cause correctness issues.
|
| 188 |
+
class FloorDiv(sympy.Function):
|
| 189 |
+
"""
|
| 190 |
+
We maintain this so that:
|
| 191 |
+
1. We can use divisibility guards to simplify FloorDiv(a, b) to a / b.
|
| 192 |
+
2. Printing out the expression is nicer (compared to say, representing a//b as (a - a % b) / b)
|
| 193 |
+
|
| 194 |
+
NB: This is Python-style floor division, round to -Inf
|
| 195 |
+
"""
|
| 196 |
+
|
| 197 |
+
nargs: tuple[int, ...] = (2,)
|
| 198 |
+
precedence: int = 35 # lower precedence than add
|
| 199 |
+
is_integer: bool = True
|
| 200 |
+
|
| 201 |
+
@property
|
| 202 |
+
def base(self) -> sympy.Basic:
|
| 203 |
+
# pyrefly: ignore [missing-attribute]
|
| 204 |
+
return self.args[0]
|
| 205 |
+
|
| 206 |
+
@property
|
| 207 |
+
def divisor(self) -> sympy.Basic:
|
| 208 |
+
# pyrefly: ignore [missing-attribute]
|
| 209 |
+
return self.args[1]
|
| 210 |
+
|
| 211 |
+
def _sympystr(self, printer: sympy.printing.StrPrinter) -> str:
|
| 212 |
+
base = printer.parenthesize(self.base, PRECEDENCE["Atom"] - 0.5)
|
| 213 |
+
divisor = printer.parenthesize(self.divisor, PRECEDENCE["Atom"] - 0.5)
|
| 214 |
+
return f"({base}//{divisor})"
|
| 215 |
+
|
| 216 |
+
# Automatic evaluation.
|
| 217 |
+
# https://docs.sympy.org/latest/guides/custom-functions.html#best-practices-for-eval
|
| 218 |
+
@classmethod
|
| 219 |
+
def eval(cls, base: sympy.Integer, divisor: sympy.Integer) -> sympy.Basic | None:
|
| 220 |
+
# python test/test_dynamic_shapes.py -k TestDimConstraints.test_dim_constraints_solve_full
|
| 221 |
+
# Assert triggered by inequality solver
|
| 222 |
+
# assert base.is_integer, base
|
| 223 |
+
# assert divisor.is_integer, divisor
|
| 224 |
+
|
| 225 |
+
# We don't provide the same error message as in Python because SymPy
|
| 226 |
+
# makes it difficult to check the types.
|
| 227 |
+
if divisor.is_zero:
|
| 228 |
+
raise ZeroDivisionError("division by zero")
|
| 229 |
+
if base in (int_oo, -int_oo, sympy.oo, -sympy.oo) and divisor in (
|
| 230 |
+
int_oo,
|
| 231 |
+
-int_oo,
|
| 232 |
+
sympy.oo,
|
| 233 |
+
-sympy.oo,
|
| 234 |
+
):
|
| 235 |
+
return sympy.nan
|
| 236 |
+
if base is sympy.nan or divisor is sympy.nan:
|
| 237 |
+
return sympy.nan
|
| 238 |
+
|
| 239 |
+
if base.is_zero:
|
| 240 |
+
return sympy.S.Zero
|
| 241 |
+
if base.is_integer and equal_valued(divisor, 1):
|
| 242 |
+
return base
|
| 243 |
+
if base.is_integer and equal_valued(divisor, -1):
|
| 244 |
+
return sympy.Mul(base, -1)
|
| 245 |
+
if (
|
| 246 |
+
isinstance(base, sympy.Number)
|
| 247 |
+
and isinstance(divisor, sympy.Number)
|
| 248 |
+
and (
|
| 249 |
+
base in (int_oo, -int_oo, sympy.oo, -sympy.oo)
|
| 250 |
+
or divisor in (int_oo, -int_oo, sympy.oo, -sympy.oo)
|
| 251 |
+
)
|
| 252 |
+
):
|
| 253 |
+
r = float(base) / float(divisor)
|
| 254 |
+
if r == math.inf:
|
| 255 |
+
return int_oo
|
| 256 |
+
elif r == -math.inf:
|
| 257 |
+
return -int_oo
|
| 258 |
+
elif math.isnan(r):
|
| 259 |
+
return sympy.nan
|
| 260 |
+
else:
|
| 261 |
+
return sympy.Integer(math.floor(r))
|
| 262 |
+
if isinstance(base, sympy.Integer) and isinstance(divisor, sympy.Integer):
|
| 263 |
+
return sympy.Integer(int(base) // int(divisor))
|
| 264 |
+
if isinstance(base, FloorDiv):
|
| 265 |
+
return FloorDiv(base.args[0], base.args[1] * divisor)
|
| 266 |
+
|
| 267 |
+
# Expands (x + y) // b into x // b + y // b.
|
| 268 |
+
# This only works if floor is an identity, i.e. x / b is an integer.
|
| 269 |
+
if isinstance(divisor, sympy.Integer):
|
| 270 |
+
quotients = 0
|
| 271 |
+
terms = []
|
| 272 |
+
for term in sympy.Add.make_args(base):
|
| 273 |
+
quotient = term / divisor
|
| 274 |
+
|
| 275 |
+
# This is a sympy bug fixed in https://github.com/sympy/sympy/pull/28442
|
| 276 |
+
# sympy can generate a quotient with (1/22)*.... such that quotient.is_integer is True
|
| 277 |
+
# FloorDiv should not allow that as output. see
|
| 278 |
+
quotient_is_integer = None
|
| 279 |
+
if isinstance(quotient, sympy.Mul) and TorchVersion(
|
| 280 |
+
sympy.__version__
|
| 281 |
+
) < TorchVersion("1.15.0"):
|
| 282 |
+
rationals = quotient.atoms(sympy.Rational)
|
| 283 |
+
all_rationals_ints = all(r.q == 1 for r in rationals)
|
| 284 |
+
quotient_is_integer = quotient.is_integer and all_rationals_ints
|
| 285 |
+
else:
|
| 286 |
+
quotient_is_integer = quotient.is_integer
|
| 287 |
+
|
| 288 |
+
if quotient_is_integer:
|
| 289 |
+
terms.append(term)
|
| 290 |
+
quotients += quotient
|
| 291 |
+
|
| 292 |
+
if len(terms) != 0:
|
| 293 |
+
# Passing evaluate = False since expression will be optimized during the subtraction post its construction.
|
| 294 |
+
return (
|
| 295 |
+
FloorDiv(base - sympy.Add(*terms, evaluate=False), divisor)
|
| 296 |
+
+ quotients
|
| 297 |
+
)
|
| 298 |
+
|
| 299 |
+
try:
|
| 300 |
+
gcd = simple_floordiv_gcd(base, divisor)
|
| 301 |
+
if equal_valued(gcd, 1) and isinstance(divisor, sympy.Add):
|
| 302 |
+
gcd = sympy.gcd(base, divisor)
|
| 303 |
+
if not equal_valued(gcd, 1):
|
| 304 |
+
return FloorDiv(
|
| 305 |
+
sympy.simplify(base / gcd), sympy.simplify(divisor / gcd)
|
| 306 |
+
)
|
| 307 |
+
except sympy.PolynomialError:
|
| 308 |
+
pass # https://github.com/pytorch/pytorch/issues/108276
|
| 309 |
+
|
| 310 |
+
return None
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
class ModularIndexing(sympy.Function):
|
| 314 |
+
"""
|
| 315 |
+
ModularIndexing(a, b, c) => (a // b) % c where % is the C modulus
|
| 316 |
+
"""
|
| 317 |
+
|
| 318 |
+
nargs: tuple[int, ...] = (3,)
|
| 319 |
+
is_integer: bool = True
|
| 320 |
+
precedence: int = 35 # lower precedence than add
|
| 321 |
+
|
| 322 |
+
@classmethod
|
| 323 |
+
def eval(
|
| 324 |
+
cls, base: sympy.Integer, divisor: sympy.Integer, modulus: sympy.Integer
|
| 325 |
+
) -> sympy.Basic | None:
|
| 326 |
+
if base == 0 or modulus == 1:
|
| 327 |
+
return sympy.S.Zero
|
| 328 |
+
if (
|
| 329 |
+
isinstance(base, sympy.Integer)
|
| 330 |
+
and isinstance(divisor, sympy.Integer)
|
| 331 |
+
and isinstance(modulus, sympy.Integer)
|
| 332 |
+
):
|
| 333 |
+
return (base // divisor) % modulus
|
| 334 |
+
|
| 335 |
+
try:
|
| 336 |
+
if divisor != 1:
|
| 337 |
+
gcd = sympy.gcd(base, divisor)
|
| 338 |
+
if gcd != 1:
|
| 339 |
+
return ModularIndexing(
|
| 340 |
+
sympy.simplify(base / gcd),
|
| 341 |
+
sympy.simplify(divisor / gcd),
|
| 342 |
+
modulus,
|
| 343 |
+
)
|
| 344 |
+
except sympy.PolynomialError:
|
| 345 |
+
pass # https://github.com/pytorch/pytorch/issues/108276
|
| 346 |
+
|
| 347 |
+
if isinstance(base, sympy.Add):
|
| 348 |
+
new_terms: list[sympy.Integer] = []
|
| 349 |
+
all_positive: bool = True
|
| 350 |
+
for term in base.args:
|
| 351 |
+
if sympy.gcd(term, modulus * divisor) != modulus * divisor:
|
| 352 |
+
if (isinstance(term, sympy.Integer) and term < 0) or (
|
| 353 |
+
isinstance(term, sympy.Mul)
|
| 354 |
+
and isinstance(term.args[0], sympy.Integer)
|
| 355 |
+
and term.args[0] < 0
|
| 356 |
+
):
|
| 357 |
+
# workaround for https://github.com/triton-lang/triton/issues/619,
|
| 358 |
+
# if there are negative terms, // produces wrong result
|
| 359 |
+
# TODO if https://github.com/triton-lang/triton/issues/619 is fixed
|
| 360 |
+
# this optimization would become valid
|
| 361 |
+
all_positive = False
|
| 362 |
+
break
|
| 363 |
+
else:
|
| 364 |
+
new_terms.append(term)
|
| 365 |
+
|
| 366 |
+
if len(new_terms) != len(base.args) and all_positive:
|
| 367 |
+
return ModularIndexing(sum(new_terms), divisor, modulus)
|
| 368 |
+
|
| 369 |
+
if isinstance(base, FloorDiv):
|
| 370 |
+
return ModularIndexing(base.args[0], base.args[1] * divisor, modulus)
|
| 371 |
+
|
| 372 |
+
return None
|
| 373 |
+
|
| 374 |
+
def _eval_is_nonnegative(self) -> bool | None:
|
| 375 |
+
# pyrefly: ignore [missing-attribute]
|
| 376 |
+
p, q = self.args[:2]
|
| 377 |
+
return fuzzy_eq(p.is_nonnegative, q.is_nonnegative) # type: ignore[attr-defined]
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
class Where(sympy.Function):
|
| 381 |
+
"""
|
| 382 |
+
Good ol' ternary operator
|
| 383 |
+
"""
|
| 384 |
+
|
| 385 |
+
nargs: tuple[int, ...] = (3,)
|
| 386 |
+
precedence: int = 35 # lower precedence than add
|
| 387 |
+
|
| 388 |
+
def _eval_is_integer(self) -> bool | None:
|
| 389 |
+
return True if self.args[1].is_integer and self.args[2].is_integer else None # type: ignore[attr-defined]
|
| 390 |
+
|
| 391 |
+
def _eval_is_nonnegative(self) -> bool | None:
|
| 392 |
+
return (
|
| 393 |
+
True
|
| 394 |
+
if self.args[1].is_nonnegative and self.args[2].is_nonnegative # type: ignore[attr-defined]
|
| 395 |
+
else None
|
| 396 |
+
)
|
| 397 |
+
|
| 398 |
+
def _eval_is_positive(self) -> bool | None:
|
| 399 |
+
return True if self.args[1].is_positive and self.args[2].is_positive else None # type: ignore[attr-defined]
|
| 400 |
+
|
| 401 |
+
@classmethod
|
| 402 |
+
def eval(cls, c: sympy.Basic, p: sympy.Basic, q: sympy.Basic) -> sympy.Basic | None:
|
| 403 |
+
if c == sympy.true:
|
| 404 |
+
return p
|
| 405 |
+
elif c == sympy.false:
|
| 406 |
+
return q
|
| 407 |
+
return None
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
# Python-style modulus: take sign from RHS
|
| 411 |
+
class PythonMod(sympy.Function):
|
| 412 |
+
nargs: tuple[int, ...] = (2,)
|
| 413 |
+
|
| 414 |
+
precedence: int = 35 # lower precedence than add
|
| 415 |
+
is_integer: bool = True
|
| 416 |
+
|
| 417 |
+
@classmethod
|
| 418 |
+
def eval(cls, p: sympy.Expr, q: sympy.Expr) -> sympy.Expr | None:
|
| 419 |
+
# python test/dynamo/test_export.py -k ExportTests.test_trivial_constraint
|
| 420 |
+
# Triggered by sympy.solvers.inequalities.reduce_inequalities
|
| 421 |
+
# assert p.is_integer, p
|
| 422 |
+
# assert q.is_integer, q
|
| 423 |
+
|
| 424 |
+
if q.is_zero:
|
| 425 |
+
raise ZeroDivisionError("Modulo by zero")
|
| 426 |
+
|
| 427 |
+
# Three cases:
|
| 428 |
+
# 1. p == 0
|
| 429 |
+
# 2. p is either q or -q
|
| 430 |
+
# 3. p is integer and q == 1
|
| 431 |
+
if p is S.Zero or p in (q, -q) or q == 1:
|
| 432 |
+
return S.Zero
|
| 433 |
+
|
| 434 |
+
# Evaluate if they are both literals.
|
| 435 |
+
if q.is_Number and p.is_Number:
|
| 436 |
+
return p % q
|
| 437 |
+
|
| 438 |
+
# If q == 2, it's a matter of whether p is odd or even.
|
| 439 |
+
if q.is_Number and q == 2:
|
| 440 |
+
if p.is_even:
|
| 441 |
+
return S.Zero
|
| 442 |
+
if p.is_odd:
|
| 443 |
+
return S.One
|
| 444 |
+
|
| 445 |
+
# If p is a multiple of q.
|
| 446 |
+
r = p / q
|
| 447 |
+
if r.is_integer:
|
| 448 |
+
return S.Zero
|
| 449 |
+
|
| 450 |
+
# If p < q and its ratio is positive, then:
|
| 451 |
+
# - floor(p / q) = 0
|
| 452 |
+
# - p % q = p - floor(p / q) * q = p
|
| 453 |
+
less = p < q
|
| 454 |
+
# pyrefly: ignore [missing-attribute]
|
| 455 |
+
if less.is_Boolean and bool(less) and r.is_positive:
|
| 456 |
+
return p
|
| 457 |
+
|
| 458 |
+
if sympy.Mod(p, q) == 0:
|
| 459 |
+
return S.Zero
|
| 460 |
+
|
| 461 |
+
return None
|
| 462 |
+
|
| 463 |
+
# NB: args[1] for PythonMod
|
| 464 |
+
def _eval_is_nonnegative(self) -> bool | None:
|
| 465 |
+
return True if self.args[1].is_positive else None # type: ignore[attr-defined]
|
| 466 |
+
|
| 467 |
+
def _eval_is_nonpositive(self) -> bool | None:
|
| 468 |
+
return True if self.args[1].is_negative else None # type: ignore[attr-defined]
|
| 469 |
+
|
| 470 |
+
def _ccode(self, printer) -> str:
|
| 471 |
+
# pyrefly: ignore [missing-attribute]
|
| 472 |
+
p = printer.parenthesize(self.args[0], PRECEDENCE["Atom"] - 0.5)
|
| 473 |
+
# pyrefly: ignore [missing-attribute]
|
| 474 |
+
q = printer.parenthesize(self.args[1], PRECEDENCE["Atom"] - 0.5)
|
| 475 |
+
# pyrefly: ignore [missing-attribute]
|
| 476 |
+
abs_q = str(q) if self.args[1].is_positive else f"abs({q})"
|
| 477 |
+
return f"({p} % {q}) < 0 ? {p} % {q} + {abs_q} : {p} % {q}"
|
| 478 |
+
|
| 479 |
+
|
| 480 |
+
# Generic modulus: only defined on non-negative arguments
|
| 481 |
+
class Mod(sympy.Function):
|
| 482 |
+
nargs = (2,)
|
| 483 |
+
precedence: int = 35 # lower precedence than add
|
| 484 |
+
|
| 485 |
+
is_integer = True
|
| 486 |
+
is_nonnegative = True
|
| 487 |
+
|
| 488 |
+
@classmethod
|
| 489 |
+
def eval(cls, p, q):
|
| 490 |
+
# This was adapted from: sympy/core/mod.py
|
| 491 |
+
|
| 492 |
+
# Triggered by
|
| 493 |
+
# python test/test_dynamic_shapes.py -k TestDimConstraints.test_dim_constraints_solve_full
|
| 494 |
+
# assert p.is_integer, p
|
| 495 |
+
# assert q.is_integer, q
|
| 496 |
+
|
| 497 |
+
if q.is_zero:
|
| 498 |
+
raise ZeroDivisionError("Modulo by zero")
|
| 499 |
+
|
| 500 |
+
# Three cases:
|
| 501 |
+
# 1. p == 0
|
| 502 |
+
# 2. p is either q or -q
|
| 503 |
+
# 3. p is integer and q == 1
|
| 504 |
+
if p is S.Zero or p in (q, -q) or q == 1:
|
| 505 |
+
return S.Zero
|
| 506 |
+
|
| 507 |
+
# Evaluate if they are both literals.
|
| 508 |
+
if q.is_Number and p.is_Number:
|
| 509 |
+
if p < 0:
|
| 510 |
+
raise AssertionError(p)
|
| 511 |
+
if q < 1:
|
| 512 |
+
raise AssertionError(q)
|
| 513 |
+
return p % q
|
| 514 |
+
|
| 515 |
+
# If q == 2, it's a matter of whether p is odd or even.
|
| 516 |
+
if q.is_Number and q == 2:
|
| 517 |
+
if p.is_even:
|
| 518 |
+
return S.Zero
|
| 519 |
+
if p.is_odd:
|
| 520 |
+
return S.One
|
| 521 |
+
|
| 522 |
+
# If p is a multiple of q.
|
| 523 |
+
r = p / q
|
| 524 |
+
if r.is_integer:
|
| 525 |
+
return S.Zero
|
| 526 |
+
|
| 527 |
+
# If p < q and its ratio is positive, then:
|
| 528 |
+
# - floor(p / q) = 0
|
| 529 |
+
# - p % q = p - floor(p / q) * q = p
|
| 530 |
+
less = p < q
|
| 531 |
+
if less.is_Boolean and bool(less) and r.is_positive:
|
| 532 |
+
return p
|
| 533 |
+
|
| 534 |
+
|
| 535 |
+
class CleanDiv(FloorDiv):
|
| 536 |
+
"""
|
| 537 |
+
Div where we can assume no rounding.
|
| 538 |
+
This is to enable future optimizations.
|
| 539 |
+
"""
|
| 540 |
+
|
| 541 |
+
|
| 542 |
+
# Don't use sympy ceiling/floor as they will attempt simplifications involving
|
| 543 |
+
# frac
|
| 544 |
+
class CeilToInt(sympy.Function):
|
| 545 |
+
is_integer = True
|
| 546 |
+
|
| 547 |
+
@classmethod
|
| 548 |
+
def eval(cls, number):
|
| 549 |
+
# assert number.is_integer is not True, number
|
| 550 |
+
if number in (sympy.oo, int_oo):
|
| 551 |
+
return int_oo
|
| 552 |
+
if number in (-sympy.oo, -int_oo):
|
| 553 |
+
return -int_oo
|
| 554 |
+
if isinstance(number, sympy.Number):
|
| 555 |
+
return sympy.Integer(math.ceil(float(number)))
|
| 556 |
+
|
| 557 |
+
def _ccode(self, printer) -> str:
|
| 558 |
+
# pyrefly: ignore [missing-attribute]
|
| 559 |
+
number = printer.parenthesize(self.args[0], self.args[0].precedence - 0.5)
|
| 560 |
+
return f"ceil({number})"
|
| 561 |
+
|
| 562 |
+
|
| 563 |
+
class FloorToInt(sympy.Function):
|
| 564 |
+
is_integer = True
|
| 565 |
+
|
| 566 |
+
@classmethod
|
| 567 |
+
def eval(cls, number):
|
| 568 |
+
if number in (sympy.oo, int_oo):
|
| 569 |
+
return int_oo
|
| 570 |
+
if number in (-sympy.oo, int_oo):
|
| 571 |
+
return -int_oo
|
| 572 |
+
if isinstance(number, sympy.Integer):
|
| 573 |
+
return number
|
| 574 |
+
if isinstance(number, sympy.Number):
|
| 575 |
+
return sympy.Integer(math.floor(float(number)))
|
| 576 |
+
|
| 577 |
+
|
| 578 |
+
class CeilDiv(sympy.Function):
|
| 579 |
+
"""
|
| 580 |
+
Div used in indexing that rounds up.
|
| 581 |
+
"""
|
| 582 |
+
|
| 583 |
+
is_integer = True
|
| 584 |
+
|
| 585 |
+
def __new__(cls, base, divisor):
|
| 586 |
+
base = sympy.sympify(base)
|
| 587 |
+
divisor = sympy.sympify(divisor)
|
| 588 |
+
if sympy.gcd(base, divisor) == divisor:
|
| 589 |
+
return CleanDiv(base, divisor)
|
| 590 |
+
else:
|
| 591 |
+
return FloorDiv(base + (divisor - 1), divisor)
|
| 592 |
+
|
| 593 |
+
|
| 594 |
+
class LShift(sympy.Function):
|
| 595 |
+
is_integer = True
|
| 596 |
+
|
| 597 |
+
@classmethod
|
| 598 |
+
def eval(cls, base, shift):
|
| 599 |
+
if shift < 0:
|
| 600 |
+
raise ValueError("negative shift count")
|
| 601 |
+
return base * 2**shift
|
| 602 |
+
|
| 603 |
+
|
| 604 |
+
class RShift(sympy.Function):
|
| 605 |
+
is_integer = True
|
| 606 |
+
|
| 607 |
+
@classmethod
|
| 608 |
+
def eval(cls, base, shift):
|
| 609 |
+
if shift < 0:
|
| 610 |
+
raise ValueError("negative shift count")
|
| 611 |
+
return FloorDiv(base, 2**shift)
|
| 612 |
+
|
| 613 |
+
|
| 614 |
+
class MinMaxBase(Expr, LatticeOp): # type: ignore[misc]
|
| 615 |
+
def __new__(cls, *original_args, **assumptions):
|
| 616 |
+
from sympy.core.parameters import global_parameters
|
| 617 |
+
|
| 618 |
+
evaluate = assumptions.pop("evaluate", global_parameters.evaluate)
|
| 619 |
+
args = (sympify(arg) for arg in original_args)
|
| 620 |
+
|
| 621 |
+
# See the comment in _satisfy_unique_summations_symbols.
|
| 622 |
+
unique_summations_symbols = (
|
| 623 |
+
None
|
| 624 |
+
if not evaluate
|
| 625 |
+
else cls._satisfy_unique_summations_symbols(original_args)
|
| 626 |
+
)
|
| 627 |
+
|
| 628 |
+
if evaluate:
|
| 629 |
+
try:
|
| 630 |
+
# first standard filter, for cls.zero and cls.identity
|
| 631 |
+
# also reshape Max(a, Max(b, c)) to Max(a, b, c)
|
| 632 |
+
args = frozenset(cls._new_args_filter(args)) # type: ignore[assignment]
|
| 633 |
+
except ShortCircuit:
|
| 634 |
+
return cls.zero # type: ignore[attr-defined]
|
| 635 |
+
|
| 636 |
+
# No need to run _collapse_arguments and _find_localzeros, see the comment
|
| 637 |
+
# in _satisfy_unique_summations_symbols.
|
| 638 |
+
if unique_summations_symbols is None:
|
| 639 |
+
# remove redundant args that are easily identified
|
| 640 |
+
args = cls._collapse_arguments(args, **assumptions)
|
| 641 |
+
|
| 642 |
+
# find local zeros
|
| 643 |
+
args = cls._find_localzeros(args, **assumptions)
|
| 644 |
+
|
| 645 |
+
args = frozenset(args)
|
| 646 |
+
|
| 647 |
+
if not args:
|
| 648 |
+
return cls.identity # type: ignore[attr-defined]
|
| 649 |
+
|
| 650 |
+
if len(args) == 1:
|
| 651 |
+
return list(args).pop()
|
| 652 |
+
|
| 653 |
+
# base creation
|
| 654 |
+
obj = Expr.__new__(cls, *ordered(args), **assumptions)
|
| 655 |
+
obj._argset = args
|
| 656 |
+
|
| 657 |
+
obj.unique_summations_symbols = unique_summations_symbols
|
| 658 |
+
return obj
|
| 659 |
+
|
| 660 |
+
@classmethod
|
| 661 |
+
def _satisfy_unique_summations_symbols(
|
| 662 |
+
cls, args
|
| 663 |
+
) -> set[sympy.core.symbol.Symbol] | None:
|
| 664 |
+
"""
|
| 665 |
+
One common case in some models is building expressions of the form
|
| 666 |
+
max(max(max(a+b...), c+d), e+f) which is simplified to max(a+b, c+d, e+f, ...).
|
| 667 |
+
For such expressions, we call the Max constructor X times (once for each nested
|
| 668 |
+
max) and the expression gets flattened.
|
| 669 |
+
|
| 670 |
+
An expensive cost in constructing those expressions is running _collapse_arguments
|
| 671 |
+
and _find_localzeros. However, those two optimizations are unnecessary when the args
|
| 672 |
+
to max are all of the form a+b, c+d, ..etc where each term uses a unique set of symbols.
|
| 673 |
+
|
| 674 |
+
This function is used to detect such properties of the expressions we are building
|
| 675 |
+
and if so inform that we do not need to run those optimizations. To detect those,
|
| 676 |
+
we store a property in the expression that tells that this expression is a min/max
|
| 677 |
+
operation over terms that use unique symbols "unique_summations_symbols". This property
|
| 678 |
+
also memoize the set of symbols used in all the terms to make it faster to detect this
|
| 679 |
+
property inductively.
|
| 680 |
+
|
| 681 |
+
When we apply max to add a new term, all we need to do is check if the new term uses
|
| 682 |
+
unique symbols (with respect to existing terms and itself).
|
| 683 |
+
Example:
|
| 684 |
+
t = Max(a+b, c+d) ==> satisfies the property
|
| 685 |
+
Max(t, h+j) ==> h,j not in [a,b,c,d] => satisfy the property.
|
| 686 |
+
|
| 687 |
+
The function returns None if the new expression does not satisfy the unique_summations_symbols
|
| 688 |
+
property. Otherwise, it returns a new set of unique symbols.
|
| 689 |
+
"""
|
| 690 |
+
if len(args) != 2:
|
| 691 |
+
return None
|
| 692 |
+
|
| 693 |
+
(lhs, rhs) = (
|
| 694 |
+
(args[1], args[0])
|
| 695 |
+
if isinstance(args[1], MinMaxBase)
|
| 696 |
+
else (args[0], args[1])
|
| 697 |
+
)
|
| 698 |
+
|
| 699 |
+
if not _is_symbols_binary_summation(rhs):
|
| 700 |
+
return None
|
| 701 |
+
|
| 702 |
+
# base case max(a+b, c+d) ==> satisfies the property if a+b and c+d use unique symbols.
|
| 703 |
+
if _is_symbols_binary_summation(lhs):
|
| 704 |
+
return cls._unique_symbols(args)
|
| 705 |
+
|
| 706 |
+
# inductive case max(t, h+j) ==> satisfies the property if h, j not in t.unique_summations_symbols
|
| 707 |
+
if isinstance(lhs, MinMaxBase):
|
| 708 |
+
lhs_unique_summations_symbols = getattr(
|
| 709 |
+
lhs, "unique_summations_symbols", None
|
| 710 |
+
)
|
| 711 |
+
if lhs_unique_summations_symbols is not None:
|
| 712 |
+
return cls._unique_symbols([rhs], lhs_unique_summations_symbols)
|
| 713 |
+
|
| 714 |
+
return None
|
| 715 |
+
|
| 716 |
+
@classmethod
|
| 717 |
+
def _unique_symbols(
|
| 718 |
+
cls, args, initial_set: set[sympy.core.symbol.Symbol] | None = None
|
| 719 |
+
) -> set[sympy.core.symbol.Symbol] | None:
|
| 720 |
+
"""
|
| 721 |
+
Return seen_symbols if all atoms in all args are all unique symbols,
|
| 722 |
+
else returns None. initial_set can be used to represent initial value for seen_symbols
|
| 723 |
+
"""
|
| 724 |
+
seen_symbols = set() if initial_set is None else initial_set
|
| 725 |
+
for arg in args:
|
| 726 |
+
for element in arg.atoms():
|
| 727 |
+
if not isinstance(element, sympy.core.symbol.Symbol):
|
| 728 |
+
return None
|
| 729 |
+
elif element in seen_symbols:
|
| 730 |
+
return None
|
| 731 |
+
else:
|
| 732 |
+
seen_symbols.add(element)
|
| 733 |
+
return seen_symbols
|
| 734 |
+
|
| 735 |
+
@classmethod
|
| 736 |
+
def _collapse_arguments(cls, args, **assumptions):
|
| 737 |
+
"""Remove redundant args.
|
| 738 |
+
|
| 739 |
+
Examples
|
| 740 |
+
========
|
| 741 |
+
|
| 742 |
+
>>> from sympy import Min, Max
|
| 743 |
+
>>> from sympy.abc import a, b, c, d, e
|
| 744 |
+
|
| 745 |
+
Any arg in parent that appears in any
|
| 746 |
+
parent-like function in any of the flat args
|
| 747 |
+
of parent can be removed from that sub-arg:
|
| 748 |
+
|
| 749 |
+
>>> Min(a, Max(b, Min(a, c, d)))
|
| 750 |
+
Min(a, Max(b, Min(c, d)))
|
| 751 |
+
|
| 752 |
+
If the arg of parent appears in an opposite-than parent
|
| 753 |
+
function in any of the flat args of parent that function
|
| 754 |
+
can be replaced with the arg:
|
| 755 |
+
|
| 756 |
+
>>> Min(a, Max(b, Min(c, d, Max(a, e))))
|
| 757 |
+
Min(a, Max(b, Min(a, c, d)))
|
| 758 |
+
"""
|
| 759 |
+
if not args:
|
| 760 |
+
return args
|
| 761 |
+
args = list(ordered(args))
|
| 762 |
+
if cls is Min:
|
| 763 |
+
other = Max
|
| 764 |
+
else:
|
| 765 |
+
other = Min # type: ignore[assignment]
|
| 766 |
+
|
| 767 |
+
# find global comparable max of Max and min of Min if a new
|
| 768 |
+
# value is being introduced in these args at position 0 of
|
| 769 |
+
# the ordered args
|
| 770 |
+
if args[0].is_number:
|
| 771 |
+
sifted = mins, maxs = [], [] # type: ignore[var-annotated]
|
| 772 |
+
for i in args:
|
| 773 |
+
for v in walk(i, Min, Max):
|
| 774 |
+
if v.args[0].is_comparable:
|
| 775 |
+
sifted[isinstance(v, Max)].append(v)
|
| 776 |
+
small = Min.identity
|
| 777 |
+
for i in mins:
|
| 778 |
+
v = i.args[0]
|
| 779 |
+
if v.is_number and (v < small) == True: # noqa: E712
|
| 780 |
+
small = v
|
| 781 |
+
big = Max.identity
|
| 782 |
+
for i in maxs:
|
| 783 |
+
v = i.args[0]
|
| 784 |
+
if v.is_number and (v > big) == True: # noqa: E712
|
| 785 |
+
big = v
|
| 786 |
+
# at the point when this function is called from __new__,
|
| 787 |
+
# there may be more than one numeric arg present since
|
| 788 |
+
# local zeros have not been handled yet, so look through
|
| 789 |
+
# more than the first arg
|
| 790 |
+
if cls is Min:
|
| 791 |
+
for arg in args:
|
| 792 |
+
if not arg.is_number:
|
| 793 |
+
break
|
| 794 |
+
if (arg < small) == True: # noqa: E712
|
| 795 |
+
small = arg
|
| 796 |
+
elif cls == Max:
|
| 797 |
+
for arg in args:
|
| 798 |
+
if not arg.is_number:
|
| 799 |
+
break
|
| 800 |
+
if (arg > big) == True: # noqa: E712
|
| 801 |
+
big = arg
|
| 802 |
+
T = None
|
| 803 |
+
if cls is Min:
|
| 804 |
+
if small != Min.identity:
|
| 805 |
+
other = Max
|
| 806 |
+
T = small
|
| 807 |
+
elif big != Max.identity:
|
| 808 |
+
other = Min # type: ignore[assignment]
|
| 809 |
+
T = big
|
| 810 |
+
if T is not None:
|
| 811 |
+
# remove numerical redundancy
|
| 812 |
+
for i in range(len(args)):
|
| 813 |
+
a = args[i]
|
| 814 |
+
if isinstance(a, other):
|
| 815 |
+
a0 = a.args[0]
|
| 816 |
+
if ( # noqa: E712
|
| 817 |
+
(a0 > T) if other == Max else (a0 < T) # noqa: E712
|
| 818 |
+
) == True: # noqa: E712
|
| 819 |
+
args[i] = cls.identity # type: ignore[attr-defined]
|
| 820 |
+
|
| 821 |
+
# remove redundant symbolic args
|
| 822 |
+
def do(ai, a):
|
| 823 |
+
if not isinstance(ai, (Min, Max)):
|
| 824 |
+
return ai
|
| 825 |
+
cond = a in ai.args
|
| 826 |
+
if not cond:
|
| 827 |
+
return ai.func(*[do(i, a) for i in ai.args], evaluate=False)
|
| 828 |
+
if isinstance(ai, cls):
|
| 829 |
+
# pyrefly: ignore [missing-attribute]
|
| 830 |
+
return ai.func(*[do(i, a) for i in ai.args if i != a], evaluate=False)
|
| 831 |
+
return a
|
| 832 |
+
|
| 833 |
+
for i, a in enumerate(args):
|
| 834 |
+
args[i + 1 :] = [do(ai, a) for ai in args[i + 1 :]]
|
| 835 |
+
|
| 836 |
+
# factor out common elements as for
|
| 837 |
+
# Min(Max(x, y), Max(x, z)) -> Max(x, Min(y, z))
|
| 838 |
+
# and vice versa when swapping Min/Max -- do this only for the
|
| 839 |
+
# easy case where all functions contain something in common;
|
| 840 |
+
# trying to find some optimal subset of args to modify takes
|
| 841 |
+
# too long
|
| 842 |
+
|
| 843 |
+
def factor_minmax(args):
|
| 844 |
+
is_other = lambda arg: isinstance(arg, other) # noqa: E731
|
| 845 |
+
other_args, remaining_args = sift(args, is_other, binary=True)
|
| 846 |
+
if not other_args:
|
| 847 |
+
return args
|
| 848 |
+
|
| 849 |
+
# Min(Max(x, y, z), Max(x, y, u, v)) -> {x,y}, ({z}, {u,v})
|
| 850 |
+
arg_sets = [set(arg.args) for arg in other_args]
|
| 851 |
+
common = set.intersection(*arg_sets)
|
| 852 |
+
if not common:
|
| 853 |
+
return args
|
| 854 |
+
|
| 855 |
+
new_other_args = list(common)
|
| 856 |
+
arg_sets_diff = [arg_set - common for arg_set in arg_sets]
|
| 857 |
+
|
| 858 |
+
# If any set is empty after removing common then all can be
|
| 859 |
+
# discarded e.g. Min(Max(a, b, c), Max(a, b)) -> Max(a, b)
|
| 860 |
+
if all(arg_sets_diff):
|
| 861 |
+
other_args_diff = [other(*s, evaluate=False) for s in arg_sets_diff]
|
| 862 |
+
new_other_args.append(cls(*other_args_diff, evaluate=False))
|
| 863 |
+
|
| 864 |
+
other_args_factored = other(*new_other_args, evaluate=False)
|
| 865 |
+
return remaining_args + [other_args_factored]
|
| 866 |
+
|
| 867 |
+
if len(args) > 1:
|
| 868 |
+
args = factor_minmax(args)
|
| 869 |
+
|
| 870 |
+
return args
|
| 871 |
+
|
| 872 |
+
@classmethod
|
| 873 |
+
def _new_args_filter(cls, arg_sequence):
|
| 874 |
+
"""
|
| 875 |
+
Generator filtering args.
|
| 876 |
+
|
| 877 |
+
first standard filter, for cls.zero and cls.identity.
|
| 878 |
+
Also reshape ``Max(a, Max(b, c))`` to ``Max(a, b, c)``,
|
| 879 |
+
and check arguments for comparability
|
| 880 |
+
"""
|
| 881 |
+
for arg in arg_sequence:
|
| 882 |
+
# pre-filter, checking comparability of arguments
|
| 883 |
+
if (
|
| 884 |
+
not isinstance(arg, Expr)
|
| 885 |
+
or arg.is_extended_real is False
|
| 886 |
+
or (arg.is_number and not arg.is_comparable)
|
| 887 |
+
):
|
| 888 |
+
raise ValueError(f"The argument '{arg}' is not comparable.")
|
| 889 |
+
|
| 890 |
+
if arg == cls.zero: # type: ignore[attr-defined]
|
| 891 |
+
raise ShortCircuit(arg)
|
| 892 |
+
elif arg == cls.identity: # type: ignore[attr-defined]
|
| 893 |
+
continue
|
| 894 |
+
elif arg.func == cls:
|
| 895 |
+
yield from arg.args
|
| 896 |
+
else:
|
| 897 |
+
yield arg
|
| 898 |
+
|
| 899 |
+
@classmethod
|
| 900 |
+
def _find_localzeros(cls, values, **options):
|
| 901 |
+
"""
|
| 902 |
+
Sequentially allocate values to localzeros.
|
| 903 |
+
|
| 904 |
+
When a value is identified as being more extreme than another member it
|
| 905 |
+
replaces that member; if this is never true, then the value is simply
|
| 906 |
+
appended to the localzeros.
|
| 907 |
+
|
| 908 |
+
Unlike the sympy implementation, we only look for zero and one, we don't
|
| 909 |
+
do generic is connected test pairwise which is slow
|
| 910 |
+
"""
|
| 911 |
+
|
| 912 |
+
# First, collapse all numeric arguments
|
| 913 |
+
other_values = set()
|
| 914 |
+
num_value = None
|
| 915 |
+
for arg in values:
|
| 916 |
+
if arg.is_Number:
|
| 917 |
+
if num_value is None:
|
| 918 |
+
num_value = arg
|
| 919 |
+
else:
|
| 920 |
+
if cls is Max:
|
| 921 |
+
num_value = max(num_value, arg)
|
| 922 |
+
elif cls is Min:
|
| 923 |
+
num_value = min(num_value, arg)
|
| 924 |
+
else:
|
| 925 |
+
raise AssertionError(f"impossible {cls}")
|
| 926 |
+
else:
|
| 927 |
+
other_values.add(arg)
|
| 928 |
+
|
| 929 |
+
# Special cases when there is only one symbolic value
|
| 930 |
+
if num_value is None:
|
| 931 |
+
return other_values
|
| 932 |
+
|
| 933 |
+
if len(other_values) == 0:
|
| 934 |
+
return {num_value}
|
| 935 |
+
|
| 936 |
+
if len(other_values) == 1:
|
| 937 |
+
other_value = next(iter(other_values))
|
| 938 |
+
if num_value in (0.0, 0) and other_value.is_nonnegative:
|
| 939 |
+
return other_values if cls is Max else {num_value}
|
| 940 |
+
if num_value == 1 and other_value.is_positive:
|
| 941 |
+
return other_values if cls is Max else {num_value}
|
| 942 |
+
|
| 943 |
+
other_values.add(num_value)
|
| 944 |
+
return other_values
|
| 945 |
+
|
| 946 |
+
_eval_is_algebraic = lambda s: _torf(i.is_algebraic for i in s.args) # noqa: E731
|
| 947 |
+
_eval_is_antihermitian = lambda s: _torf( # noqa: E731
|
| 948 |
+
i.is_antihermitian
|
| 949 |
+
for i in s.args # noqa: E731
|
| 950 |
+
) # noqa: E731
|
| 951 |
+
_eval_is_commutative = lambda s: _torf( # noqa: E731
|
| 952 |
+
i.is_commutative
|
| 953 |
+
for i in s.args # noqa: E731
|
| 954 |
+
) # noqa: E731
|
| 955 |
+
_eval_is_complex = lambda s: _torf(i.is_complex for i in s.args) # noqa: E731
|
| 956 |
+
_eval_is_composite = lambda s: _torf(i.is_composite for i in s.args) # noqa: E731
|
| 957 |
+
_eval_is_even = lambda s: _torf(i.is_even for i in s.args) # noqa: E731
|
| 958 |
+
_eval_is_finite = lambda s: _torf(i.is_finite for i in s.args) # noqa: E731
|
| 959 |
+
_eval_is_hermitian = lambda s: _torf(i.is_hermitian for i in s.args) # noqa: E731
|
| 960 |
+
_eval_is_imaginary = lambda s: _torf(i.is_imaginary for i in s.args) # noqa: E731
|
| 961 |
+
_eval_is_infinite = lambda s: _torf(i.is_infinite for i in s.args) # noqa: E731
|
| 962 |
+
_eval_is_integer = lambda s: _torf(i.is_integer for i in s.args) # noqa: E731
|
| 963 |
+
_eval_is_irrational = lambda s: _torf(i.is_irrational for i in s.args) # noqa: E731
|
| 964 |
+
_eval_is_negative = lambda s: _torf(i.is_negative for i in s.args) # noqa: E731
|
| 965 |
+
_eval_is_noninteger = lambda s: _torf(i.is_noninteger for i in s.args) # noqa: E731
|
| 966 |
+
_eval_is_nonnegative = lambda s: _torf( # noqa: E731
|
| 967 |
+
i.is_nonnegative
|
| 968 |
+
for i in s.args # noqa: E731
|
| 969 |
+
) # noqa: E731
|
| 970 |
+
_eval_is_nonpositive = lambda s: _torf( # noqa: E731
|
| 971 |
+
i.is_nonpositive
|
| 972 |
+
for i in s.args # noqa: E731
|
| 973 |
+
) # noqa: E731
|
| 974 |
+
_eval_is_nonzero = lambda s: _torf(i.is_nonzero for i in s.args) # noqa: E731
|
| 975 |
+
_eval_is_odd = lambda s: _torf(i.is_odd for i in s.args) # noqa: E731
|
| 976 |
+
_eval_is_polar = lambda s: _torf(i.is_polar for i in s.args) # noqa: E731
|
| 977 |
+
_eval_is_positive = lambda s: _torf(i.is_positive for i in s.args) # noqa: E731
|
| 978 |
+
_eval_is_prime = lambda s: _torf(i.is_prime for i in s.args) # noqa: E731
|
| 979 |
+
_eval_is_rational = lambda s: _torf(i.is_rational for i in s.args) # noqa: E731
|
| 980 |
+
_eval_is_real = lambda s: _torf(i.is_real for i in s.args) # noqa: E731
|
| 981 |
+
_eval_is_extended_real = lambda s: _torf( # noqa: E731
|
| 982 |
+
i.is_extended_real
|
| 983 |
+
for i in s.args # noqa: E731
|
| 984 |
+
) # noqa: E731
|
| 985 |
+
_eval_is_transcendental = lambda s: _torf( # noqa: E731
|
| 986 |
+
i.is_transcendental
|
| 987 |
+
for i in s.args # noqa: E731
|
| 988 |
+
) # noqa: E731
|
| 989 |
+
_eval_is_zero = lambda s: _torf(i.is_zero for i in s.args) # noqa: E731
|
| 990 |
+
|
| 991 |
+
|
| 992 |
+
class Max(MinMaxBase, Application): # type: ignore[misc]
|
| 993 |
+
r"""
|
| 994 |
+
Return, if possible, the maximum value of the list.
|
| 995 |
+
"""
|
| 996 |
+
|
| 997 |
+
zero = S.Infinity
|
| 998 |
+
identity = S.NegativeInfinity
|
| 999 |
+
|
| 1000 |
+
def _eval_is_positive(self): # type:ignore[override]
|
| 1001 |
+
return fuzzy_or(a.is_positive for a in self.args) # type: ignore[attr-defined]
|
| 1002 |
+
|
| 1003 |
+
def _eval_is_nonnegative(self): # type:ignore[override]
|
| 1004 |
+
return fuzzy_or(a.is_nonnegative for a in self.args) # type: ignore[attr-defined]
|
| 1005 |
+
|
| 1006 |
+
def _eval_is_negative(self): # type:ignore[override]
|
| 1007 |
+
# pyrefly: ignore [missing-attribute]
|
| 1008 |
+
return fuzzy_and(a.is_negative for a in self.args)
|
| 1009 |
+
|
| 1010 |
+
|
| 1011 |
+
class Min(MinMaxBase, Application): # type: ignore[misc]
|
| 1012 |
+
"""
|
| 1013 |
+
Return, if possible, the minimum value of the list.
|
| 1014 |
+
"""
|
| 1015 |
+
|
| 1016 |
+
zero = S.NegativeInfinity
|
| 1017 |
+
identity = S.Infinity
|
| 1018 |
+
|
| 1019 |
+
def _eval_is_positive(self): # type:ignore[override]
|
| 1020 |
+
return fuzzy_and(a.is_positive for a in self.args) # type: ignore[attr-defined]
|
| 1021 |
+
|
| 1022 |
+
def _eval_is_nonnegative(self): # type:ignore[override]
|
| 1023 |
+
return fuzzy_and(a.is_nonnegative for a in self.args) # type: ignore[attr-defined]
|
| 1024 |
+
|
| 1025 |
+
def _eval_is_negative(self): # type:ignore[override]
|
| 1026 |
+
# pyrefly: ignore [missing-attribute]
|
| 1027 |
+
return fuzzy_or(a.is_negative for a in self.args)
|
| 1028 |
+
|
| 1029 |
+
|
| 1030 |
+
def safe_pow(base, exp):
|
| 1031 |
+
sign = 1
|
| 1032 |
+
if base < 0:
|
| 1033 |
+
base = -base
|
| 1034 |
+
sign = 1 if exp % 2 == 0 else -1
|
| 1035 |
+
return sign * _safe_pow(base, exp)
|
| 1036 |
+
|
| 1037 |
+
|
| 1038 |
+
# Prevent people from overflowing pow
|
| 1039 |
+
def _safe_pow(base, exponent):
|
| 1040 |
+
if exponent < 0:
|
| 1041 |
+
raise ValueError("Exponent must be non-negative.")
|
| 1042 |
+
|
| 1043 |
+
if exponent == 0:
|
| 1044 |
+
return 1
|
| 1045 |
+
|
| 1046 |
+
half_exp = safe_pow(base, exponent // 2)
|
| 1047 |
+
if half_exp is int_oo:
|
| 1048 |
+
return int_oo
|
| 1049 |
+
|
| 1050 |
+
# TODO: microoptimization is to avoid overflowing into arbitrary precision
|
| 1051 |
+
# and detect overflow prior to doing operations
|
| 1052 |
+
|
| 1053 |
+
result = half_exp * half_exp
|
| 1054 |
+
if result > sys.maxsize:
|
| 1055 |
+
return int_oo
|
| 1056 |
+
|
| 1057 |
+
if exponent % 2 == 1:
|
| 1058 |
+
result *= base
|
| 1059 |
+
if result > sys.maxsize:
|
| 1060 |
+
return int_oo
|
| 1061 |
+
|
| 1062 |
+
return result
|
| 1063 |
+
|
| 1064 |
+
|
| 1065 |
+
class PowByNatural(sympy.Function):
|
| 1066 |
+
is_integer = True
|
| 1067 |
+
|
| 1068 |
+
precedence: int = 50 # precedence of mul
|
| 1069 |
+
|
| 1070 |
+
@classmethod
|
| 1071 |
+
def eval(cls, base, exp):
|
| 1072 |
+
if isinstance(base, sympy.Integer) and isinstance(exp, sympy.Integer):
|
| 1073 |
+
r = safe_pow(base, exp)
|
| 1074 |
+
if r in (-int_oo, int_oo):
|
| 1075 |
+
return r
|
| 1076 |
+
return sympy.Integer(r)
|
| 1077 |
+
if isinstance(exp, sympy.Integer):
|
| 1078 |
+
# Rely on regular sympy Pow for this (note that iterated
|
| 1079 |
+
# multiplication turns into a Pow anyway, you can't escape!!)
|
| 1080 |
+
return sympy.Pow(base, exp)
|
| 1081 |
+
if exp in (int_oo, sympy.oo):
|
| 1082 |
+
if base.is_nonnegative:
|
| 1083 |
+
return int_oo
|
| 1084 |
+
elif base.is_negative:
|
| 1085 |
+
return sympy.zoo # this is apparently what (-2)**sympy.oo does
|
| 1086 |
+
# NB: do NOT translate into sympy.Pow, we will lose knowledge that exp
|
| 1087 |
+
# is a natural number if we do
|
| 1088 |
+
|
| 1089 |
+
|
| 1090 |
+
# base is assumed to be nonnegative, thereby prevent complex numbers from
|
| 1091 |
+
# occurring
|
| 1092 |
+
class FloatPow(sympy.Function):
|
| 1093 |
+
is_real = True
|
| 1094 |
+
|
| 1095 |
+
precedence: int = 60 # precedence of pow
|
| 1096 |
+
|
| 1097 |
+
@classmethod
|
| 1098 |
+
def eval(cls, base, exp):
|
| 1099 |
+
# NB: These test sympy.Number, not sympy.Float, because:
|
| 1100 |
+
# - Sometimes we may have sympy.oo or int_oo, and that's not a Float
|
| 1101 |
+
# (but coerces to math.Inf)
|
| 1102 |
+
# - Sometimes Float(0.0) will unpredictably decay to Integer(0),
|
| 1103 |
+
# but we should still accept it in floatey contexts
|
| 1104 |
+
if isinstance(base, sympy.Number) and isinstance(exp, sympy.Number):
|
| 1105 |
+
return sympy.Float(float(base) ** float(exp))
|
| 1106 |
+
# NB: do not do any nontrivial reasoning
|
| 1107 |
+
|
| 1108 |
+
|
| 1109 |
+
# Overloaded to be compatible with regular Python.
|
| 1110 |
+
# https://github.com/pytorch/pytorch/issues/90900
|
| 1111 |
+
#
|
| 1112 |
+
# In particular, sympy division is willing to simplify x/x == 1
|
| 1113 |
+
# where 1 is an integer, but this must be a float if x was float.
|
| 1114 |
+
class FloatTrueDiv(sympy.Function):
|
| 1115 |
+
is_real = True
|
| 1116 |
+
|
| 1117 |
+
precedence: int = 35 # lower precedence than add
|
| 1118 |
+
|
| 1119 |
+
@classmethod
|
| 1120 |
+
def eval(cls, base, divisor):
|
| 1121 |
+
# assert base.is_integer is not True, base
|
| 1122 |
+
# assert divisor.is_integer is not True, divisor
|
| 1123 |
+
|
| 1124 |
+
if divisor.is_zero:
|
| 1125 |
+
raise ZeroDivisionError("division by zero")
|
| 1126 |
+
|
| 1127 |
+
if isinstance(base, sympy.Number) and isinstance(divisor, sympy.Number):
|
| 1128 |
+
return sympy.Float(float(base) / float(divisor))
|
| 1129 |
+
|
| 1130 |
+
|
| 1131 |
+
# Overloaded to be compatible with regular Python. We distinguish this from
|
| 1132 |
+
# FloatTrueDiv, because the code generation has to be different for this case:
|
| 1133 |
+
# Python has a fancy algorithm for integer true division that isn't just
|
| 1134 |
+
# "promote both arguments to float and use float division", so you need to
|
| 1135 |
+
# codegen it differently. While technically you can work it out from the
|
| 1136 |
+
# types of the input, this is often inconvenient to do in Inductor codegen,
|
| 1137 |
+
# so just have a different operator
|
| 1138 |
+
# NB: Right now, Inductor codegen doesn't implement this correctly lol
|
| 1139 |
+
class IntTrueDiv(sympy.Function):
|
| 1140 |
+
is_real = True
|
| 1141 |
+
|
| 1142 |
+
precedence: int = 35 # lower precedence than add
|
| 1143 |
+
|
| 1144 |
+
@classmethod
|
| 1145 |
+
def eval(cls, base, divisor):
|
| 1146 |
+
if divisor.is_zero:
|
| 1147 |
+
raise ZeroDivisionError("division by zero")
|
| 1148 |
+
|
| 1149 |
+
if (
|
| 1150 |
+
isinstance(base, sympy.Number)
|
| 1151 |
+
and isinstance(divisor, sympy.Number)
|
| 1152 |
+
and (
|
| 1153 |
+
base in (int_oo, -int_oo, sympy.oo, -sympy.oo)
|
| 1154 |
+
or divisor in (int_oo, -int_oo, sympy.oo, -sympy.oo)
|
| 1155 |
+
)
|
| 1156 |
+
):
|
| 1157 |
+
# Don't have to worry about precision here, you're getting zero or
|
| 1158 |
+
# inf from the division
|
| 1159 |
+
return sympy.Float(float(base) / float(divisor))
|
| 1160 |
+
if isinstance(base, sympy.Integer) and isinstance(divisor, sympy.Integer):
|
| 1161 |
+
return sympy.Float(int(base) / int(divisor))
|
| 1162 |
+
|
| 1163 |
+
def _ccode(self, printer) -> str:
|
| 1164 |
+
# pyrefly: ignore [missing-attribute]
|
| 1165 |
+
base = printer.parenthesize(self.args[0], PRECEDENCE["Atom"] - 0.5)
|
| 1166 |
+
# pyrefly: ignore [missing-attribute]
|
| 1167 |
+
divisor = printer.parenthesize(self.args[1], PRECEDENCE["Atom"] - 0.5)
|
| 1168 |
+
return f"((int){base}/(int){divisor})"
|
| 1169 |
+
|
| 1170 |
+
|
| 1171 |
+
# TODO: As an indicator, this != 0 implies == 1 (and vice versa).
|
| 1172 |
+
# Because we do not have the ability to guard on the stride permutation
|
| 1173 |
+
# at the moment, it is hard to make further inferences when this is true,
|
| 1174 |
+
# as although we know the tensor is contiguous in *some* layout, we don't
|
| 1175 |
+
# know which one (however, you could, for example, make the inference that
|
| 1176 |
+
# reshaping this to a 1D tensor can be guard-free.)
|
| 1177 |
+
class IsNonOverlappingAndDenseIndicator(sympy.Function):
|
| 1178 |
+
is_integer = True
|
| 1179 |
+
|
| 1180 |
+
@classmethod
|
| 1181 |
+
def eval(cls, *args):
|
| 1182 |
+
if len(args) % 2 != 0:
|
| 1183 |
+
raise AssertionError(
|
| 1184 |
+
f"expected an even number of arguments, got {len(args)}"
|
| 1185 |
+
)
|
| 1186 |
+
dim = len(args) // 2
|
| 1187 |
+
sizes = args[0:dim]
|
| 1188 |
+
strides = args[dim:]
|
| 1189 |
+
|
| 1190 |
+
# sym_node imported in torch.__init__. Local import to avoid an import cycle
|
| 1191 |
+
from torch.fx.experimental.symbolic_shapes import (
|
| 1192 |
+
eval_is_non_overlapping_and_dense,
|
| 1193 |
+
)
|
| 1194 |
+
|
| 1195 |
+
if all(isinstance(a, sympy.Integer) for a in args):
|
| 1196 |
+
return eval_is_non_overlapping_and_dense(
|
| 1197 |
+
[int(a) for a in sizes], [int(a) for a in strides]
|
| 1198 |
+
)
|
| 1199 |
+
|
| 1200 |
+
if dim == 1:
|
| 1201 |
+
# Manually implement the rank one short circuit
|
| 1202 |
+
if strides[0].is_Number and strides[0] == 1:
|
| 1203 |
+
return 1
|
| 1204 |
+
|
| 1205 |
+
if sizes[0].is_Number and sizes[0] < 2:
|
| 1206 |
+
return 1
|
| 1207 |
+
|
| 1208 |
+
# return 0 case covered by case above
|
| 1209 |
+
|
| 1210 |
+
# TODO: Inability to access size-obliviousness sucks: if we have a
|
| 1211 |
+
# size oblivious test on a size-like unbacked SymInt, we could
|
| 1212 |
+
# confidently return zero when we have a size-like u0 stride
|
| 1213 |
+
# and a size-like u1 size. Maybe a fancy ValueRanges analysis for
|
| 1214 |
+
# this function could help figure this out.
|
| 1215 |
+
|
| 1216 |
+
if all(isinstance(a, sympy.Integer) for a in strides):
|
| 1217 |
+
if dim == 0:
|
| 1218 |
+
raise AssertionError("dim must not be zero")
|
| 1219 |
+
# When all strides are integral, we can sort, and the size for the
|
| 1220 |
+
# largest stride doesn't matter and can be arbitrarily symbolic
|
| 1221 |
+
s_sizes, s_strides = zip(
|
| 1222 |
+
*sorted(zip(sizes, strides, strict=True), key=operator.itemgetter(1)),
|
| 1223 |
+
strict=True,
|
| 1224 |
+
)
|
| 1225 |
+
# Put something arbitrary in the max size spot, it'll be ignored
|
| 1226 |
+
if all(isinstance(a, sympy.Integer) for a in s_sizes[:-1]):
|
| 1227 |
+
s_sizes = s_sizes[:-1] + (42,)
|
| 1228 |
+
# We can reuse the regular eval, because it is invariant to
|
| 1229 |
+
# permutation of dimensions
|
| 1230 |
+
return eval_is_non_overlapping_and_dense(
|
| 1231 |
+
[int(a) for a in s_sizes], [int(a) for a in s_strides]
|
| 1232 |
+
)
|
| 1233 |
+
|
| 1234 |
+
return None
|
| 1235 |
+
|
| 1236 |
+
|
| 1237 |
+
# NB: this is inconsistent with math.trunc in Python
|
| 1238 |
+
class TruncToFloat(sympy.Function):
|
| 1239 |
+
is_real = True
|
| 1240 |
+
|
| 1241 |
+
@classmethod
|
| 1242 |
+
def eval(cls, number):
|
| 1243 |
+
# assert number.is_integer is not True, number
|
| 1244 |
+
if isinstance(number, sympy.Number):
|
| 1245 |
+
# NB: It is safe to use truncation to integer, which is what
|
| 1246 |
+
# math.trunc does, as Python integers are arbitrary precision and
|
| 1247 |
+
# so we are guaranteed not to lose precision when we do this
|
| 1248 |
+
return sympy.Float(math.trunc(float(number)))
|
| 1249 |
+
|
| 1250 |
+
|
| 1251 |
+
class TruncToInt(sympy.Function):
|
| 1252 |
+
is_integer = True
|
| 1253 |
+
|
| 1254 |
+
@classmethod
|
| 1255 |
+
def eval(cls, number):
|
| 1256 |
+
# assert number.is_integer is not True, number
|
| 1257 |
+
if number in (sympy.oo, int_oo):
|
| 1258 |
+
return int_oo
|
| 1259 |
+
if number in (-sympy.oo, -int_oo):
|
| 1260 |
+
return -int_oo
|
| 1261 |
+
if isinstance(number, sympy.Number):
|
| 1262 |
+
return sympy.Integer(math.trunc(float(number)))
|
| 1263 |
+
|
| 1264 |
+
|
| 1265 |
+
# This is float -> int
|
| 1266 |
+
class RoundToInt(sympy.Function):
|
| 1267 |
+
is_integer = True
|
| 1268 |
+
|
| 1269 |
+
@classmethod
|
| 1270 |
+
def eval(cls, number):
|
| 1271 |
+
# assert number.is_integer is not True, number
|
| 1272 |
+
|
| 1273 |
+
if number is sympy.oo:
|
| 1274 |
+
return int_oo
|
| 1275 |
+
if number is -sympy.oo:
|
| 1276 |
+
return -int_oo
|
| 1277 |
+
if isinstance(number, sympy.Number):
|
| 1278 |
+
return sympy.Integer(round(float(number), 0))
|
| 1279 |
+
|
| 1280 |
+
|
| 1281 |
+
# To get float -> int, Python style round semantics.
|
| 1282 |
+
#
|
| 1283 |
+
# x = PyFloat_AsDouble(self);
|
| 1284 |
+
# if (o_ndigits == Py_None) {
|
| 1285 |
+
# /* single-argument round or with None ndigits:
|
| 1286 |
+
# * round to nearest integer */
|
| 1287 |
+
# rounded = round(x);
|
| 1288 |
+
# if (fabs(x-rounded) == 0.5)
|
| 1289 |
+
# /* halfway case: round to even */
|
| 1290 |
+
# rounded = 2.0*round(x/2.0);
|
| 1291 |
+
# return PyLong_FromDouble(rounded);
|
| 1292 |
+
# }
|
| 1293 |
+
|
| 1294 |
+
|
| 1295 |
+
# NB: Like Round, this only ever returns floats. ndigits cannot be None
|
| 1296 |
+
class RoundDecimal(sympy.Function):
|
| 1297 |
+
is_real = True
|
| 1298 |
+
|
| 1299 |
+
@classmethod
|
| 1300 |
+
def eval(cls, number, ndigits):
|
| 1301 |
+
# assert number.is_integer is not True, number
|
| 1302 |
+
|
| 1303 |
+
if isinstance(number, sympy.Number) and isinstance(ndigits, sympy.Integer):
|
| 1304 |
+
return sympy.Float(round(float(number), int(ndigits)))
|
| 1305 |
+
|
| 1306 |
+
|
| 1307 |
+
class ToFloat(sympy.Function):
|
| 1308 |
+
is_real = True
|
| 1309 |
+
|
| 1310 |
+
@classmethod
|
| 1311 |
+
def eval(cls, number):
|
| 1312 |
+
if number in [sympy.oo, -sympy.oo]:
|
| 1313 |
+
return number
|
| 1314 |
+
|
| 1315 |
+
if isinstance(number, sympy.Integer):
|
| 1316 |
+
return sympy.Float(int(number))
|
| 1317 |
+
if number is int_oo:
|
| 1318 |
+
return sympy.oo
|
| 1319 |
+
if number is -int_oo:
|
| 1320 |
+
return -sympy.oo
|
| 1321 |
+
|
| 1322 |
+
|
| 1323 |
+
class Identity(sympy.Function):
|
| 1324 |
+
"""
|
| 1325 |
+
Prevents expansion and other optimizations
|
| 1326 |
+
"""
|
| 1327 |
+
|
| 1328 |
+
precedence = 10
|
| 1329 |
+
|
| 1330 |
+
def __repr__(self) -> str: # type: ignore[override]
|
| 1331 |
+
# pyrefly: ignore [missing-attribute]
|
| 1332 |
+
return f"Identity({self.args[0]})"
|
| 1333 |
+
|
| 1334 |
+
def _sympystr(self, printer) -> str:
|
| 1335 |
+
"""Controls how sympy's StrPrinter prints this"""
|
| 1336 |
+
# pyrefly: ignore [missing-attribute]
|
| 1337 |
+
return f"({printer.doprint(self.args[0])})"
|
| 1338 |
+
|
| 1339 |
+
def _eval_is_real(self):
|
| 1340 |
+
# pyrefly: ignore [missing-attribute]
|
| 1341 |
+
return self.args[0].is_real
|
| 1342 |
+
|
| 1343 |
+
def _eval_is_integer(self):
|
| 1344 |
+
return self.args[0].is_integer # type: ignore[attr-defined]
|
| 1345 |
+
|
| 1346 |
+
def _eval_expand_identity(self, **hints):
|
| 1347 |
+
# Removes the identity op.
|
| 1348 |
+
# pyrefly: ignore [missing-attribute]
|
| 1349 |
+
return self.args[0]
|
| 1350 |
+
|
| 1351 |
+
def __int__(self) -> int:
|
| 1352 |
+
# pyrefly: ignore [missing-attribute]
|
| 1353 |
+
return int(self.args[0])
|
| 1354 |
+
|
| 1355 |
+
def __float__(self) -> float:
|
| 1356 |
+
# pyrefly: ignore [missing-attribute]
|
| 1357 |
+
return float(self.args[0])
|
| 1358 |
+
|
| 1359 |
+
|
| 1360 |
+
def make_opaque_unary_fn(name):
|
| 1361 |
+
class OpaqueUnaryFn(sympy.Function):
|
| 1362 |
+
"""
|
| 1363 |
+
Unlike the builtin sympy functions on real numbers like sympy.sqrt,
|
| 1364 |
+
these equivalents do not do any nontrivial reasoning besides
|
| 1365 |
+
constant propagation. This helps avoid performing transformations
|
| 1366 |
+
that are valid for real numbers but are invalid for floating point;
|
| 1367 |
+
in particular, while we are willing to make optimizations that change
|
| 1368 |
+
numerics for Tensor compute, we are NOT willing to make optimizations
|
| 1369 |
+
that change numerics for size compute.
|
| 1370 |
+
"""
|
| 1371 |
+
|
| 1372 |
+
_torch_handler_name = name
|
| 1373 |
+
_torch_unpickler = make_opaque_unary_fn
|
| 1374 |
+
|
| 1375 |
+
@classmethod
|
| 1376 |
+
def eval(cls, a):
|
| 1377 |
+
if isinstance(a, (sympy.Integer, sympy.Float)):
|
| 1378 |
+
# Python converts to float64 before computing, c.f.
|
| 1379 |
+
# >>> math.sin(2**53+1)
|
| 1380 |
+
# -0.848925964814655
|
| 1381 |
+
# >>> math.sin(float(2**53+1))
|
| 1382 |
+
# -0.848925964814655
|
| 1383 |
+
try:
|
| 1384 |
+
return sympy.Float(getattr(math, name)(float(a)))
|
| 1385 |
+
# Just use sympy semantics for infinity/overflow, you might get some
|
| 1386 |
+
# weird objects but ask silly questions, get silly answers
|
| 1387 |
+
except OverflowError:
|
| 1388 |
+
return getattr(sympy, name)(a)
|
| 1389 |
+
elif a in [sympy.oo, -sympy.oo, sympy.zoo, -sympy.zoo, int_oo, -int_oo]:
|
| 1390 |
+
if a is int_oo:
|
| 1391 |
+
a = sympy.oo
|
| 1392 |
+
if a is -int_oo:
|
| 1393 |
+
a = -sympy.oo
|
| 1394 |
+
if name == "log2":
|
| 1395 |
+
return sympy.log(a, 2)
|
| 1396 |
+
return getattr(sympy, name)(a)
|
| 1397 |
+
return None
|
| 1398 |
+
|
| 1399 |
+
nm = "OpaqueUnaryFn_" + name
|
| 1400 |
+
OpaqueUnaryFn.__name__ = nm
|
| 1401 |
+
OpaqueUnaryFn.__qualname__ = nm
|
| 1402 |
+
|
| 1403 |
+
return OpaqueUnaryFn
|
| 1404 |
+
|
| 1405 |
+
|
| 1406 |
+
# Keep in sync with math_op_names in torch/fx/experimental/sym_node.py
|
| 1407 |
+
OpaqueUnaryFn_sqrt = make_opaque_unary_fn("sqrt")
|
| 1408 |
+
OpaqueUnaryFn_cos = make_opaque_unary_fn("cos")
|
| 1409 |
+
OpaqueUnaryFn_cosh = make_opaque_unary_fn("cosh")
|
| 1410 |
+
OpaqueUnaryFn_sin = make_opaque_unary_fn("sin")
|
| 1411 |
+
OpaqueUnaryFn_sinh = make_opaque_unary_fn("sinh")
|
| 1412 |
+
OpaqueUnaryFn_tan = make_opaque_unary_fn("tan")
|
| 1413 |
+
OpaqueUnaryFn_tanh = make_opaque_unary_fn("tanh")
|
| 1414 |
+
OpaqueUnaryFn_asin = make_opaque_unary_fn("asin")
|
| 1415 |
+
OpaqueUnaryFn_acos = make_opaque_unary_fn("acos")
|
| 1416 |
+
OpaqueUnaryFn_atan = make_opaque_unary_fn("atan")
|
| 1417 |
+
OpaqueUnaryFn_exp = make_opaque_unary_fn("exp")
|
| 1418 |
+
OpaqueUnaryFn_log = make_opaque_unary_fn("log")
|
| 1419 |
+
OpaqueUnaryFn_asinh = make_opaque_unary_fn("asinh")
|
| 1420 |
+
OpaqueUnaryFn_log2 = make_opaque_unary_fn("log2")
|
| 1421 |
+
|
| 1422 |
+
|
| 1423 |
+
def make_opaque_bitwise_fn(name, real_op_name):
|
| 1424 |
+
if name == "bitwise_and":
|
| 1425 |
+
prec = PRECEDENCE["BitwiseAnd"]
|
| 1426 |
+
elif name == "bitwise_xor":
|
| 1427 |
+
prec = PRECEDENCE["BitwiseXor"]
|
| 1428 |
+
elif name == "bitwise_or":
|
| 1429 |
+
prec = PRECEDENCE["BitwiseOr"]
|
| 1430 |
+
else:
|
| 1431 |
+
raise AssertionError(f"unrecognized {name}")
|
| 1432 |
+
|
| 1433 |
+
class BitwiseFn(sympy.Function):
|
| 1434 |
+
_torch_handler_name = name
|
| 1435 |
+
precedence: int = prec
|
| 1436 |
+
_torch_unpickler = functools.partial(
|
| 1437 |
+
make_opaque_bitwise_fn, real_op_name=real_op_name
|
| 1438 |
+
)
|
| 1439 |
+
|
| 1440 |
+
@classmethod
|
| 1441 |
+
def eval(cls, a, b):
|
| 1442 |
+
if a.is_Boolean and b.is_Boolean:
|
| 1443 |
+
return getattr(operator, real_op_name)(a, b)
|
| 1444 |
+
if a.is_Boolean:
|
| 1445 |
+
a = sympy.Integer(1 if a else 0)
|
| 1446 |
+
if b.is_Boolean:
|
| 1447 |
+
b = sympy.Integer(1 if b else 0)
|
| 1448 |
+
if isinstance(a, (sympy.Integer, int)) and isinstance(
|
| 1449 |
+
b, (sympy.Integer, int)
|
| 1450 |
+
):
|
| 1451 |
+
return sympy.Integer(getattr(operator, real_op_name)(int(a), int(b)))
|
| 1452 |
+
return None
|
| 1453 |
+
|
| 1454 |
+
nm = "BitwiseFn_" + name
|
| 1455 |
+
BitwiseFn.__name__ = nm
|
| 1456 |
+
BitwiseFn.__qualname__ = nm
|
| 1457 |
+
|
| 1458 |
+
return BitwiseFn
|
| 1459 |
+
|
| 1460 |
+
|
| 1461 |
+
BitwiseFn_bitwise_and = make_opaque_bitwise_fn("bitwise_and", "and_")
|
| 1462 |
+
BitwiseFn_bitwise_or = make_opaque_bitwise_fn("bitwise_or", "or_")
|
| 1463 |
+
BitwiseFn_bitwise_xor = make_opaque_bitwise_fn("bitwise_xor", "xor")
|
miniconda3/envs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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
"""
|
| 3 |
+
This is a simple interpreter for Sympy expressions that dispatches to
|
| 4 |
+
classes following the torch._inductor.virtualized calling convention.
|
| 5 |
+
For directness, the interpreter takes the handler directly rather than
|
| 6 |
+
consulting the TLS. It does not use most of the methods on the full
|
| 7 |
+
handler; only those with corresponding Sympy expressions. To see an example
|
| 8 |
+
of a full handler, see torch.utils._sympy.value_ranges.ValueRangeAnalysis.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import functools
|
| 12 |
+
import logging
|
| 13 |
+
from typing import Any
|
| 14 |
+
|
| 15 |
+
import sympy
|
| 16 |
+
from sympy.logic.boolalg import Boolean as SympyBoolean, BooleanAtom
|
| 17 |
+
|
| 18 |
+
import torch
|
| 19 |
+
|
| 20 |
+
from .functions import (
|
| 21 |
+
BitwiseFn_bitwise_and,
|
| 22 |
+
BitwiseFn_bitwise_or,
|
| 23 |
+
BitwiseFn_bitwise_xor,
|
| 24 |
+
CeilToInt,
|
| 25 |
+
CleanDiv,
|
| 26 |
+
FloatPow,
|
| 27 |
+
FloatTrueDiv,
|
| 28 |
+
FloorDiv,
|
| 29 |
+
FloorToInt,
|
| 30 |
+
Identity,
|
| 31 |
+
IntTrueDiv,
|
| 32 |
+
IsNonOverlappingAndDenseIndicator,
|
| 33 |
+
Max,
|
| 34 |
+
Min,
|
| 35 |
+
Mod,
|
| 36 |
+
ModularIndexing,
|
| 37 |
+
OpaqueUnaryFn_log2,
|
| 38 |
+
PowByNatural,
|
| 39 |
+
PythonMod,
|
| 40 |
+
RoundDecimal,
|
| 41 |
+
RoundToInt,
|
| 42 |
+
ToFloat,
|
| 43 |
+
TruncToFloat,
|
| 44 |
+
TruncToInt,
|
| 45 |
+
Where,
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
log = logging.getLogger(__name__)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
# TODO: Dedupe this with SYMPY_INTERP
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
@functools.cache
|
| 56 |
+
def handlers():
|
| 57 |
+
# TODO add CeilDiv (it doesn't appear in the index_expr)
|
| 58 |
+
|
| 59 |
+
# TODO default to some decompositions if the interpreter doesn't have them
|
| 60 |
+
# like decomposing ModularIndexing or implementing Le(a,b) as Ge(b, a)
|
| 61 |
+
|
| 62 |
+
HANDLERS = {
|
| 63 |
+
sympy.Or: "or_",
|
| 64 |
+
sympy.And: "and_",
|
| 65 |
+
sympy.Eq: "eq",
|
| 66 |
+
sympy.Ne: "ne",
|
| 67 |
+
sympy.Lt: "lt",
|
| 68 |
+
sympy.Gt: "gt",
|
| 69 |
+
sympy.Le: "le",
|
| 70 |
+
sympy.Ge: "ge",
|
| 71 |
+
sympy.Not: "not_",
|
| 72 |
+
IntTrueDiv: "int_truediv",
|
| 73 |
+
FloatTrueDiv: "truediv",
|
| 74 |
+
FloorDiv: "floordiv",
|
| 75 |
+
CleanDiv: "floordiv", # TODO: hmm?
|
| 76 |
+
TruncToFloat: "trunc",
|
| 77 |
+
Where: "where",
|
| 78 |
+
sympy.Add: "add",
|
| 79 |
+
sympy.Mul: "mul",
|
| 80 |
+
FloatPow: "pow",
|
| 81 |
+
PowByNatural: "pow_by_natural",
|
| 82 |
+
# sympy simplifies x * x into Pow(x, 2), so we need to handle this.
|
| 83 |
+
# Do NOT use builtin Pow for floats
|
| 84 |
+
# TODO: There is a hazard here, if we have float * float it will
|
| 85 |
+
# also get turned into Pow(float, 2) but we don't want this because
|
| 86 |
+
# pow_by_natural is assumed to only be integers. Probably the fix is
|
| 87 |
+
# to add a FloatMul to impede this optimization
|
| 88 |
+
sympy.Pow: "pow_by_natural",
|
| 89 |
+
Mod: "mod",
|
| 90 |
+
PythonMod: "python_mod",
|
| 91 |
+
# TODO: Inductor can generate these, but it's ill-specified which
|
| 92 |
+
# semantics were intended here. Needs to be cleaned up along with
|
| 93 |
+
# FloorDiv in a bigger cleanup
|
| 94 |
+
sympy.Mod: "mod",
|
| 95 |
+
sympy.Abs: "abs",
|
| 96 |
+
sympy.log: "log",
|
| 97 |
+
sympy.exp: "exp",
|
| 98 |
+
sympy.Min: "minimum",
|
| 99 |
+
sympy.Max: "maximum",
|
| 100 |
+
Min: "minimum",
|
| 101 |
+
Max: "maximum",
|
| 102 |
+
ModularIndexing: "modular_indexing",
|
| 103 |
+
sympy.functions.elementary.piecewise.ExprCondPair: "expr_cond_pair",
|
| 104 |
+
sympy.Piecewise: "piecewise",
|
| 105 |
+
Identity: "identity",
|
| 106 |
+
IsNonOverlappingAndDenseIndicator: "is_non_overlapping_and_dense_indicator",
|
| 107 |
+
RoundDecimal: "round_decimal",
|
| 108 |
+
# TODO: do the rest of the opaque unary functions...
|
| 109 |
+
OpaqueUnaryFn_log2: "log2",
|
| 110 |
+
BitwiseFn_bitwise_and: "bitwise_and",
|
| 111 |
+
BitwiseFn_bitwise_or: "bitwise_or",
|
| 112 |
+
BitwiseFn_bitwise_xor: "bitwise_xor",
|
| 113 |
+
}
|
| 114 |
+
# TODO: This is kind of pointless, we shouldn't be generating sympy.sin
|
| 115 |
+
# for these functions, they should be Opaque instead
|
| 116 |
+
for name in ["cos", "sin", "tan", "sinh", "cosh", "tanh", "asin", "acos", "atan"]:
|
| 117 |
+
HANDLERS[getattr(sympy, name)] = name
|
| 118 |
+
|
| 119 |
+
return HANDLERS
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
ASSOCIATIVE_OPS = {"minimum", "maximum", "mul", "add", "and_", "or_"}
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def _run_sympy_handler(analysis, args, expr, index_dtype=torch.int64):
|
| 126 |
+
# Special cases
|
| 127 |
+
if isinstance(expr, sympy.Pow) and isinstance(
|
| 128 |
+
expr.args[1], sympy.core.numbers.Half
|
| 129 |
+
):
|
| 130 |
+
return analysis.sqrt(args[0])
|
| 131 |
+
if isinstance(expr, ToFloat):
|
| 132 |
+
return analysis.to_dtype(args[0], torch.float64)
|
| 133 |
+
|
| 134 |
+
# These handlers are special because they take an extra dtype argument
|
| 135 |
+
# specifying what they should convert to, and we need to appropriately set
|
| 136 |
+
# this up when we convert from Sympy. A reasonable default when you
|
| 137 |
+
# are translating is to conservatively do int64, and then narrow these
|
| 138 |
+
# arguments later when you discover you can narrow the index range. But
|
| 139 |
+
# if you already know that 32-bit indexing is OK, you can directly do the
|
| 140 |
+
# sympy translation with index_dtype=torch.int32
|
| 141 |
+
INDEX_DTYPE_HANDLERS = {
|
| 142 |
+
TruncToInt: "trunc_to_int",
|
| 143 |
+
sympy.floor: "floor_to_int",
|
| 144 |
+
sympy.ceiling: "ceil_to_int",
|
| 145 |
+
FloorToInt: "floor_to_int",
|
| 146 |
+
CeilToInt: "ceil_to_int",
|
| 147 |
+
RoundToInt: "round_to_int",
|
| 148 |
+
}
|
| 149 |
+
if (handler_name := INDEX_DTYPE_HANDLERS.get(expr.func)) is not None:
|
| 150 |
+
return getattr(analysis, handler_name)(*args, index_dtype)
|
| 151 |
+
|
| 152 |
+
# Fastpath for n-ary integral addition
|
| 153 |
+
if expr.func is sympy.Add and expr.is_integer and hasattr(analysis, "sym_sum"):
|
| 154 |
+
r = analysis.sym_sum(args)
|
| 155 |
+
log.debug("sym_sum(%s) -> %s", args, r)
|
| 156 |
+
return r
|
| 157 |
+
|
| 158 |
+
if hasattr(expr.func, "_torch_handler_name"):
|
| 159 |
+
handler_name = expr.func._torch_handler_name
|
| 160 |
+
else:
|
| 161 |
+
handler_name = handlers()[expr.func]
|
| 162 |
+
handler = getattr(analysis, handler_name)
|
| 163 |
+
try:
|
| 164 |
+
if handler_name in ASSOCIATIVE_OPS:
|
| 165 |
+
if len(args) <= 1:
|
| 166 |
+
raise AssertionError("associative op needs >1 args")
|
| 167 |
+
acc = handler(args[0], args[1])
|
| 168 |
+
for i in range(2, len(args)):
|
| 169 |
+
acc = handler(acc, args[i])
|
| 170 |
+
log.debug("%s(%s) -> %s", handler_name, args, acc)
|
| 171 |
+
return acc
|
| 172 |
+
else:
|
| 173 |
+
r = handler(*args)
|
| 174 |
+
log.debug("%s(%s) -> %s", handler_name, args, r)
|
| 175 |
+
return r
|
| 176 |
+
except NotImplementedError:
|
| 177 |
+
raise
|
| 178 |
+
except Exception:
|
| 179 |
+
log.warning("failed while executing %s(%s)", handler_name, args)
|
| 180 |
+
raise
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
_nil = object()
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def sympy_interp(
|
| 187 |
+
analysis,
|
| 188 |
+
env: dict[sympy.Symbol, Any],
|
| 189 |
+
expr: sympy.Expr | SympyBoolean,
|
| 190 |
+
*,
|
| 191 |
+
index_dtype=torch.int64,
|
| 192 |
+
missing_handler=None,
|
| 193 |
+
):
|
| 194 |
+
# Handle base cases
|
| 195 |
+
dtype = None
|
| 196 |
+
if isinstance(expr, BooleanAtom):
|
| 197 |
+
dtype = torch.bool
|
| 198 |
+
elif isinstance(expr, sympy.Integer):
|
| 199 |
+
dtype = torch.int64
|
| 200 |
+
elif isinstance(expr, sympy.Number):
|
| 201 |
+
dtype = torch.double
|
| 202 |
+
|
| 203 |
+
if dtype is not None:
|
| 204 |
+
return analysis.constant(expr, dtype)
|
| 205 |
+
elif isinstance(expr, sympy.Symbol):
|
| 206 |
+
if (r := env.get(expr, _nil)) is not _nil:
|
| 207 |
+
return r
|
| 208 |
+
elif missing_handler:
|
| 209 |
+
return missing_handler(expr)
|
| 210 |
+
else:
|
| 211 |
+
raise KeyError(expr)
|
| 212 |
+
|
| 213 |
+
# Recursive case
|
| 214 |
+
return _run_sympy_handler(
|
| 215 |
+
analysis,
|
| 216 |
+
[
|
| 217 |
+
sympy_interp(
|
| 218 |
+
analysis,
|
| 219 |
+
env,
|
| 220 |
+
arg,
|
| 221 |
+
index_dtype=index_dtype,
|
| 222 |
+
missing_handler=missing_handler,
|
| 223 |
+
)
|
| 224 |
+
for arg in expr.args
|
| 225 |
+
],
|
| 226 |
+
expr,
|
| 227 |
+
index_dtype=index_dtype,
|
| 228 |
+
)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/_sympy/numbers.py
ADDED
|
@@ -0,0 +1,399 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import mpmath.libmp as mlib # type: ignore[import-untyped]
|
| 3 |
+
import sympy
|
| 4 |
+
from sympy import Expr
|
| 5 |
+
from sympy.core.decorators import _sympifyit
|
| 6 |
+
from sympy.core.expr import AtomicExpr
|
| 7 |
+
from sympy.core.numbers import Number
|
| 8 |
+
from sympy.core.parameters import global_parameters
|
| 9 |
+
from sympy.core.singleton import S, Singleton
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
# pyrefly: ignore [invalid-inheritance]
|
| 13 |
+
class IntInfinity(Number, metaclass=Singleton):
|
| 14 |
+
r"""Positive integer infinite quantity.
|
| 15 |
+
|
| 16 |
+
Integer infinity is a value in an extended integers which
|
| 17 |
+
is greater than all other integers. We distinguish it from
|
| 18 |
+
sympy's existing notion of infinity in that it reports that
|
| 19 |
+
it is_integer.
|
| 20 |
+
|
| 21 |
+
Infinity is a singleton, and can be accessed by ``S.IntInfinity``,
|
| 22 |
+
or can be imported as ``int_oo``.
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
# NB: We can't actually mark this as infinite, as integer and infinite are
|
| 26 |
+
# inconsistent assumptions in sympy. We also report that we are complex,
|
| 27 |
+
# different from sympy.oo
|
| 28 |
+
|
| 29 |
+
is_integer = True
|
| 30 |
+
is_commutative = True
|
| 31 |
+
is_number = True
|
| 32 |
+
is_extended_real = True
|
| 33 |
+
is_comparable = True
|
| 34 |
+
is_extended_positive = True
|
| 35 |
+
is_prime = False
|
| 36 |
+
|
| 37 |
+
# Ensure we get dispatched to before plain numbers
|
| 38 |
+
_op_priority = 100.0
|
| 39 |
+
|
| 40 |
+
__slots__ = ()
|
| 41 |
+
|
| 42 |
+
def __new__(cls):
|
| 43 |
+
return AtomicExpr.__new__(cls)
|
| 44 |
+
|
| 45 |
+
def _sympystr(self, printer) -> str:
|
| 46 |
+
return "int_oo"
|
| 47 |
+
|
| 48 |
+
def _eval_subs(self, old, new):
|
| 49 |
+
if self == old:
|
| 50 |
+
return new
|
| 51 |
+
|
| 52 |
+
# We could do these, not sure about it
|
| 53 |
+
"""
|
| 54 |
+
def _eval_evalf(self, prec=None):
|
| 55 |
+
return Float('inf')
|
| 56 |
+
|
| 57 |
+
def evalf(self, prec=None, **options):
|
| 58 |
+
return self._eval_evalf(prec)
|
| 59 |
+
"""
|
| 60 |
+
|
| 61 |
+
@_sympifyit("other", NotImplemented)
|
| 62 |
+
def __add__(self, other):
|
| 63 |
+
if isinstance(other, Number) and global_parameters.evaluate:
|
| 64 |
+
if other in (S.Infinity, S.NegativeInfinity):
|
| 65 |
+
return other
|
| 66 |
+
if other in (S.NegativeIntInfinity, S.NaN):
|
| 67 |
+
return S.NaN
|
| 68 |
+
return self
|
| 69 |
+
return Number.__add__(self, other)
|
| 70 |
+
|
| 71 |
+
__radd__ = __add__
|
| 72 |
+
|
| 73 |
+
@_sympifyit("other", NotImplemented)
|
| 74 |
+
def __sub__(self, other):
|
| 75 |
+
if isinstance(other, Number) and global_parameters.evaluate:
|
| 76 |
+
if other is S.Infinity:
|
| 77 |
+
return S.NegativeInfinity
|
| 78 |
+
if other is S.NegativeInfinity:
|
| 79 |
+
return S.Infinity
|
| 80 |
+
if other in (S.IntInfinity, S.NaN):
|
| 81 |
+
return S.NaN
|
| 82 |
+
return self
|
| 83 |
+
return Number.__sub__(self, other)
|
| 84 |
+
|
| 85 |
+
@_sympifyit("other", NotImplemented)
|
| 86 |
+
def __rsub__(self, other):
|
| 87 |
+
return (-self).__add__(other)
|
| 88 |
+
|
| 89 |
+
@_sympifyit("other", NotImplemented)
|
| 90 |
+
def __mul__(self, other):
|
| 91 |
+
if isinstance(other, Number) and global_parameters.evaluate:
|
| 92 |
+
if other.is_zero or other is S.NaN:
|
| 93 |
+
return S.NaN
|
| 94 |
+
if other.is_extended_positive:
|
| 95 |
+
return self
|
| 96 |
+
return S.NegativeIntInfinity
|
| 97 |
+
return Number.__mul__(self, other)
|
| 98 |
+
|
| 99 |
+
__rmul__ = __mul__
|
| 100 |
+
|
| 101 |
+
@_sympifyit("other", NotImplemented)
|
| 102 |
+
def __truediv__(self, other):
|
| 103 |
+
if isinstance(other, Number) and global_parameters.evaluate:
|
| 104 |
+
if other in (
|
| 105 |
+
S.Infinity,
|
| 106 |
+
S.IntInfinity,
|
| 107 |
+
S.NegativeInfinity,
|
| 108 |
+
S.NegativeIntInfinity,
|
| 109 |
+
S.NaN,
|
| 110 |
+
):
|
| 111 |
+
return S.NaN
|
| 112 |
+
if other.is_extended_nonnegative:
|
| 113 |
+
return S.Infinity # truediv produces float
|
| 114 |
+
return S.NegativeInfinity # truediv produces float
|
| 115 |
+
return Number.__truediv__(self, other)
|
| 116 |
+
|
| 117 |
+
def __abs__(self):
|
| 118 |
+
return S.IntInfinity
|
| 119 |
+
|
| 120 |
+
def __neg__(self):
|
| 121 |
+
return S.NegativeIntInfinity
|
| 122 |
+
|
| 123 |
+
def _eval_power(self, expt):
|
| 124 |
+
if expt.is_extended_positive:
|
| 125 |
+
return S.IntInfinity
|
| 126 |
+
if expt.is_extended_negative:
|
| 127 |
+
return S.Zero
|
| 128 |
+
if expt is S.NaN:
|
| 129 |
+
return S.NaN
|
| 130 |
+
if expt is S.ComplexInfinity:
|
| 131 |
+
return S.NaN
|
| 132 |
+
if expt.is_extended_real is False and expt.is_number:
|
| 133 |
+
from sympy.functions.elementary.complexes import re
|
| 134 |
+
|
| 135 |
+
expt_real = re(expt)
|
| 136 |
+
if expt_real.is_positive:
|
| 137 |
+
return S.ComplexInfinity
|
| 138 |
+
if expt_real.is_negative:
|
| 139 |
+
return S.Zero
|
| 140 |
+
if expt_real.is_zero:
|
| 141 |
+
return S.NaN
|
| 142 |
+
|
| 143 |
+
return self ** expt.evalf()
|
| 144 |
+
|
| 145 |
+
def _as_mpf_val(self, prec):
|
| 146 |
+
return mlib.finf
|
| 147 |
+
|
| 148 |
+
def __hash__(self):
|
| 149 |
+
return super().__hash__()
|
| 150 |
+
|
| 151 |
+
def __eq__(self, other):
|
| 152 |
+
return other is S.IntInfinity
|
| 153 |
+
|
| 154 |
+
def __ne__(self, other):
|
| 155 |
+
return other is not S.IntInfinity
|
| 156 |
+
|
| 157 |
+
def __gt__(self, other):
|
| 158 |
+
if other is S.Infinity:
|
| 159 |
+
return sympy.false # sympy.oo > int_oo
|
| 160 |
+
elif other is S.IntInfinity:
|
| 161 |
+
return sympy.false # consistency with sympy.oo
|
| 162 |
+
else:
|
| 163 |
+
return sympy.true
|
| 164 |
+
|
| 165 |
+
def __ge__(self, other):
|
| 166 |
+
if other is S.Infinity:
|
| 167 |
+
return sympy.false # sympy.oo > int_oo
|
| 168 |
+
elif other is S.IntInfinity:
|
| 169 |
+
return sympy.true # consistency with sympy.oo
|
| 170 |
+
else:
|
| 171 |
+
return sympy.true
|
| 172 |
+
|
| 173 |
+
def __lt__(self, other):
|
| 174 |
+
if other is S.Infinity:
|
| 175 |
+
return sympy.true # sympy.oo > int_oo
|
| 176 |
+
elif other is S.IntInfinity:
|
| 177 |
+
return sympy.false # consistency with sympy.oo
|
| 178 |
+
else:
|
| 179 |
+
return sympy.false
|
| 180 |
+
|
| 181 |
+
def __le__(self, other):
|
| 182 |
+
if other is S.Infinity:
|
| 183 |
+
return sympy.true # sympy.oo > int_oo
|
| 184 |
+
elif other is S.IntInfinity:
|
| 185 |
+
return sympy.true # consistency with sympy.oo
|
| 186 |
+
else:
|
| 187 |
+
return sympy.false
|
| 188 |
+
|
| 189 |
+
@_sympifyit("other", NotImplemented)
|
| 190 |
+
def __mod__(self, other):
|
| 191 |
+
if not isinstance(other, Expr):
|
| 192 |
+
return NotImplemented
|
| 193 |
+
return S.NaN
|
| 194 |
+
|
| 195 |
+
__rmod__ = __mod__
|
| 196 |
+
|
| 197 |
+
def floor(self):
|
| 198 |
+
return self
|
| 199 |
+
|
| 200 |
+
def ceiling(self):
|
| 201 |
+
return self
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
int_oo = S.IntInfinity
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
# pyrefly: ignore [invalid-inheritance]
|
| 208 |
+
class NegativeIntInfinity(Number, metaclass=Singleton):
|
| 209 |
+
"""Negative integer infinite quantity.
|
| 210 |
+
|
| 211 |
+
NegativeInfinity is a singleton, and can be accessed
|
| 212 |
+
by ``S.NegativeInfinity``.
|
| 213 |
+
|
| 214 |
+
See Also
|
| 215 |
+
========
|
| 216 |
+
|
| 217 |
+
IntInfinity
|
| 218 |
+
"""
|
| 219 |
+
|
| 220 |
+
# Ensure we get dispatched to before plain numbers
|
| 221 |
+
_op_priority = 100.0
|
| 222 |
+
|
| 223 |
+
is_integer = True
|
| 224 |
+
is_extended_real = True
|
| 225 |
+
is_commutative = True
|
| 226 |
+
is_comparable = True
|
| 227 |
+
is_extended_negative = True
|
| 228 |
+
is_number = True
|
| 229 |
+
is_prime = False
|
| 230 |
+
|
| 231 |
+
__slots__ = ()
|
| 232 |
+
|
| 233 |
+
def __new__(cls):
|
| 234 |
+
return AtomicExpr.__new__(cls)
|
| 235 |
+
|
| 236 |
+
def _eval_subs(self, old, new):
|
| 237 |
+
if self == old:
|
| 238 |
+
return new
|
| 239 |
+
|
| 240 |
+
def _sympystr(self, printer) -> str:
|
| 241 |
+
return "-int_oo"
|
| 242 |
+
|
| 243 |
+
"""
|
| 244 |
+
def _eval_evalf(self, prec=None):
|
| 245 |
+
return Float('-inf')
|
| 246 |
+
|
| 247 |
+
def evalf(self, prec=None, **options):
|
| 248 |
+
return self._eval_evalf(prec)
|
| 249 |
+
"""
|
| 250 |
+
|
| 251 |
+
@_sympifyit("other", NotImplemented)
|
| 252 |
+
def __add__(self, other):
|
| 253 |
+
if isinstance(other, Number) and global_parameters.evaluate:
|
| 254 |
+
if other is S.Infinity:
|
| 255 |
+
return S.Infinity
|
| 256 |
+
if other in (S.IntInfinity, S.NaN):
|
| 257 |
+
return S.NaN
|
| 258 |
+
return self
|
| 259 |
+
return Number.__add__(self, other)
|
| 260 |
+
|
| 261 |
+
__radd__ = __add__
|
| 262 |
+
|
| 263 |
+
@_sympifyit("other", NotImplemented)
|
| 264 |
+
def __sub__(self, other):
|
| 265 |
+
if isinstance(other, Number) and global_parameters.evaluate:
|
| 266 |
+
if other is S.NegativeInfinity:
|
| 267 |
+
return S.Infinity
|
| 268 |
+
if other in (S.NegativeIntInfinity, S.NaN):
|
| 269 |
+
return S.NaN
|
| 270 |
+
return self
|
| 271 |
+
return Number.__sub__(self, other)
|
| 272 |
+
|
| 273 |
+
@_sympifyit("other", NotImplemented)
|
| 274 |
+
def __rsub__(self, other):
|
| 275 |
+
return (-self).__add__(other)
|
| 276 |
+
|
| 277 |
+
@_sympifyit("other", NotImplemented)
|
| 278 |
+
def __mul__(self, other):
|
| 279 |
+
if isinstance(other, Number) and global_parameters.evaluate:
|
| 280 |
+
if other.is_zero or other is S.NaN:
|
| 281 |
+
return S.NaN
|
| 282 |
+
if other.is_extended_positive:
|
| 283 |
+
return self
|
| 284 |
+
return S.IntInfinity
|
| 285 |
+
return Number.__mul__(self, other)
|
| 286 |
+
|
| 287 |
+
__rmul__ = __mul__
|
| 288 |
+
|
| 289 |
+
@_sympifyit("other", NotImplemented)
|
| 290 |
+
def __truediv__(self, other):
|
| 291 |
+
if isinstance(other, Number) and global_parameters.evaluate:
|
| 292 |
+
if other in (
|
| 293 |
+
S.Infinity,
|
| 294 |
+
S.IntInfinity,
|
| 295 |
+
S.NegativeInfinity,
|
| 296 |
+
S.NegativeIntInfinity,
|
| 297 |
+
S.NaN,
|
| 298 |
+
):
|
| 299 |
+
return S.NaN
|
| 300 |
+
if other.is_extended_nonnegative:
|
| 301 |
+
return self
|
| 302 |
+
return S.Infinity # truediv returns float
|
| 303 |
+
return Number.__truediv__(self, other)
|
| 304 |
+
|
| 305 |
+
def __abs__(self):
|
| 306 |
+
return S.IntInfinity
|
| 307 |
+
|
| 308 |
+
def __neg__(self):
|
| 309 |
+
return S.IntInfinity
|
| 310 |
+
|
| 311 |
+
def _eval_power(self, expt):
|
| 312 |
+
if expt.is_number:
|
| 313 |
+
if expt in (
|
| 314 |
+
S.NaN,
|
| 315 |
+
S.Infinity,
|
| 316 |
+
S.NegativeInfinity,
|
| 317 |
+
S.IntInfinity,
|
| 318 |
+
S.NegativeIntInfinity,
|
| 319 |
+
):
|
| 320 |
+
return S.NaN
|
| 321 |
+
|
| 322 |
+
if isinstance(expt, sympy.Integer) and expt.is_extended_positive:
|
| 323 |
+
if expt.is_odd:
|
| 324 |
+
return S.NegativeIntInfinity
|
| 325 |
+
else:
|
| 326 |
+
return S.IntInfinity
|
| 327 |
+
|
| 328 |
+
inf_part = S.IntInfinity**expt
|
| 329 |
+
s_part = S.NegativeOne**expt
|
| 330 |
+
if inf_part == 0 and s_part.is_finite:
|
| 331 |
+
return inf_part
|
| 332 |
+
if (
|
| 333 |
+
inf_part is S.ComplexInfinity
|
| 334 |
+
and s_part.is_finite
|
| 335 |
+
and not s_part.is_zero
|
| 336 |
+
):
|
| 337 |
+
return S.ComplexInfinity
|
| 338 |
+
return s_part * inf_part
|
| 339 |
+
|
| 340 |
+
def _as_mpf_val(self, prec):
|
| 341 |
+
return mlib.fninf
|
| 342 |
+
|
| 343 |
+
def __hash__(self):
|
| 344 |
+
return super().__hash__()
|
| 345 |
+
|
| 346 |
+
def __eq__(self, other):
|
| 347 |
+
return other is S.NegativeIntInfinity
|
| 348 |
+
|
| 349 |
+
def __ne__(self, other):
|
| 350 |
+
return other is not S.NegativeIntInfinity
|
| 351 |
+
|
| 352 |
+
def __gt__(self, other):
|
| 353 |
+
if other is S.NegativeInfinity:
|
| 354 |
+
return sympy.true # -sympy.oo < -int_oo
|
| 355 |
+
elif other is S.NegativeIntInfinity:
|
| 356 |
+
return sympy.false # consistency with sympy.oo
|
| 357 |
+
else:
|
| 358 |
+
return sympy.false
|
| 359 |
+
|
| 360 |
+
def __ge__(self, other):
|
| 361 |
+
if other is S.NegativeInfinity:
|
| 362 |
+
return sympy.true # -sympy.oo < -int_oo
|
| 363 |
+
elif other is S.NegativeIntInfinity:
|
| 364 |
+
return sympy.true # consistency with sympy.oo
|
| 365 |
+
else:
|
| 366 |
+
return sympy.false
|
| 367 |
+
|
| 368 |
+
def __lt__(self, other):
|
| 369 |
+
if other is S.NegativeInfinity:
|
| 370 |
+
return sympy.false # -sympy.oo < -int_oo
|
| 371 |
+
elif other is S.NegativeIntInfinity:
|
| 372 |
+
return sympy.false # consistency with sympy.oo
|
| 373 |
+
else:
|
| 374 |
+
return sympy.true
|
| 375 |
+
|
| 376 |
+
def __le__(self, other):
|
| 377 |
+
if other is S.NegativeInfinity:
|
| 378 |
+
return sympy.false # -sympy.oo < -int_oo
|
| 379 |
+
elif other is S.NegativeIntInfinity:
|
| 380 |
+
return sympy.true # consistency with sympy.oo
|
| 381 |
+
else:
|
| 382 |
+
return sympy.true
|
| 383 |
+
|
| 384 |
+
@_sympifyit("other", NotImplemented)
|
| 385 |
+
def __mod__(self, other):
|
| 386 |
+
if not isinstance(other, Expr):
|
| 387 |
+
return NotImplemented
|
| 388 |
+
return S.NaN
|
| 389 |
+
|
| 390 |
+
__rmod__ = __mod__
|
| 391 |
+
|
| 392 |
+
def floor(self):
|
| 393 |
+
return self
|
| 394 |
+
|
| 395 |
+
def ceiling(self):
|
| 396 |
+
return self
|
| 397 |
+
|
| 398 |
+
def as_powers_dict(self):
|
| 399 |
+
return {S.NegativeOne: 1, S.IntInfinity: 1}
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/_sympy/printers.py
ADDED
|
@@ -0,0 +1,593 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
|
| 3 |
+
import sympy
|
| 4 |
+
from sympy.printing.precedence import PRECEDENCE, precedence
|
| 5 |
+
from sympy.printing.str import StrPrinter
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
INDEX_TYPE = "int64_t"
|
| 9 |
+
INDEX_TYPE_MAX = (1 << 63) - 1
|
| 10 |
+
INDEX_TYPE_MIN = -1 << 63
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
# This printer contains rules that are supposed to be generic for both C/C++ and
|
| 14 |
+
# Python
|
| 15 |
+
class ExprPrinter(StrPrinter):
|
| 16 |
+
# override this so that _print_FloorDiv is used
|
| 17 |
+
printmethod = "_torch_sympystr"
|
| 18 |
+
|
| 19 |
+
def _print_Mul(self, expr: sympy.Expr) -> str:
|
| 20 |
+
return self.stringify(expr.args, "*", precedence(expr))
|
| 21 |
+
|
| 22 |
+
def _print_Not(self, expr: sympy.Expr) -> str:
|
| 23 |
+
return f"not ({self._print(expr.args[0])})"
|
| 24 |
+
|
| 25 |
+
def _print_Add(self, expr: sympy.Expr, order: str | None = None) -> str:
|
| 26 |
+
return self.stringify(expr.args, " + ", precedence(expr))
|
| 27 |
+
|
| 28 |
+
def _print_Relational(self, expr: sympy.Expr) -> str:
|
| 29 |
+
return self.stringify(expr.args, f" {expr.rel_op} ", precedence(expr))
|
| 30 |
+
|
| 31 |
+
def _print_BitwiseFn_bitwise_and(self, expr: sympy.Expr) -> str:
|
| 32 |
+
return self.stringify(expr.args, " & ", PRECEDENCE["BitwiseAnd"])
|
| 33 |
+
|
| 34 |
+
def _print_BitwiseFn_bitwise_or(self, expr: sympy.Expr) -> str:
|
| 35 |
+
return self.stringify(expr.args, " | ", PRECEDENCE["BitwiseOr"])
|
| 36 |
+
|
| 37 |
+
def _print_BitwiseFn_bitwise_xor(self, expr: sympy.Expr) -> str:
|
| 38 |
+
return self.stringify(expr.args, " ^ ", PRECEDENCE["BitwiseXor"])
|
| 39 |
+
|
| 40 |
+
# NB: this is OK to put here, because Mod is only defined for positive
|
| 41 |
+
# numbers, and so across C/Python its behavior is consistent
|
| 42 |
+
def _print_Mod(self, expr: sympy.Expr) -> str:
|
| 43 |
+
return self.stringify(expr.args, " % ", PRECEDENCE["Atom"] - 0.5)
|
| 44 |
+
|
| 45 |
+
def _print_FloatTrueDiv(self, expr: sympy.Expr) -> str:
|
| 46 |
+
s = self.stringify(expr.args, " / ", PRECEDENCE["Atom"] - 0.5)
|
| 47 |
+
return f"({s})"
|
| 48 |
+
|
| 49 |
+
def _print_CleanDiv(self, expr: sympy.Expr) -> str:
|
| 50 |
+
return self._print_FloorDiv(expr)
|
| 51 |
+
|
| 52 |
+
def _print_Identity(self, expr: sympy.Expr) -> str:
|
| 53 |
+
return self._print(expr.args[0])
|
| 54 |
+
|
| 55 |
+
def _print_Float(self, expr: sympy.Expr) -> str:
|
| 56 |
+
if expr._prec == 53:
|
| 57 |
+
# IEEE-754 double precision have 53 bits. SymPy prints them with
|
| 58 |
+
# 15 digits, but we need 17 for round-trip correctness
|
| 59 |
+
return str(sympy.Float(expr, dps=17))
|
| 60 |
+
else:
|
| 61 |
+
# We don't use other precisions in pytorch
|
| 62 |
+
return str(expr)
|
| 63 |
+
|
| 64 |
+
# This must be implemented because sympy will collect x * x into Pow(x, 2), without
|
| 65 |
+
# any explicit intervention. We print it just like x * x, notably, we
|
| 66 |
+
# never generate sympy.Pow with floats.
|
| 67 |
+
#
|
| 68 |
+
# NB: this pow by natural, you should never have used builtin sympy.pow
|
| 69 |
+
# for FloatPow, and a symbolic exponent should be PowByNatural. These
|
| 70 |
+
# means exp is guaranteed to be integer.
|
| 71 |
+
# pyrefly: ignore [bad-override]
|
| 72 |
+
def _print_Pow(self, expr: sympy.Expr) -> str:
|
| 73 |
+
base, exp = expr.args
|
| 74 |
+
if exp != int(exp):
|
| 75 |
+
raise AssertionError(exp)
|
| 76 |
+
exp = int(exp)
|
| 77 |
+
if exp < 0:
|
| 78 |
+
raise AssertionError(f"exponent must be non-negative, got {exp}")
|
| 79 |
+
if exp > 0:
|
| 80 |
+
return self.stringify([base] * exp, "*", PRECEDENCE["Mul"])
|
| 81 |
+
return "1"
|
| 82 |
+
|
| 83 |
+
# Explicit NotImplemented functions are to prevent default sympy printing
|
| 84 |
+
# behavior, which will just barf out ToFloat(...) to your IR. The error
|
| 85 |
+
# message is better here because it tells you which printer class it needs
|
| 86 |
+
# to go in.
|
| 87 |
+
|
| 88 |
+
def _print_ToFloat(self, expr: sympy.Expr) -> str:
|
| 89 |
+
raise NotImplementedError(f"_print_ToFloat not implemented for {type(self)}")
|
| 90 |
+
|
| 91 |
+
def _print_Infinity(self, expr: sympy.Expr) -> str:
|
| 92 |
+
raise NotImplementedError(f"_print_Infinity not implemented for {type(self)}")
|
| 93 |
+
|
| 94 |
+
def _print_NegativeInfinity(self, expr: sympy.Expr) -> str:
|
| 95 |
+
raise NotImplementedError(
|
| 96 |
+
f"_print_NegativeInfinity not implemented for {type(self)}"
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
def _print_FloorDiv(self, expr: sympy.Expr) -> str:
|
| 100 |
+
raise NotImplementedError(f"_print_FloorDiv not implemented for {type(self)}")
|
| 101 |
+
|
| 102 |
+
def _print_PythonMod(self, expr: sympy.Expr) -> str:
|
| 103 |
+
raise NotImplementedError(f"_print_PythonMod not implemented for {type(self)}")
|
| 104 |
+
|
| 105 |
+
def _print_IntTrueDiv(self, expr: sympy.Expr) -> str:
|
| 106 |
+
raise NotImplementedError(f"_print_IntTrueDiv not implemented for {type(self)}")
|
| 107 |
+
|
| 108 |
+
def _print_PowByNatural(self, expr: sympy.Expr) -> str:
|
| 109 |
+
raise NotImplementedError(
|
| 110 |
+
f"_print_PowByNatural not implemented for {type(self)}"
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
def _print_FloatPow(self, expr: sympy.Expr) -> str:
|
| 114 |
+
raise NotImplementedError(f"_print_FloatPow not implemented for {type(self)}")
|
| 115 |
+
|
| 116 |
+
def _print_TruncToInt(self, expr: sympy.Expr) -> str:
|
| 117 |
+
raise NotImplementedError(f"_print_TruncToInt not implemented for {type(self)}")
|
| 118 |
+
|
| 119 |
+
def _print_RoundToInt(self, expr: sympy.Expr) -> str:
|
| 120 |
+
raise NotImplementedError(f"_print_RoundToInt not implemented for {type(self)}")
|
| 121 |
+
|
| 122 |
+
def _print_RoundDecimal(self, expr: sympy.Expr) -> str:
|
| 123 |
+
raise NotImplementedError(
|
| 124 |
+
f"_print_RoundDecimal not implemented for {type(self)}"
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
# NB: Some float operations are INTENTIONALLY not implemented for
|
| 128 |
+
# printers. You can implement them as a quick unblock, but it is better
|
| 129 |
+
# to ask yourself why we haven't done this computation in the Tensor
|
| 130 |
+
# universe instead
|
| 131 |
+
|
| 132 |
+
def _print_TruncToFloat(self, expr: sympy.Expr) -> str:
|
| 133 |
+
raise NotImplementedError(
|
| 134 |
+
f"_print_TruncToFloat not implemented for {type(self)}"
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
class PythonPrinter(ExprPrinter):
|
| 139 |
+
def _print_ToFloat(self, expr: sympy.Expr) -> str:
|
| 140 |
+
if len(expr.args) != 1:
|
| 141 |
+
raise AssertionError("ToFloat expects exactly one argument")
|
| 142 |
+
# NB: We use sym_float here because the printer is used for cache
|
| 143 |
+
# serialization, and cache guards get evaluated with SymInt to
|
| 144 |
+
# propagate guards to the parent ShapeEnv. However, this comes at a
|
| 145 |
+
# runtime cost for guards involving float. If this is unacceptable
|
| 146 |
+
# overhead, what you want to do is have two separate printers for
|
| 147 |
+
# SymInt, one for when the inputs are guaranteed to be int, and
|
| 148 |
+
# another for when they could be SymInt.
|
| 149 |
+
#
|
| 150 |
+
# NB: sym_min/sym_max also have this problem, but I chose not to fix
|
| 151 |
+
# those.
|
| 152 |
+
#
|
| 153 |
+
# See https://github.com/pytorch/pytorch/issues/142507 for more
|
| 154 |
+
# context.
|
| 155 |
+
return f"torch.sym_float({self._print(expr.args[0])})"
|
| 156 |
+
|
| 157 |
+
def _print_And(self, expr: sympy.Expr) -> str:
|
| 158 |
+
return self.stringify(expr.args, " and ", precedence(expr))
|
| 159 |
+
|
| 160 |
+
def _print_Or(self, expr: sympy.Expr) -> str:
|
| 161 |
+
return self.stringify(expr.args, " or ", precedence(expr))
|
| 162 |
+
|
| 163 |
+
def _print_ModularIndexing(self, expr: sympy.Expr) -> str:
|
| 164 |
+
x, div, mod = (
|
| 165 |
+
self.parenthesize(arg, PRECEDENCE["Atom"] - 0.5) for arg in expr.args
|
| 166 |
+
)
|
| 167 |
+
if div != "1":
|
| 168 |
+
x = f"({x} // {div})"
|
| 169 |
+
return f"({x} % {mod})"
|
| 170 |
+
|
| 171 |
+
def _print_Infinity(self, expr: sympy.Expr) -> str:
|
| 172 |
+
return "math.inf"
|
| 173 |
+
|
| 174 |
+
def _print_NegativeInfinity(self, expr: sympy.Expr) -> str:
|
| 175 |
+
return "-math.inf"
|
| 176 |
+
|
| 177 |
+
# WARNING: this is dangerous for Triton, which has C-style modulus
|
| 178 |
+
def _print_PythonMod(self, expr: sympy.Expr) -> str:
|
| 179 |
+
return self.stringify(expr.args, " % ", PRECEDENCE["Atom"] - 0.5)
|
| 180 |
+
|
| 181 |
+
# WARNING: this is dangerous for Triton, which has C-style modulus
|
| 182 |
+
def _print_FloorDiv(self, expr: sympy.Expr) -> str:
|
| 183 |
+
x, div = (self.parenthesize(arg, PRECEDENCE["Atom"] - 0.5) for arg in expr.args)
|
| 184 |
+
return f"{x} // {div}"
|
| 185 |
+
|
| 186 |
+
# WARNING: this is dangerous for Triton, when lhs, rhs > 2**53, Python
|
| 187 |
+
# does a special algorithm
|
| 188 |
+
def _print_IntTrueDiv(self, expr: sympy.Expr) -> str:
|
| 189 |
+
return self.stringify(expr.args, " / ", PRECEDENCE["Atom"] - 0.5)
|
| 190 |
+
|
| 191 |
+
def _helper_sqrt(self, expr: sympy.Expr) -> str:
|
| 192 |
+
return f"math.sqrt({self._print(expr)})"
|
| 193 |
+
|
| 194 |
+
def _print_OpaqueUnaryFn_sqrt(self, expr: sympy.Expr) -> str:
|
| 195 |
+
return self._helper_sqrt(expr.args[0])
|
| 196 |
+
|
| 197 |
+
def _print_FloatPow(self, expr: sympy.Expr) -> str:
|
| 198 |
+
return self.stringify(expr.args, " ** ", PRECEDENCE["Pow"])
|
| 199 |
+
|
| 200 |
+
# TODO: Not sure this works with Triton, even when base/exp are integral
|
| 201 |
+
def _print_PowByNatural(self, expr: sympy.Expr) -> str:
|
| 202 |
+
return self.stringify(expr.args, " ** ", PRECEDENCE["Pow"])
|
| 203 |
+
|
| 204 |
+
def _print_floor(self, expr: sympy.Expr) -> str:
|
| 205 |
+
if len(expr.args) != 1:
|
| 206 |
+
raise AssertionError("floor expects exactly one argument")
|
| 207 |
+
return f"math.floor({self._print(expr.args[0])})"
|
| 208 |
+
|
| 209 |
+
def _print_FloorToInt(self, expr: sympy.Expr) -> str:
|
| 210 |
+
if len(expr.args) != 1:
|
| 211 |
+
raise AssertionError("FloorToInt expects exactly one argument")
|
| 212 |
+
return f"math.floor({self._print(expr.args[0])})"
|
| 213 |
+
|
| 214 |
+
def _print_TruncToInt(self, expr: sympy.Expr) -> str:
|
| 215 |
+
if len(expr.args) != 1:
|
| 216 |
+
raise AssertionError("TruncToInt expects exactly one argument")
|
| 217 |
+
# This also could have been int(), they'll do the same thing for float
|
| 218 |
+
return f"math.trunc({self._print(expr.args[0])})"
|
| 219 |
+
|
| 220 |
+
def _print_ceiling(self, expr: sympy.Expr) -> str:
|
| 221 |
+
if len(expr.args) != 1:
|
| 222 |
+
raise AssertionError("ceiling expects exactly one argument")
|
| 223 |
+
return f"math.ceil({self._print(expr.args[0])})"
|
| 224 |
+
|
| 225 |
+
def _print_CeilToInt(self, expr: sympy.Expr) -> str:
|
| 226 |
+
if len(expr.args) != 1:
|
| 227 |
+
raise AssertionError("CeilToInt expects exactly one argument")
|
| 228 |
+
return f"math.ceil({self._print(expr.args[0])})"
|
| 229 |
+
|
| 230 |
+
def _print_Abs(self, expr: sympy.Expr) -> str:
|
| 231 |
+
if len(expr.args) != 1:
|
| 232 |
+
raise AssertionError("Abs expects exactly one argument")
|
| 233 |
+
return f"abs({self._print(expr.args[0])})"
|
| 234 |
+
|
| 235 |
+
# NB: It's expected that we've made explicit any promotion in the sympy
|
| 236 |
+
# expression, so it doesn't matter that Python max/min doesn't perform
|
| 237 |
+
# promotion
|
| 238 |
+
def _print_Max(self, expr: sympy.Expr) -> str:
|
| 239 |
+
if len(expr.args) < 2:
|
| 240 |
+
raise AssertionError("Max expects at least two arguments")
|
| 241 |
+
return f"max({', '.join(map(self._print, expr.args))})"
|
| 242 |
+
|
| 243 |
+
def _print_Min(self, expr: sympy.Expr) -> str:
|
| 244 |
+
if len(expr.args) < 2:
|
| 245 |
+
raise AssertionError("Min expects at least two arguments")
|
| 246 |
+
return f"min({', '.join(map(self._print, expr.args))})"
|
| 247 |
+
|
| 248 |
+
def _print_OpaqueUnaryFn_cos(self, expr: sympy.Expr) -> str:
|
| 249 |
+
if len(expr.args) != 1:
|
| 250 |
+
raise AssertionError("cos expects exactly one argument")
|
| 251 |
+
return f"math.cos({self._print(expr.args[0])})"
|
| 252 |
+
|
| 253 |
+
def _print_OpaqueUnaryFn_cosh(self, expr: sympy.Expr) -> str:
|
| 254 |
+
if len(expr.args) != 1:
|
| 255 |
+
raise AssertionError("cosh expects exactly one argument")
|
| 256 |
+
return f"math.cosh({self._print(expr.args[0])})"
|
| 257 |
+
|
| 258 |
+
def _print_OpaqueUnaryFn_acos(self, expr: sympy.Expr) -> str:
|
| 259 |
+
if len(expr.args) != 1:
|
| 260 |
+
raise AssertionError("acos expects exactly one argument")
|
| 261 |
+
return f"math.acos({self._print(expr.args[0])})"
|
| 262 |
+
|
| 263 |
+
def _print_OpaqueUnaryFn_sin(self, expr: sympy.Expr) -> str:
|
| 264 |
+
if len(expr.args) != 1:
|
| 265 |
+
raise AssertionError("sin expects exactly one argument")
|
| 266 |
+
return f"math.sin({self._print(expr.args[0])})"
|
| 267 |
+
|
| 268 |
+
def _print_OpaqueUnaryFn_sinh(self, expr: sympy.Expr) -> str:
|
| 269 |
+
if len(expr.args) != 1:
|
| 270 |
+
raise AssertionError("sinh expects exactly one argument")
|
| 271 |
+
return f"math.sinh({self._print(expr.args[0])})"
|
| 272 |
+
|
| 273 |
+
def _print_OpaqueUnaryFn_asin(self, expr: sympy.Expr) -> str:
|
| 274 |
+
if len(expr.args) != 1:
|
| 275 |
+
raise AssertionError("asin expects exactly one argument")
|
| 276 |
+
return f"math.asin({self._print(expr.args[0])})"
|
| 277 |
+
|
| 278 |
+
def _print_OpaqueUnaryFn_tan(self, expr: sympy.Expr) -> str:
|
| 279 |
+
if len(expr.args) != 1:
|
| 280 |
+
raise AssertionError("tan expects exactly one argument")
|
| 281 |
+
return f"math.tan({self._print(expr.args[0])})"
|
| 282 |
+
|
| 283 |
+
def _print_OpaqueUnaryFn_tanh(self, expr: sympy.Expr) -> str:
|
| 284 |
+
if len(expr.args) != 1:
|
| 285 |
+
raise AssertionError("tanh expects exactly one argument")
|
| 286 |
+
return f"math.tanh({self._print(expr.args[0])})"
|
| 287 |
+
|
| 288 |
+
def _print_OpaqueUnaryFn_atan(self, expr: sympy.Expr) -> str:
|
| 289 |
+
if len(expr.args) != 1:
|
| 290 |
+
raise AssertionError("atan expects exactly one argument")
|
| 291 |
+
return f"math.atan({self._print(expr.args[0])})"
|
| 292 |
+
|
| 293 |
+
def _print_OpaqueUnaryFn_log2(self, expr: sympy.Expr) -> str:
|
| 294 |
+
if len(expr.args) != 1:
|
| 295 |
+
raise AssertionError("log2 expects exactly one argument")
|
| 296 |
+
return f"math.log2({self._print(expr.args[0])})"
|
| 297 |
+
|
| 298 |
+
def _print_RoundToInt(self, expr: sympy.Expr) -> str:
|
| 299 |
+
if len(expr.args) != 1:
|
| 300 |
+
raise AssertionError("RoundToInt expects exactly one argument")
|
| 301 |
+
return f"round({self._print(expr.args[0])})"
|
| 302 |
+
|
| 303 |
+
def _print_RoundDecimal(self, expr: sympy.Expr) -> str:
|
| 304 |
+
if len(expr.args) != 2:
|
| 305 |
+
raise AssertionError("RoundDecimal expects exactly two arguments")
|
| 306 |
+
number, ndigits = expr.args
|
| 307 |
+
if not isinstance(ndigits, sympy.Integer):
|
| 308 |
+
raise TypeError("ndigits must be an instance of sympy.Integer")
|
| 309 |
+
return f"round({self._print(number)}, {ndigits})"
|
| 310 |
+
|
| 311 |
+
def _print_Piecewise(self, expr: sympy.Expr) -> str:
|
| 312 |
+
# Convert Piecewise(expr_cond_pairs) to nested ternary expressions
|
| 313 |
+
# Piecewise((e1, c1), (e2, c2), ..., (eN, cN))
|
| 314 |
+
# becomes: e1 if c1 else (e2 if c2 else (... else eN))
|
| 315 |
+
result: str | None = None
|
| 316 |
+
for expr_i, cond_i in reversed(expr.args):
|
| 317 |
+
expr_str = self._print(expr_i)
|
| 318 |
+
if cond_i == True: # noqa: E712
|
| 319 |
+
# This is the default case
|
| 320 |
+
result = expr_str
|
| 321 |
+
else:
|
| 322 |
+
cond_str = self._print(cond_i)
|
| 323 |
+
if result is None:
|
| 324 |
+
result = expr_str
|
| 325 |
+
else:
|
| 326 |
+
result = f"({expr_str} if {cond_str} else {result})"
|
| 327 |
+
return result if result else "0"
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
class CppPrinter(ExprPrinter):
|
| 331 |
+
def _print_Integer(self, expr: sympy.Expr) -> str:
|
| 332 |
+
suffix = "LL" if sys.platform in ["darwin", "win32"] else "L"
|
| 333 |
+
i = int(expr)
|
| 334 |
+
if i > INDEX_TYPE_MAX or i < INDEX_TYPE_MIN:
|
| 335 |
+
raise OverflowError(f"{i} too big to convert to {INDEX_TYPE}")
|
| 336 |
+
elif i == INDEX_TYPE_MIN:
|
| 337 |
+
if i != (-1) << 63:
|
| 338 |
+
raise AssertionError("unexpected minimum index type value")
|
| 339 |
+
# Writing -9223372036854775808L makes the value overflow
|
| 340 |
+
# as it is parsed as -(9223372036854775808L) by the C/C++ compiler
|
| 341 |
+
return f"(-1{suffix} << 63)"
|
| 342 |
+
return f"{i}{suffix}"
|
| 343 |
+
|
| 344 |
+
def _print_Where(self, expr: sympy.Expr) -> str:
|
| 345 |
+
c, p, q = (
|
| 346 |
+
self.parenthesize(arg, PRECEDENCE["Atom"] - 0.5) for arg in expr.args
|
| 347 |
+
)
|
| 348 |
+
return f"{c} ? {p} : {q}"
|
| 349 |
+
|
| 350 |
+
def _print_Piecewise(self, expr: sympy.Expr) -> str:
|
| 351 |
+
# Convert Piecewise(expr_cond_pairs) to nested ternary operators
|
| 352 |
+
# Piecewise((e1, c1), (e2, c2), ..., (eN, cN))
|
| 353 |
+
# becomes: c1 ? e1 : (c2 ? e2 : (... : eN))
|
| 354 |
+
result: str | None = None
|
| 355 |
+
for expr_i, cond_i in reversed(expr.args):
|
| 356 |
+
expr_str = self.parenthesize(expr_i, PRECEDENCE["Atom"] - 0.5)
|
| 357 |
+
if cond_i == True: # noqa: E712
|
| 358 |
+
# This is the default case
|
| 359 |
+
result = expr_str
|
| 360 |
+
else:
|
| 361 |
+
cond_str = self.parenthesize(cond_i, PRECEDENCE["Atom"] - 0.5)
|
| 362 |
+
if result is None:
|
| 363 |
+
result = expr_str
|
| 364 |
+
else:
|
| 365 |
+
result = f"{cond_str} ? {expr_str} : {result}"
|
| 366 |
+
return f"({result})" if result else "0"
|
| 367 |
+
|
| 368 |
+
def _print_ModularIndexing(self, expr: sympy.Expr) -> str:
|
| 369 |
+
x, div, mod = expr.args
|
| 370 |
+
x = self.doprint(x)
|
| 371 |
+
if div != 1:
|
| 372 |
+
div = self.doprint(div)
|
| 373 |
+
if expr.is_integer:
|
| 374 |
+
x = f"c10::div_floor_integer(static_cast<int64_t>({x}), static_cast<int64_t>({div}))"
|
| 375 |
+
else:
|
| 376 |
+
x = f"c10::div_floor_floating(static_cast<double>({x}), static_cast<double>({div}))"
|
| 377 |
+
mod = self.doprint(mod)
|
| 378 |
+
return f"(static_cast<{INDEX_TYPE}>({x}) % static_cast<{INDEX_TYPE}>({mod}))"
|
| 379 |
+
|
| 380 |
+
def _print_FloorDiv(self, expr: sympy.Expr) -> str:
|
| 381 |
+
x, div = expr.args
|
| 382 |
+
x = self.doprint(x)
|
| 383 |
+
div = self.doprint(div)
|
| 384 |
+
if expr.is_integer:
|
| 385 |
+
return f"c10::div_floor_integer(static_cast<int64_t>({x}), static_cast<int64_t>({div}))"
|
| 386 |
+
return f"c10::div_floor_floating(static_cast<double>({x}), static_cast<double>({div}))"
|
| 387 |
+
|
| 388 |
+
def _print_floor(self, expr: sympy.Expr) -> str:
|
| 389 |
+
if len(expr.args) != 1:
|
| 390 |
+
raise AssertionError("floor expects exactly one argument")
|
| 391 |
+
r = f"std::floor({self._print(expr.args[0])})"
|
| 392 |
+
return f"static_cast<{INDEX_TYPE}>({r})" if expr.is_integer else r
|
| 393 |
+
|
| 394 |
+
def _print_FloorToInt(self, expr: sympy.Expr) -> str:
|
| 395 |
+
if len(expr.args) != 1:
|
| 396 |
+
raise AssertionError("FloorToInt expects exactly one argument")
|
| 397 |
+
r = f"std::floor({self._print(expr.args[0])})"
|
| 398 |
+
return f"static_cast<{INDEX_TYPE}>({r})" if expr.is_integer else r
|
| 399 |
+
|
| 400 |
+
def _print_TruncToInt(self, expr: sympy.Expr) -> str:
|
| 401 |
+
if len(expr.args) != 1:
|
| 402 |
+
raise AssertionError("TruncToInt expects exactly one argument")
|
| 403 |
+
r = f"std::trunc({self._print(expr.args[0])})"
|
| 404 |
+
return f"static_cast<{INDEX_TYPE}>({r})"
|
| 405 |
+
|
| 406 |
+
def _print_TruncToFloat(self, expr: sympy.Expr) -> str:
|
| 407 |
+
if len(expr.args) != 1:
|
| 408 |
+
raise AssertionError("TruncToFloat expects exactly one argument")
|
| 409 |
+
return f"std::trunc({self._print(expr.args[0])})"
|
| 410 |
+
|
| 411 |
+
def _print_ToFloat(self, expr: sympy.Expr) -> str:
|
| 412 |
+
if len(expr.args) != 1:
|
| 413 |
+
raise AssertionError("ToFloat expects exactly one argument")
|
| 414 |
+
return f"static_cast<double>({self._print(expr.args[0])})"
|
| 415 |
+
|
| 416 |
+
def _print_PythonMod(self, expr: sympy.Expr) -> str:
|
| 417 |
+
x, div = expr.args
|
| 418 |
+
x = self.doprint(x)
|
| 419 |
+
div = self.doprint(div)
|
| 420 |
+
return f"c10::div_mod({x}, {div})"
|
| 421 |
+
|
| 422 |
+
def _print_IntTrueDiv(self, expr: sympy.Expr) -> str:
|
| 423 |
+
lhs, rhs = expr.args
|
| 424 |
+
# TODO: This is only accurate up to 2**53
|
| 425 |
+
return f"static_cast<double>({self._print(lhs)}) / static_cast<double>({self._print(rhs)})"
|
| 426 |
+
|
| 427 |
+
# TODO: PowByNatural: we need to implement our own int-int pow. Do NOT
|
| 428 |
+
# use std::pow, that operates on floats
|
| 429 |
+
def _print_PowByNatural(self, expr: sympy.Expr) -> str:
|
| 430 |
+
# Implement the special-case of 2**x for now
|
| 431 |
+
base, exp = expr.args
|
| 432 |
+
if base == 2:
|
| 433 |
+
return f"(1 << ({self._print(exp)}))"
|
| 434 |
+
raise NotImplementedError(
|
| 435 |
+
f"_print_PowByNatural not implemented for {type(self)}"
|
| 436 |
+
)
|
| 437 |
+
|
| 438 |
+
def _print_FloatPow(self, expr: sympy.Expr) -> str:
|
| 439 |
+
base, exp = expr.args
|
| 440 |
+
return f"std::pow({self._print(base)}, {self._print(exp)})"
|
| 441 |
+
|
| 442 |
+
def _print_Pow(self, expr: sympy.Expr) -> str:
|
| 443 |
+
# Uses float constants to perform FP div
|
| 444 |
+
base, exp = expr.args
|
| 445 |
+
|
| 446 |
+
if exp == 0.5 or exp == -0.5:
|
| 447 |
+
base = self._print(base)
|
| 448 |
+
return f"std::sqrt({base})" if exp == 0.5 else f"1.0/std::sqrt({base})"
|
| 449 |
+
if exp.is_integer:
|
| 450 |
+
exp = int(exp)
|
| 451 |
+
if exp > 0:
|
| 452 |
+
r = self.stringify([base] * exp, "*", PRECEDENCE["Mul"])
|
| 453 |
+
elif exp < -1:
|
| 454 |
+
r = (
|
| 455 |
+
"1.0/("
|
| 456 |
+
+ self.stringify([base] * abs(exp), "*", PRECEDENCE["Mul"])
|
| 457 |
+
+ ")"
|
| 458 |
+
)
|
| 459 |
+
elif exp == -1:
|
| 460 |
+
r = "1.0/" + self._print(base)
|
| 461 |
+
else: # exp == 0
|
| 462 |
+
r = "1.0"
|
| 463 |
+
|
| 464 |
+
return f"static_cast<{INDEX_TYPE}>({r})" if expr.is_integer else r
|
| 465 |
+
else:
|
| 466 |
+
# TODO: float vs double
|
| 467 |
+
return f"std::pow({base}, {float(exp)})"
|
| 468 |
+
|
| 469 |
+
def _print_Rational(self, expr: sympy.Expr) -> str:
|
| 470 |
+
# Uses float constants to perform FP div
|
| 471 |
+
if expr.q == 1:
|
| 472 |
+
r = f"{expr.p}"
|
| 473 |
+
else:
|
| 474 |
+
r = f"{expr.p}.0/{expr.q}.0"
|
| 475 |
+
return f"static_cast<{INDEX_TYPE}>({r})" if expr.is_integer else r
|
| 476 |
+
|
| 477 |
+
def _print_ceiling(self, expr: sympy.Expr) -> str:
|
| 478 |
+
if len(expr.args) != 1:
|
| 479 |
+
raise AssertionError("ceiling expects exactly one argument")
|
| 480 |
+
r = f"std::ceil({self._print(expr.args[0])})"
|
| 481 |
+
return f"static_cast<{INDEX_TYPE}>({r})" if expr.is_integer else r
|
| 482 |
+
|
| 483 |
+
def _print_CeilToInt(self, expr: sympy.Expr) -> str:
|
| 484 |
+
if len(expr.args) != 1:
|
| 485 |
+
raise AssertionError("CeilToInt expects exactly one argument")
|
| 486 |
+
r = f"std::ceil({self._print(expr.args[0])})"
|
| 487 |
+
return f"static_cast<{INDEX_TYPE}>({r})" if expr.is_integer else r
|
| 488 |
+
|
| 489 |
+
def _print_Min(self, expr: sympy.Expr) -> str:
|
| 490 |
+
args = [self._print(a) for a in expr.args]
|
| 491 |
+
if len(args) == 2:
|
| 492 |
+
return f"std::min(static_cast<{INDEX_TYPE}>({args[0]}), static_cast<{INDEX_TYPE}>({args[1]}))"
|
| 493 |
+
else:
|
| 494 |
+
# Initializer list overload
|
| 495 |
+
il = "{" + ", ".join(args) + "}"
|
| 496 |
+
return f"std::min<{INDEX_TYPE}>({il})"
|
| 497 |
+
|
| 498 |
+
def _print_Max(self, expr: sympy.Expr) -> str:
|
| 499 |
+
args = [self._print(a) for a in expr.args]
|
| 500 |
+
if len(args) == 2:
|
| 501 |
+
return f"std::max(static_cast<{INDEX_TYPE}>({args[0]}), static_cast<{INDEX_TYPE}>({args[1]}))"
|
| 502 |
+
else:
|
| 503 |
+
# Initializer list overload
|
| 504 |
+
il = "{" + ", ".join(args) + "}"
|
| 505 |
+
return f"std::max<{INDEX_TYPE}>({il})"
|
| 506 |
+
|
| 507 |
+
def _print_Abs(self, expr: sympy.Expr) -> str:
|
| 508 |
+
if len(expr.args) != 1:
|
| 509 |
+
raise AssertionError("Abs expects exactly one argument")
|
| 510 |
+
return f"std::abs({self._print(expr.args[0])})"
|
| 511 |
+
|
| 512 |
+
def _print_OpaqueUnaryFn_cos(self, expr: sympy.Expr) -> str:
|
| 513 |
+
if len(expr.args) != 1:
|
| 514 |
+
raise AssertionError("cos expects exactly one argument")
|
| 515 |
+
return f"std::cos({self._print(expr.args[0])})"
|
| 516 |
+
|
| 517 |
+
def _print_OpaqueUnaryFn_cosh(self, expr: sympy.Expr) -> str:
|
| 518 |
+
if len(expr.args) != 1:
|
| 519 |
+
raise AssertionError("cosh expects exactly one argument")
|
| 520 |
+
return f"std::cosh({self._print(expr.args[0])})"
|
| 521 |
+
|
| 522 |
+
def _print_OpaqueUnaryFn_acos(self, expr: sympy.Expr) -> str:
|
| 523 |
+
if len(expr.args) != 1:
|
| 524 |
+
raise AssertionError("acos expects exactly one argument")
|
| 525 |
+
return f"std::acos({self._print(expr.args[0])})"
|
| 526 |
+
|
| 527 |
+
def _print_OpaqueUnaryFn_sin(self, expr: sympy.Expr) -> str:
|
| 528 |
+
if len(expr.args) != 1:
|
| 529 |
+
raise AssertionError("sin expects exactly one argument")
|
| 530 |
+
return f"math.sin({self._print(expr.args[0])})"
|
| 531 |
+
|
| 532 |
+
def _print_OpaqueUnaryFn_sinh(self, expr: sympy.Expr) -> str:
|
| 533 |
+
if len(expr.args) != 1:
|
| 534 |
+
raise AssertionError("sinh expects exactly one argument")
|
| 535 |
+
return f"std::sinh({self._print(expr.args[0])})"
|
| 536 |
+
|
| 537 |
+
def _print_OpaqueUnaryFn_asin(self, expr: sympy.Expr) -> str:
|
| 538 |
+
if len(expr.args) != 1:
|
| 539 |
+
raise AssertionError("asin expects exactly one argument")
|
| 540 |
+
return f"std::asin({self._print(expr.args[0])})"
|
| 541 |
+
|
| 542 |
+
def _print_OpaqueUnaryFn_tan(self, expr: sympy.Expr) -> str:
|
| 543 |
+
if len(expr.args) != 1:
|
| 544 |
+
raise AssertionError("tan expects exactly one argument")
|
| 545 |
+
return f"std::tan({self._print(expr.args[0])})"
|
| 546 |
+
|
| 547 |
+
def _print_OpaqueUnaryFn_tanh(self, expr: sympy.Expr) -> str:
|
| 548 |
+
if len(expr.args) != 1:
|
| 549 |
+
raise AssertionError("tanh expects exactly one argument")
|
| 550 |
+
return f"std::tanh({self._print(expr.args[0])})"
|
| 551 |
+
|
| 552 |
+
def _print_OpaqueUnaryFn_atan(self, expr: sympy.Expr) -> str:
|
| 553 |
+
if len(expr.args) != 1:
|
| 554 |
+
raise AssertionError("atan expects exactly one argument")
|
| 555 |
+
return f"std::atan({self._print(expr.args[0])})"
|
| 556 |
+
|
| 557 |
+
def _print_OpaqueUnaryFn_sqrt(self, expr: sympy.Expr) -> str:
|
| 558 |
+
return f"std::sqrt({self._print(expr.args[0])})"
|
| 559 |
+
|
| 560 |
+
def _print_OpaqueUnaryFn_log2(self, expr: sympy.Expr) -> str:
|
| 561 |
+
return f"std::log2({self._print(expr.args[0])})"
|
| 562 |
+
|
| 563 |
+
def _print_RoundToInt(self, expr: sympy.Expr) -> str:
|
| 564 |
+
if len(expr.args) != 1:
|
| 565 |
+
raise AssertionError("RoundToInt expects exactly one argument")
|
| 566 |
+
# TODO: dispatch to llrint depending on index type
|
| 567 |
+
return f"std::lrint({self._print(expr.args[0])})"
|
| 568 |
+
|
| 569 |
+
def _print_RoundDecimal(self, expr: sympy.Expr) -> str:
|
| 570 |
+
if len(expr.args) != 2:
|
| 571 |
+
raise AssertionError("RoundDecimal expects exactly two arguments")
|
| 572 |
+
number, ndigits = expr.args
|
| 573 |
+
if number.is_integer:
|
| 574 |
+
# ndigits < 0 should have been filtered by the sympy function
|
| 575 |
+
if ndigits >= 0:
|
| 576 |
+
raise AssertionError("ndigits must be negative for integer inputs")
|
| 577 |
+
raise ValueError(
|
| 578 |
+
f"For integer inputs, only non-negative ndigits are currently supported, but got {ndigits}."
|
| 579 |
+
)
|
| 580 |
+
number_str = self.parenthesize(number, PRECEDENCE["Mul"])
|
| 581 |
+
return f"static_cast<double>(std::nearbyint(1e{ndigits} * {number_str}) * 1e{-ndigits})"
|
| 582 |
+
|
| 583 |
+
def _print_BooleanTrue(self, expr: sympy.Expr) -> str:
|
| 584 |
+
return "true"
|
| 585 |
+
|
| 586 |
+
def _print_BooleanFalse(self, expr: sympy.Expr) -> str:
|
| 587 |
+
return "false"
|
| 588 |
+
|
| 589 |
+
def _print_Infinity(self, expr: sympy.Expr) -> str:
|
| 590 |
+
return "std::numeric_limits<double>::infinity()"
|
| 591 |
+
|
| 592 |
+
def _print_NegativeInfinity(self, expr: sympy.Expr) -> str:
|
| 593 |
+
return f"-{self._print_Infinity(expr)}"
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/_sympy/reference.py
ADDED
|
@@ -0,0 +1,600 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import math
|
| 3 |
+
import operator
|
| 4 |
+
from typing import NoReturn
|
| 5 |
+
|
| 6 |
+
import sympy
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
from torch.utils._sympy.functions import (
|
| 10 |
+
_keep_float,
|
| 11 |
+
BitwiseFn_bitwise_and,
|
| 12 |
+
BitwiseFn_bitwise_or,
|
| 13 |
+
BitwiseFn_bitwise_xor,
|
| 14 |
+
FloatPow,
|
| 15 |
+
FloatTrueDiv,
|
| 16 |
+
FloorDiv,
|
| 17 |
+
IntTrueDiv,
|
| 18 |
+
Max,
|
| 19 |
+
Min,
|
| 20 |
+
Mod,
|
| 21 |
+
OpaqueUnaryFn_exp,
|
| 22 |
+
OpaqueUnaryFn_log,
|
| 23 |
+
OpaqueUnaryFn_log2,
|
| 24 |
+
OpaqueUnaryFn_sqrt,
|
| 25 |
+
PowByNatural,
|
| 26 |
+
RoundDecimal,
|
| 27 |
+
RoundToInt,
|
| 28 |
+
ToFloat,
|
| 29 |
+
TruncToInt,
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
# The sympy interpretation of operators. It will also sometimes work with
|
| 34 |
+
# plain int/float, but if you do certain operations you will get out a
|
| 35 |
+
# sympy.Basic in the end. If you want the Python/FX traceable interpretation,
|
| 36 |
+
# check PythonReferenceAnalysis.
|
| 37 |
+
# NB: For magic methods this needs to use normal magic methods
|
| 38 |
+
# so that test_magic_methods works
|
| 39 |
+
class ReferenceAnalysis:
|
| 40 |
+
@staticmethod
|
| 41 |
+
def constant(c, dtype):
|
| 42 |
+
return sympy.sympify(c)
|
| 43 |
+
|
| 44 |
+
@staticmethod
|
| 45 |
+
def or_(a, b):
|
| 46 |
+
return a | b
|
| 47 |
+
|
| 48 |
+
@staticmethod
|
| 49 |
+
def and_(a, b):
|
| 50 |
+
return a & b
|
| 51 |
+
|
| 52 |
+
@staticmethod
|
| 53 |
+
def eq(a, b):
|
| 54 |
+
if isinstance(a, sympy.Expr) or isinstance(b, sympy.Expr):
|
| 55 |
+
return sympy.Eq(a, b)
|
| 56 |
+
return a == b
|
| 57 |
+
|
| 58 |
+
@classmethod
|
| 59 |
+
def ne(cls, a, b):
|
| 60 |
+
return cls.not_(cls.eq(a, b))
|
| 61 |
+
|
| 62 |
+
@staticmethod
|
| 63 |
+
def lt(a, b):
|
| 64 |
+
return a < b
|
| 65 |
+
|
| 66 |
+
@staticmethod
|
| 67 |
+
def gt(a, b):
|
| 68 |
+
return a > b
|
| 69 |
+
|
| 70 |
+
@staticmethod
|
| 71 |
+
def le(a, b):
|
| 72 |
+
return a <= b
|
| 73 |
+
|
| 74 |
+
@staticmethod
|
| 75 |
+
def ge(a, b):
|
| 76 |
+
return a >= b
|
| 77 |
+
|
| 78 |
+
@staticmethod
|
| 79 |
+
def not_(a):
|
| 80 |
+
if isinstance(a, bool):
|
| 81 |
+
raise AssertionError("not_ needs sympy expr")
|
| 82 |
+
return ~a
|
| 83 |
+
|
| 84 |
+
@staticmethod
|
| 85 |
+
def reciprocal(x):
|
| 86 |
+
return FloatTrueDiv(1.0, x)
|
| 87 |
+
|
| 88 |
+
@staticmethod
|
| 89 |
+
def square(x):
|
| 90 |
+
return PowByNatural(x, 2)
|
| 91 |
+
|
| 92 |
+
@staticmethod
|
| 93 |
+
def trunc_to_int(x, dtype):
|
| 94 |
+
return TruncToInt(x)
|
| 95 |
+
|
| 96 |
+
@staticmethod
|
| 97 |
+
def ceil_to_int(x, dtype):
|
| 98 |
+
return sympy.ceiling(x)
|
| 99 |
+
|
| 100 |
+
@staticmethod
|
| 101 |
+
def floor_to_int(x, dtype):
|
| 102 |
+
return sympy.floor(x)
|
| 103 |
+
|
| 104 |
+
@staticmethod
|
| 105 |
+
def floor(x):
|
| 106 |
+
return _keep_float(sympy.floor)(x)
|
| 107 |
+
|
| 108 |
+
@staticmethod
|
| 109 |
+
def ceil(x):
|
| 110 |
+
return _keep_float(sympy.ceiling)(x)
|
| 111 |
+
|
| 112 |
+
@staticmethod
|
| 113 |
+
def to_dtype(x, dtype):
|
| 114 |
+
if dtype == torch.float64:
|
| 115 |
+
return ToFloat(x)
|
| 116 |
+
raise NotImplementedError(f"to_dtype {dtype} NYI")
|
| 117 |
+
|
| 118 |
+
@staticmethod
|
| 119 |
+
def mod(x, y):
|
| 120 |
+
return Mod(x, y)
|
| 121 |
+
|
| 122 |
+
@staticmethod
|
| 123 |
+
def abs(x):
|
| 124 |
+
return abs(x)
|
| 125 |
+
|
| 126 |
+
@staticmethod
|
| 127 |
+
def neg(x):
|
| 128 |
+
return -x
|
| 129 |
+
|
| 130 |
+
@staticmethod
|
| 131 |
+
def truediv(a, b):
|
| 132 |
+
return FloatTrueDiv(a, b)
|
| 133 |
+
|
| 134 |
+
@staticmethod
|
| 135 |
+
def int_truediv(a, b):
|
| 136 |
+
return IntTrueDiv(a, b)
|
| 137 |
+
|
| 138 |
+
@staticmethod
|
| 139 |
+
def floordiv(a, b):
|
| 140 |
+
return FloorDiv(a, b)
|
| 141 |
+
|
| 142 |
+
@staticmethod
|
| 143 |
+
def truncdiv(a, b) -> NoReturn:
|
| 144 |
+
raise NotImplementedError("TODO: truncdiv")
|
| 145 |
+
|
| 146 |
+
@staticmethod
|
| 147 |
+
def add(a, b):
|
| 148 |
+
return _keep_float(operator.add)(a, b)
|
| 149 |
+
|
| 150 |
+
@classmethod
|
| 151 |
+
def sym_sum(cls, args):
|
| 152 |
+
return sympy.Add(*args)
|
| 153 |
+
|
| 154 |
+
@staticmethod
|
| 155 |
+
def mul(a, b):
|
| 156 |
+
return _keep_float(operator.mul)(a, b)
|
| 157 |
+
|
| 158 |
+
@staticmethod
|
| 159 |
+
def sub(a, b):
|
| 160 |
+
return _keep_float(operator.sub)(a, b)
|
| 161 |
+
|
| 162 |
+
@staticmethod
|
| 163 |
+
def exp(x):
|
| 164 |
+
return OpaqueUnaryFn_exp(x)
|
| 165 |
+
|
| 166 |
+
@staticmethod
|
| 167 |
+
def log(x):
|
| 168 |
+
return OpaqueUnaryFn_log(x)
|
| 169 |
+
|
| 170 |
+
@staticmethod
|
| 171 |
+
def log2(x):
|
| 172 |
+
return OpaqueUnaryFn_log2(x)
|
| 173 |
+
|
| 174 |
+
@staticmethod
|
| 175 |
+
def sqrt(x):
|
| 176 |
+
return OpaqueUnaryFn_sqrt(x)
|
| 177 |
+
|
| 178 |
+
@staticmethod
|
| 179 |
+
def pow(a, b):
|
| 180 |
+
# pyrefly: ignore [bad-argument-type]
|
| 181 |
+
return _keep_float(FloatPow)(a, b)
|
| 182 |
+
|
| 183 |
+
@staticmethod
|
| 184 |
+
def pow_by_natural(a, b):
|
| 185 |
+
return PowByNatural(a, b)
|
| 186 |
+
|
| 187 |
+
@staticmethod
|
| 188 |
+
def minimum(a, b):
|
| 189 |
+
return Min(a, b)
|
| 190 |
+
|
| 191 |
+
@staticmethod
|
| 192 |
+
def maximum(a, b):
|
| 193 |
+
return Max(a, b)
|
| 194 |
+
|
| 195 |
+
@staticmethod
|
| 196 |
+
def round_to_int(a, dtype):
|
| 197 |
+
return RoundToInt(a)
|
| 198 |
+
|
| 199 |
+
@staticmethod
|
| 200 |
+
def round_decimal(a, b):
|
| 201 |
+
return RoundDecimal(a, b)
|
| 202 |
+
|
| 203 |
+
@staticmethod
|
| 204 |
+
def bitwise_and(a, b):
|
| 205 |
+
return BitwiseFn_bitwise_and(a, b)
|
| 206 |
+
|
| 207 |
+
@staticmethod
|
| 208 |
+
def bitwise_or(a, b):
|
| 209 |
+
return BitwiseFn_bitwise_or(a, b)
|
| 210 |
+
|
| 211 |
+
@staticmethod
|
| 212 |
+
def bitwise_xor(a, b):
|
| 213 |
+
return BitwiseFn_bitwise_xor(a, b)
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
# Unlike ReferenceAnalysis, does NOT sympyify, instead, works with plain
|
| 217 |
+
# Python types and is FX traceable. Inheritance here is purely for code
|
| 218 |
+
# sharing (TODO: considering splitting out a BaseReferenceAnalysis).
|
| 219 |
+
class PythonReferenceAnalysis(ReferenceAnalysis):
|
| 220 |
+
@staticmethod
|
| 221 |
+
def constant(c, dtype):
|
| 222 |
+
if dtype is torch.int64:
|
| 223 |
+
return int(c)
|
| 224 |
+
elif dtype is torch.double:
|
| 225 |
+
return float(c)
|
| 226 |
+
elif dtype is torch.bool:
|
| 227 |
+
return bool(c)
|
| 228 |
+
else:
|
| 229 |
+
raise AssertionError(f"unrecognized dtype {dtype}")
|
| 230 |
+
|
| 231 |
+
@staticmethod
|
| 232 |
+
def not_(a):
|
| 233 |
+
return torch.sym_not(a)
|
| 234 |
+
|
| 235 |
+
@classmethod
|
| 236 |
+
def sym_sum(cls, args):
|
| 237 |
+
if len(args) == 0:
|
| 238 |
+
return 0
|
| 239 |
+
if len(args) == 1:
|
| 240 |
+
return args[0]
|
| 241 |
+
acc = cls.add(args[0], args[1])
|
| 242 |
+
for i in range(2, len(args)):
|
| 243 |
+
acc = cls.add(acc, args[i])
|
| 244 |
+
return acc
|
| 245 |
+
|
| 246 |
+
@staticmethod
|
| 247 |
+
def floordiv(a, b):
|
| 248 |
+
return a // b
|
| 249 |
+
|
| 250 |
+
@staticmethod
|
| 251 |
+
def mod(x, y):
|
| 252 |
+
return x % y
|
| 253 |
+
|
| 254 |
+
@staticmethod
|
| 255 |
+
def python_mod(x, y):
|
| 256 |
+
return x % y
|
| 257 |
+
|
| 258 |
+
@staticmethod
|
| 259 |
+
def truncdiv(a, b):
|
| 260 |
+
return a / b
|
| 261 |
+
|
| 262 |
+
@staticmethod
|
| 263 |
+
def to_dtype(x, dtype):
|
| 264 |
+
if dtype == torch.float64:
|
| 265 |
+
return torch.sym_float(x)
|
| 266 |
+
raise NotImplementedError(f"to_dtype {dtype} NYI")
|
| 267 |
+
|
| 268 |
+
@staticmethod
|
| 269 |
+
def exp(x) -> NoReturn:
|
| 270 |
+
raise AssertionError("exp is not valid shape sympy expr")
|
| 271 |
+
|
| 272 |
+
@staticmethod
|
| 273 |
+
def log(x) -> NoReturn:
|
| 274 |
+
raise AssertionError("log is not valid shape sympy expr")
|
| 275 |
+
|
| 276 |
+
@staticmethod
|
| 277 |
+
def log2(x):
|
| 278 |
+
return torch._sym_log2(x) # type: ignore[attr-defined]
|
| 279 |
+
|
| 280 |
+
@staticmethod
|
| 281 |
+
def sqrt(x):
|
| 282 |
+
return torch._sym_sqrt(x) # type: ignore[attr-defined]
|
| 283 |
+
|
| 284 |
+
@staticmethod
|
| 285 |
+
def minimum(a, b):
|
| 286 |
+
return torch.sym_min(a, b)
|
| 287 |
+
|
| 288 |
+
@staticmethod
|
| 289 |
+
def maximum(a, b):
|
| 290 |
+
return torch.sym_max(a, b)
|
| 291 |
+
|
| 292 |
+
@staticmethod
|
| 293 |
+
def floor_to_int(x, dtype):
|
| 294 |
+
return math.floor(x)
|
| 295 |
+
|
| 296 |
+
@staticmethod
|
| 297 |
+
def ceil_to_int(x, dtype):
|
| 298 |
+
return math.ceil(x)
|
| 299 |
+
|
| 300 |
+
@staticmethod
|
| 301 |
+
def floor(x):
|
| 302 |
+
return float(math.floor(x))
|
| 303 |
+
|
| 304 |
+
@staticmethod
|
| 305 |
+
def ceil(x):
|
| 306 |
+
return float(math.ceil(x))
|
| 307 |
+
|
| 308 |
+
@staticmethod
|
| 309 |
+
def truediv(a, b):
|
| 310 |
+
return a / b
|
| 311 |
+
|
| 312 |
+
@staticmethod
|
| 313 |
+
def pow(a, b):
|
| 314 |
+
return a**b
|
| 315 |
+
|
| 316 |
+
@staticmethod
|
| 317 |
+
def pow_by_natural(a, b):
|
| 318 |
+
# Pray that safe_pow is not needed here lol. In particular, this
|
| 319 |
+
# never participates in VR low/high ranges, so overflow should be
|
| 320 |
+
# unlikely
|
| 321 |
+
return a**b
|
| 322 |
+
|
| 323 |
+
@staticmethod
|
| 324 |
+
def round_to_int(a, dtype):
|
| 325 |
+
return round(a)
|
| 326 |
+
|
| 327 |
+
@staticmethod
|
| 328 |
+
def round_decimal(a, b):
|
| 329 |
+
return round(a, ndigits=b)
|
| 330 |
+
|
| 331 |
+
@staticmethod
|
| 332 |
+
def bitwise_and(a, b):
|
| 333 |
+
return a & b
|
| 334 |
+
|
| 335 |
+
@staticmethod
|
| 336 |
+
def bitwise_or(a, b):
|
| 337 |
+
return a | b
|
| 338 |
+
|
| 339 |
+
@staticmethod
|
| 340 |
+
def bitwise_xor(a, b):
|
| 341 |
+
return a ^ b
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
# Like PythonReferenceAnalysis, but some export-unfriendly choices of
|
| 345 |
+
# operators to make things faster
|
| 346 |
+
class OptimizedPythonReferenceAnalysis(PythonReferenceAnalysis):
|
| 347 |
+
@staticmethod
|
| 348 |
+
def sym_sum(args):
|
| 349 |
+
return torch.sym_sum(args)
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
def _to_dtype(x: torch.Tensor, dtype: torch.dtype) -> torch.Tensor:
|
| 353 |
+
return torch.ops.prims.convert_element_type.default(x, dtype)
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
# Suppose we have some int/float arguments. This diagram commutes:
|
| 357 |
+
#
|
| 358 |
+
# int/float -- PythonReferenceAnalysis.op --> int/float
|
| 359 |
+
# | |
|
| 360 |
+
# | |
|
| 361 |
+
# torch.tensor(..., dtype=torch.int64/torch.float64)
|
| 362 |
+
# | |
|
| 363 |
+
# V V
|
| 364 |
+
# Tensor -- TensorReferenceAnalysis.op --> Tensor
|
| 365 |
+
#
|
| 366 |
+
# NB: int before and after must be representable in int64 (we will
|
| 367 |
+
# insert guards accordingly.)
|
| 368 |
+
#
|
| 369 |
+
# This is guaranteed to be FX traceable with OpOverloads only.
|
| 370 |
+
class TensorReferenceAnalysis:
|
| 371 |
+
# NB: This is actually dead, because with Proxy tracing the factory
|
| 372 |
+
# function isn't traced correctly. Here for completeness.
|
| 373 |
+
@staticmethod
|
| 374 |
+
def constant(c, dtype):
|
| 375 |
+
d: int | float | bool
|
| 376 |
+
if dtype is torch.int64:
|
| 377 |
+
d = int(c)
|
| 378 |
+
elif dtype is torch.double:
|
| 379 |
+
d = float(c)
|
| 380 |
+
elif dtype is torch.bool:
|
| 381 |
+
d = bool(c)
|
| 382 |
+
else:
|
| 383 |
+
raise AssertionError(f"unrecognized dtype {dtype}")
|
| 384 |
+
return torch.ops.aten.scalar_tensor.default(d, dtype=dtype)
|
| 385 |
+
|
| 386 |
+
@staticmethod
|
| 387 |
+
def or_(a, b):
|
| 388 |
+
return torch.ops.aten.logical_or.default(a, b)
|
| 389 |
+
|
| 390 |
+
@staticmethod
|
| 391 |
+
def and_(a, b):
|
| 392 |
+
return torch.ops.aten.logical_and.default(a, b)
|
| 393 |
+
|
| 394 |
+
@staticmethod
|
| 395 |
+
def bitwise_and(a, b):
|
| 396 |
+
return torch.ops.aten.bitwise_and(a, b)
|
| 397 |
+
|
| 398 |
+
@staticmethod
|
| 399 |
+
def bitwise_or(a, b):
|
| 400 |
+
return torch.ops.aten.bitwise_or(a, b)
|
| 401 |
+
|
| 402 |
+
@staticmethod
|
| 403 |
+
def bitwise_xor(a, b):
|
| 404 |
+
return torch.ops.aten.bitwise_xor(a, b)
|
| 405 |
+
|
| 406 |
+
@staticmethod
|
| 407 |
+
def eq(a, b):
|
| 408 |
+
return torch.ops.aten.eq.Tensor(a, b)
|
| 409 |
+
|
| 410 |
+
@classmethod
|
| 411 |
+
def ne(cls, a, b):
|
| 412 |
+
return torch.ops.aten.ne.Tensor(a, b)
|
| 413 |
+
|
| 414 |
+
@staticmethod
|
| 415 |
+
def lt(a, b):
|
| 416 |
+
return torch.ops.aten.lt.Tensor(a, b)
|
| 417 |
+
|
| 418 |
+
@staticmethod
|
| 419 |
+
def gt(a, b):
|
| 420 |
+
return torch.ops.aten.gt.Tensor(a, b)
|
| 421 |
+
|
| 422 |
+
@staticmethod
|
| 423 |
+
def le(a, b):
|
| 424 |
+
return torch.ops.aten.le.Tensor(a, b)
|
| 425 |
+
|
| 426 |
+
@staticmethod
|
| 427 |
+
def ge(a, b):
|
| 428 |
+
return torch.ops.aten.ge.Tensor(a, b)
|
| 429 |
+
|
| 430 |
+
@staticmethod
|
| 431 |
+
def not_(a):
|
| 432 |
+
return torch.ops.aten.logical_not.default(a)
|
| 433 |
+
|
| 434 |
+
@staticmethod
|
| 435 |
+
def reciprocal(x):
|
| 436 |
+
return torch.ops.aten.reciprocal.default(x)
|
| 437 |
+
|
| 438 |
+
@staticmethod
|
| 439 |
+
def square(x):
|
| 440 |
+
# TODO: maybe composite implicit autograd doesn't work here?
|
| 441 |
+
return torch.ops.aten.square.default(x)
|
| 442 |
+
|
| 443 |
+
@staticmethod
|
| 444 |
+
def trunc_to_int(x, dtype):
|
| 445 |
+
return _to_dtype(torch.ops.aten.trunc.default(x), dtype)
|
| 446 |
+
|
| 447 |
+
@staticmethod
|
| 448 |
+
def ceil_to_int(x, dtype):
|
| 449 |
+
return _to_dtype(torch.ops.aten.ceil.default(x), dtype)
|
| 450 |
+
|
| 451 |
+
@staticmethod
|
| 452 |
+
def floor_to_int(x, dtype):
|
| 453 |
+
return _to_dtype(torch.ops.aten.floor.default(x), dtype)
|
| 454 |
+
|
| 455 |
+
@staticmethod
|
| 456 |
+
def floor(x):
|
| 457 |
+
return torch.ops.aten.floor.default(x)
|
| 458 |
+
|
| 459 |
+
@staticmethod
|
| 460 |
+
def ceil(x):
|
| 461 |
+
return torch.ops.aten.ceil.default(x)
|
| 462 |
+
|
| 463 |
+
@staticmethod
|
| 464 |
+
def to_dtype(x, dtype):
|
| 465 |
+
return _to_dtype(x, dtype)
|
| 466 |
+
|
| 467 |
+
@staticmethod
|
| 468 |
+
def mod(x, y) -> NoReturn:
|
| 469 |
+
# TODO: https://github.com/pytorch/pytorch/pull/133654
|
| 470 |
+
raise NotImplementedError(
|
| 471 |
+
"no C-style modulus operation available from frontend atm"
|
| 472 |
+
)
|
| 473 |
+
|
| 474 |
+
@staticmethod
|
| 475 |
+
def abs(x):
|
| 476 |
+
return torch.ops.aten.abs.default(x)
|
| 477 |
+
|
| 478 |
+
@staticmethod
|
| 479 |
+
def neg(x):
|
| 480 |
+
return torch.ops.aten.neg.default(x)
|
| 481 |
+
|
| 482 |
+
@staticmethod
|
| 483 |
+
def truediv(a, b):
|
| 484 |
+
return torch.ops.aten.true_divide.Tensor(a, b)
|
| 485 |
+
|
| 486 |
+
@staticmethod
|
| 487 |
+
def int_truediv(a, b):
|
| 488 |
+
raise NotImplementedError(
|
| 489 |
+
"Python int truediv difficult to implement in PyTorch atm"
|
| 490 |
+
)
|
| 491 |
+
|
| 492 |
+
# TODO: This is wrong, CPython has a custom implementation of true
|
| 493 |
+
# division that results in higher precision when the floats are
|
| 494 |
+
# sufficiently large. Short term fix: add a guard here
|
| 495 |
+
return torch.ops.aten.true_divide.default(
|
| 496 |
+
_to_dtype(a, torch.float64), _to_dtype(b, torch.float64)
|
| 497 |
+
)
|
| 498 |
+
|
| 499 |
+
@staticmethod
|
| 500 |
+
def floordiv(a, b):
|
| 501 |
+
return torch.ops.aten.div.Tensor_mode(a, b, rounding_mode="floor")
|
| 502 |
+
|
| 503 |
+
@staticmethod
|
| 504 |
+
def truncdiv(a, b) -> NoReturn:
|
| 505 |
+
raise NotImplementedError(
|
| 506 |
+
"no C-style truncdiv operation available from frontend atm"
|
| 507 |
+
)
|
| 508 |
+
|
| 509 |
+
@staticmethod
|
| 510 |
+
def add(a, b):
|
| 511 |
+
return torch.ops.aten.add.Tensor(a, b)
|
| 512 |
+
|
| 513 |
+
@staticmethod
|
| 514 |
+
def mul(a, b):
|
| 515 |
+
return torch.ops.aten.mul.Tensor(a, b)
|
| 516 |
+
|
| 517 |
+
@staticmethod
|
| 518 |
+
def sub(a, b):
|
| 519 |
+
return torch.ops.aten.sub.Tensor(a, b)
|
| 520 |
+
|
| 521 |
+
@staticmethod
|
| 522 |
+
def exp(x):
|
| 523 |
+
return torch.ops.aten.exp.default(x)
|
| 524 |
+
|
| 525 |
+
@staticmethod
|
| 526 |
+
def log(x):
|
| 527 |
+
return torch.ops.aten.log.default(x)
|
| 528 |
+
|
| 529 |
+
@staticmethod
|
| 530 |
+
def log2(x):
|
| 531 |
+
return torch.ops.aten.log2.default(x)
|
| 532 |
+
|
| 533 |
+
@staticmethod
|
| 534 |
+
def sqrt(x):
|
| 535 |
+
return torch.ops.aten.sqrt.default(x)
|
| 536 |
+
|
| 537 |
+
@staticmethod
|
| 538 |
+
def sin(x):
|
| 539 |
+
return torch.ops.aten.sin.default(x)
|
| 540 |
+
|
| 541 |
+
@staticmethod
|
| 542 |
+
def cos(x):
|
| 543 |
+
return torch.ops.aten.cos.default(x)
|
| 544 |
+
|
| 545 |
+
@staticmethod
|
| 546 |
+
def tanh(x):
|
| 547 |
+
return torch.ops.aten.tanh.default(x)
|
| 548 |
+
|
| 549 |
+
@staticmethod
|
| 550 |
+
def sinh(x):
|
| 551 |
+
return torch.ops.aten.sinh.default(x)
|
| 552 |
+
|
| 553 |
+
@staticmethod
|
| 554 |
+
def cosh(x):
|
| 555 |
+
return torch.ops.aten.cosh.default(x)
|
| 556 |
+
|
| 557 |
+
@staticmethod
|
| 558 |
+
def tan(x):
|
| 559 |
+
return torch.ops.aten.tan.default(x)
|
| 560 |
+
|
| 561 |
+
@staticmethod
|
| 562 |
+
def acos(x):
|
| 563 |
+
return torch.ops.aten.acos.default(x)
|
| 564 |
+
|
| 565 |
+
@staticmethod
|
| 566 |
+
def atan(x):
|
| 567 |
+
return torch.ops.aten.atan.default(x)
|
| 568 |
+
|
| 569 |
+
@staticmethod
|
| 570 |
+
def asin(x):
|
| 571 |
+
return torch.ops.aten.asin.default(x)
|
| 572 |
+
|
| 573 |
+
@staticmethod
|
| 574 |
+
def pow(a, b):
|
| 575 |
+
return torch.ops.aten.pow.Tensor_Tensor(a, b)
|
| 576 |
+
|
| 577 |
+
@staticmethod
|
| 578 |
+
def pow_by_natural(a, b):
|
| 579 |
+
# NB: pow handles int x int fine
|
| 580 |
+
return torch.ops.aten.pow.Tensor_Tensor(a, b)
|
| 581 |
+
|
| 582 |
+
@staticmethod
|
| 583 |
+
def minimum(a, b):
|
| 584 |
+
return torch.ops.aten.minimum.default(a, b)
|
| 585 |
+
|
| 586 |
+
@staticmethod
|
| 587 |
+
def maximum(a, b):
|
| 588 |
+
return torch.ops.aten.maximum.default(a, b)
|
| 589 |
+
|
| 590 |
+
@staticmethod
|
| 591 |
+
def round_to_int(a, dtype):
|
| 592 |
+
return torch.ops.aten.round.default(a)
|
| 593 |
+
|
| 594 |
+
@staticmethod
|
| 595 |
+
def round_decimal(a, b) -> NoReturn:
|
| 596 |
+
raise NotImplementedError(
|
| 597 |
+
"round decimal doesn't support Tensor second argument atm"
|
| 598 |
+
)
|
| 599 |
+
|
| 600 |
+
# return torch.ops.aten.round.decimals(a, b)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/_sympy/singleton_int.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import sympy
|
| 3 |
+
from sympy.multipledispatch import dispatch
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
__all__ = ["SingletonInt"]
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class SingletonInt(sympy.AtomicExpr):
|
| 10 |
+
# This is probably not super important unless we are in multiple dispatch
|
| 11 |
+
# situations with other more exotic Expr types.
|
| 12 |
+
_op_priority = 99999
|
| 13 |
+
|
| 14 |
+
def __new__(cls, *args, coeff=None, **kwargs):
|
| 15 |
+
instance = super().__new__(cls, *args, **kwargs)
|
| 16 |
+
return instance
|
| 17 |
+
|
| 18 |
+
# The semantics of this class should match that of NestedIntSymNodeImpl in
|
| 19 |
+
# c10/core/NestedIntSymNodeImpl.h
|
| 20 |
+
def __init__(self, val, *, coeff=1) -> None:
|
| 21 |
+
self._val = val
|
| 22 |
+
self._coeff = coeff
|
| 23 |
+
super().__init__()
|
| 24 |
+
|
| 25 |
+
# See NOTE [ Inequalities with nested int ]
|
| 26 |
+
def _eval_Eq(self, other):
|
| 27 |
+
if (
|
| 28 |
+
isinstance(other, SingletonInt)
|
| 29 |
+
and other._val == self._val
|
| 30 |
+
and self._coeff == other._coeff
|
| 31 |
+
):
|
| 32 |
+
return sympy.true
|
| 33 |
+
else:
|
| 34 |
+
return sympy.false
|
| 35 |
+
|
| 36 |
+
# This is necessary so that calling expr.free_symbols on exprs that contain
|
| 37 |
+
# this Singleton does not error
|
| 38 |
+
@property
|
| 39 |
+
def free_symbols(self):
|
| 40 |
+
return set()
|
| 41 |
+
|
| 42 |
+
def __mul__(self, other):
|
| 43 |
+
if isinstance(other, SingletonInt):
|
| 44 |
+
raise ValueError(
|
| 45 |
+
"SingletonInt cannot be multiplied by another SingletonInt"
|
| 46 |
+
)
|
| 47 |
+
return SingletonInt(self._val, coeff=self._coeff * other)
|
| 48 |
+
|
| 49 |
+
def __rmul__(self, other):
|
| 50 |
+
if isinstance(other, SingletonInt):
|
| 51 |
+
raise ValueError(
|
| 52 |
+
"SingletonInt cannot be multiplied by another SingletonInt"
|
| 53 |
+
)
|
| 54 |
+
return SingletonInt(self._val, coeff=self._coeff * other)
|
| 55 |
+
|
| 56 |
+
# Make sure we promptly raise an error instead of falling back to building
|
| 57 |
+
# an expression tree. There are probably more ops, how can we be exhaustive?
|
| 58 |
+
def __add__(self, other):
|
| 59 |
+
raise NotImplementedError("NYI")
|
| 60 |
+
|
| 61 |
+
def __sub__(self, other):
|
| 62 |
+
raise NotImplementedError("NYI")
|
| 63 |
+
|
| 64 |
+
def __truediv__(self, other):
|
| 65 |
+
raise NotImplementedError("NYI")
|
| 66 |
+
|
| 67 |
+
def __floordiv__(self, other):
|
| 68 |
+
raise NotImplementedError("NYI")
|
| 69 |
+
|
| 70 |
+
def __mod__(self, other):
|
| 71 |
+
raise NotImplementedError("NYI")
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
# See NOTE [ Inequalities with nested int ]
|
| 75 |
+
@dispatch(sympy.Integer, SingletonInt)
|
| 76 |
+
def _eval_is_ge(a, b):
|
| 77 |
+
if a < 2:
|
| 78 |
+
return sympy.false
|
| 79 |
+
raise ValueError("Symbolic SingletonInt: Relation is indeterminate")
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
@dispatch(SingletonInt, sympy.Integer) # type: ignore[no-redef]
|
| 83 |
+
def _eval_is_ge(a, b): # noqa: F811
|
| 84 |
+
if b <= 2:
|
| 85 |
+
return sympy.true
|
| 86 |
+
raise ValueError("Symbolic SingletonInt: Relation is indeterminate")
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
@dispatch(SingletonInt, SingletonInt) # type: ignore[no-redef]
|
| 90 |
+
def _eval_is_ge(a, b): # noqa: F811
|
| 91 |
+
if a._val == b._val:
|
| 92 |
+
if a._coeff >= b._coeff:
|
| 93 |
+
return sympy.true
|
| 94 |
+
else:
|
| 95 |
+
return sympy.false
|
| 96 |
+
raise ValueError("Symbolic SingletonInt: Relation is indeterminate")
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/_sympy/solve.py
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
|
| 3 |
+
import sympy
|
| 4 |
+
|
| 5 |
+
from torch.utils._sympy.functions import FloorDiv
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
log = logging.getLogger(__name__)
|
| 9 |
+
|
| 10 |
+
_MIRROR_REL_OP: dict[type[sympy.Basic], type[sympy.Rel]] = {
|
| 11 |
+
sympy.Eq: sympy.Eq,
|
| 12 |
+
sympy.Ne: sympy.Ne,
|
| 13 |
+
sympy.Ge: sympy.Le,
|
| 14 |
+
sympy.Gt: sympy.Lt,
|
| 15 |
+
sympy.Le: sympy.Ge,
|
| 16 |
+
sympy.Lt: sympy.Gt,
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
INEQUALITY_TYPES = (sympy.Gt, sympy.Ge, sympy.Lt, sympy.Le)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def mirror_rel_op(type: type) -> type[sympy.Rel] | None:
|
| 23 |
+
return _MIRROR_REL_OP.get(type)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
# Tries to simplify 'expr', so as to leave only 'thing' in the left-hand side.
|
| 27 |
+
#
|
| 28 |
+
# Returns a tuple of:
|
| 29 |
+
# 1. The simplified expression
|
| 30 |
+
# 2. The expression on the right-hand side
|
| 31 |
+
#
|
| 32 |
+
# Returns 'None' if it can't reach a state where the only thing in the left
|
| 33 |
+
# hand side is 'thing'.
|
| 34 |
+
#
|
| 35 |
+
# 'trials': number of times 'try_solve' will try to isolate 'thing' to the
|
| 36 |
+
# left-hand side.
|
| 37 |
+
#
|
| 38 |
+
# 'floordiv_inequality': flag to enable conversion of 'FloorDiv' into
|
| 39 |
+
# inequalities.
|
| 40 |
+
def try_solve(
|
| 41 |
+
expr: sympy.Basic,
|
| 42 |
+
thing: sympy.Basic,
|
| 43 |
+
trials: int = 5,
|
| 44 |
+
floordiv_inequality: bool = True,
|
| 45 |
+
) -> tuple[sympy.Rel, sympy.Expr] | None:
|
| 46 |
+
mirror = mirror_rel_op(type(expr))
|
| 47 |
+
|
| 48 |
+
# Ignore unsupported expressions:
|
| 49 |
+
# - Those that are not relational operations
|
| 50 |
+
# - Those that don't have a mirror (just avoiding unexpected classes)
|
| 51 |
+
if not isinstance(expr, sympy.Rel) or mirror is None:
|
| 52 |
+
log.debug("expression with unsupported type: %s", type(expr))
|
| 53 |
+
return None
|
| 54 |
+
|
| 55 |
+
lhs_has_thing = expr.lhs.has(thing)
|
| 56 |
+
rhs_has_thing = expr.rhs.has(thing)
|
| 57 |
+
|
| 58 |
+
# Give up when 'thing' appears on both sides of the relational expression.
|
| 59 |
+
# That is because, as is, we assume the thing we are trying to isolate is
|
| 60 |
+
# only on the right-hand side.
|
| 61 |
+
if lhs_has_thing and rhs_has_thing:
|
| 62 |
+
log.debug("thing (%s) found in both sides of expression: %s", thing, expr)
|
| 63 |
+
return None
|
| 64 |
+
|
| 65 |
+
# Try considering both LHS and RHS by mirroring the original expression:
|
| 66 |
+
# a < b ==> b > a
|
| 67 |
+
expressions = []
|
| 68 |
+
|
| 69 |
+
# Add each version of 'expr' if 'thing' is in its left-hand side.
|
| 70 |
+
if lhs_has_thing:
|
| 71 |
+
expressions.append(expr)
|
| 72 |
+
if rhs_has_thing:
|
| 73 |
+
expressions.append(mirror(expr.rhs, expr.lhs))
|
| 74 |
+
|
| 75 |
+
for e in expressions:
|
| 76 |
+
if e is None:
|
| 77 |
+
continue
|
| 78 |
+
|
| 79 |
+
if not isinstance(e, sympy.Rel):
|
| 80 |
+
raise AssertionError("expected sympy.Rel")
|
| 81 |
+
|
| 82 |
+
for _ in range(trials):
|
| 83 |
+
trial = _try_isolate_lhs(e, thing, floordiv_inequality=floordiv_inequality)
|
| 84 |
+
# Stop if there was no change in this trial.
|
| 85 |
+
if trial == e:
|
| 86 |
+
break
|
| 87 |
+
e = trial # type: ignore[assignment]
|
| 88 |
+
|
| 89 |
+
# Return if we were able to isolate 'thing' on the left-hand side.
|
| 90 |
+
if isinstance(e, sympy.Rel) and e.lhs == thing:
|
| 91 |
+
log.debug("solved: %s ---> %s", expr, e)
|
| 92 |
+
return e, e.rhs
|
| 93 |
+
|
| 94 |
+
return None
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def _try_isolate_lhs(
|
| 98 |
+
e: sympy.Basic, thing: sympy.Basic, floordiv_inequality: bool
|
| 99 |
+
) -> sympy.Basic:
|
| 100 |
+
op = type(e)
|
| 101 |
+
|
| 102 |
+
if isinstance(e, sympy.Rel):
|
| 103 |
+
# Move any constants in the left-hand side to the right-hand side.
|
| 104 |
+
lhs_not_thing = (
|
| 105 |
+
sum(a for a in e.lhs.args if not a.has(thing))
|
| 106 |
+
if isinstance(e.lhs, sympy.Add)
|
| 107 |
+
else 0
|
| 108 |
+
)
|
| 109 |
+
e = op(e.lhs - lhs_not_thing, e.rhs - lhs_not_thing) # type: ignore[attr-defined]
|
| 110 |
+
|
| 111 |
+
# Divide both sides by the factors that don't contain thing.
|
| 112 |
+
if isinstance(e, sympy.Rel) and isinstance(e.lhs, sympy.Mul):
|
| 113 |
+
lhs, rhs = e.args
|
| 114 |
+
other = sympy.Mul(*[a for a in lhs.args if not a.has(thing)])
|
| 115 |
+
|
| 116 |
+
# If we can't tell whether 'other' is negative or positive, we do nothing.
|
| 117 |
+
# That is because we don't know whether we have mirror the operation or not.
|
| 118 |
+
# We also divide only when we know 'rhs' is not zero.
|
| 119 |
+
if not (isinstance(e, INEQUALITY_TYPES) and other.is_negative is None) and not (
|
| 120 |
+
not isinstance(e, INEQUALITY_TYPES) and rhs.is_zero
|
| 121 |
+
):
|
| 122 |
+
# Divide both sides by 'other'.
|
| 123 |
+
lhs = lhs / other
|
| 124 |
+
rhs = rhs / other
|
| 125 |
+
|
| 126 |
+
# If 'e' is an inequality and 'other' is negative, we have to
|
| 127 |
+
# mirror the expression.
|
| 128 |
+
if isinstance(e, INEQUALITY_TYPES) and other.is_negative:
|
| 129 |
+
op = mirror_rel_op(op) # type: ignore[assignment]
|
| 130 |
+
|
| 131 |
+
if op is None:
|
| 132 |
+
raise AssertionError("expected op to be not None")
|
| 133 |
+
e = op(lhs, rhs)
|
| 134 |
+
|
| 135 |
+
################################################################################
|
| 136 |
+
# left-hand side is FloorDiv
|
| 137 |
+
################################################################################
|
| 138 |
+
#
|
| 139 |
+
# Given the expression: a // b op c
|
| 140 |
+
# where 'op' is a relational operation, these rules only work if:
|
| 141 |
+
# - b > 0
|
| 142 |
+
# - c is an integer
|
| 143 |
+
if (
|
| 144 |
+
floordiv_inequality
|
| 145 |
+
and isinstance(e, sympy.Rel)
|
| 146 |
+
and isinstance(e.lhs, FloorDiv)
|
| 147 |
+
and e.lhs.divisor.is_positive
|
| 148 |
+
and e.rhs.is_integer
|
| 149 |
+
):
|
| 150 |
+
# a // b == expr
|
| 151 |
+
# => a >= (b * expr) and a < (b * (expr + 1))
|
| 152 |
+
if isinstance(e, sympy.Eq):
|
| 153 |
+
numerator, denominator = e.lhs.args
|
| 154 |
+
return sympy.And(
|
| 155 |
+
sympy.Ge(numerator, (e.rhs * denominator)),
|
| 156 |
+
sympy.Lt(numerator, ((e.rhs + 1) * denominator)),
|
| 157 |
+
)
|
| 158 |
+
# a // b != expr
|
| 159 |
+
# => a < (b * expr) or a >= (b * (expr + 1))
|
| 160 |
+
if isinstance(e, sympy.Ne):
|
| 161 |
+
numerator, denominator = e.lhs.args
|
| 162 |
+
return sympy.Or(
|
| 163 |
+
sympy.Lt(numerator, (e.rhs * denominator)),
|
| 164 |
+
sympy.Ge(numerator, ((e.rhs + 1) * denominator)),
|
| 165 |
+
)
|
| 166 |
+
# The transformations below only work if b is positive.
|
| 167 |
+
# Note: we only have this information for constants.
|
| 168 |
+
# a // b > expr => a >= b * (expr + 1)
|
| 169 |
+
# a // b >= expr => a >= b * expr
|
| 170 |
+
if isinstance(e, (sympy.Gt, sympy.Ge)):
|
| 171 |
+
quotient = e.rhs if isinstance(e, sympy.Ge) else (e.rhs + 1)
|
| 172 |
+
return sympy.Ge(e.lhs.args[0], (quotient * e.lhs.args[1]))
|
| 173 |
+
# a // b < expr => a < b * expr
|
| 174 |
+
# a // b <= expr => a < b * (expr + 1)
|
| 175 |
+
if isinstance(e, (sympy.Lt, sympy.Le)):
|
| 176 |
+
quotient = e.rhs if isinstance(e, sympy.Lt) else (e.rhs + 1)
|
| 177 |
+
return sympy.Lt(e.lhs.args[0], (quotient * e.lhs.args[1]))
|
| 178 |
+
|
| 179 |
+
return e
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/_sympy/symbol.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
"""
|
| 3 |
+
This file contains canonical definitions for our symbol naming conventions,
|
| 4 |
+
across torch.fx.experimental.symbolic_shapes and torch._inductor. The
|
| 5 |
+
intention is:
|
| 6 |
+
|
| 7 |
+
1. To make it easily greppable where all the sites we use a prefix are
|
| 8 |
+
2. Make it possible to easily tell if we can introduce a new prefix without
|
| 9 |
+
introducing a conflict
|
| 10 |
+
|
| 11 |
+
You can occasionally test if prefixes have been hardcoded by renaming prefixes
|
| 12 |
+
in this file and seeing what breaks.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
from collections.abc import Iterable
|
| 16 |
+
from enum import auto, Enum
|
| 17 |
+
|
| 18 |
+
import sympy
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class SymT(Enum):
|
| 22 |
+
SIZE = auto()
|
| 23 |
+
FLOAT = auto()
|
| 24 |
+
UNBACKED_INT = auto()
|
| 25 |
+
UNBACKED_FLOAT = auto()
|
| 26 |
+
# Inductor: The intermediates in inner_fn tmp0, one generated per ops call.
|
| 27 |
+
# If one of these shows up in an indexing expression, that means an
|
| 28 |
+
# indirect load is happening.
|
| 29 |
+
TMP = auto()
|
| 30 |
+
# Inductor: Placeholder variable that is later replaced with TMP
|
| 31 |
+
INDIRECT = auto()
|
| 32 |
+
# Inductor: Some size expressions are replaced with a precomputed size ps0
|
| 33 |
+
# which is computed host side, and then directly reused in the kernel, so
|
| 34 |
+
# we don't repeatedly recompute it on device.
|
| 35 |
+
PRECOMPUTED_SIZE = auto()
|
| 36 |
+
# Inductor: An indexing variable i0 in loops IR which ranges over non-reduced
|
| 37 |
+
# dim in the loop
|
| 38 |
+
INDEX = auto()
|
| 39 |
+
# Inductor: A reduction indexing (r0, r1) variables in loops IR which ranges over
|
| 40 |
+
# reduced dim(s) in the loop
|
| 41 |
+
R0_INDEX = auto()
|
| 42 |
+
R1_INDEX = auto()
|
| 43 |
+
# Inductor: In templated kernels torch._inductor.kernel, we have a hook to
|
| 44 |
+
# store the final output and append epilogue fusions. To do this, we must
|
| 45 |
+
# know what the indexes the outputs range over. NB: These will also
|
| 46 |
+
# advertise as INDEX, this is... probably OK?
|
| 47 |
+
TEMPLATE_INDEX = auto()
|
| 48 |
+
# Inductor: iteration domain for blockIdx.x/blockIdx.y
|
| 49 |
+
XBLOCK = auto()
|
| 50 |
+
YBLOCK = auto()
|
| 51 |
+
ZBLOCK = auto()
|
| 52 |
+
# Inductor: this is used solely for dynamic_reshape_indexer
|
| 53 |
+
VIEW = auto()
|
| 54 |
+
# Alternate (non-modular) indexing used in halide kernels
|
| 55 |
+
HALIDE = auto()
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
# Invariant: there must not be a prefix which is a prefix of another string,
|
| 59 |
+
# as this introduces ambiguity
|
| 60 |
+
prefix_str = {
|
| 61 |
+
SymT.SIZE: "s", # integer
|
| 62 |
+
SymT.UNBACKED_INT: "u", # integer
|
| 63 |
+
# Prefix z here is chosen to avoid false aliasing in symbol_is_type test
|
| 64 |
+
# DO NOT add a "z" type. You also need to avoid conflicts on these
|
| 65 |
+
# prefixes but this is somewhat easier to manage
|
| 66 |
+
SymT.FLOAT: "zf",
|
| 67 |
+
SymT.UNBACKED_FLOAT: "zuf",
|
| 68 |
+
SymT.TMP: "tmp",
|
| 69 |
+
SymT.PRECOMPUTED_SIZE: "ps",
|
| 70 |
+
SymT.INDEX: "i",
|
| 71 |
+
SymT.R0_INDEX: "r0_",
|
| 72 |
+
SymT.R1_INDEX: "r1_",
|
| 73 |
+
SymT.TEMPLATE_INDEX: "idx",
|
| 74 |
+
SymT.XBLOCK: "x",
|
| 75 |
+
SymT.YBLOCK: "y",
|
| 76 |
+
SymT.ZBLOCK: "z",
|
| 77 |
+
SymT.INDIRECT: "indirect", # false aliasing?
|
| 78 |
+
SymT.VIEW: "view",
|
| 79 |
+
SymT.HALIDE: "h",
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def make_symbol(prefix: SymT, idx: int, **kwargs) -> sympy.Symbol:
|
| 84 |
+
# TODO: maybe put the assumptions here directly
|
| 85 |
+
return sympy.Symbol(f"{prefix_str[prefix]}{idx}", **kwargs)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
# This type is a little wider than it should be, because free_symbols says
|
| 89 |
+
# that it contains Basic, rather than Symbol
|
| 90 |
+
def symbol_is_type(sym: sympy.Basic, prefix: SymT | Iterable[SymT]) -> bool:
|
| 91 |
+
if not isinstance(sym, sympy.Symbol):
|
| 92 |
+
raise AssertionError("expected sympy.Symbol")
|
| 93 |
+
name_str = sym.name.lower() # Match capitalized names like XBLOCK, RBLOCK
|
| 94 |
+
if isinstance(prefix, SymT):
|
| 95 |
+
return name_str.startswith(prefix_str[prefix])
|
| 96 |
+
else:
|
| 97 |
+
return name_str.startswith(tuple(prefix_str[p] for p in prefix))
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def free_symbol_is_type(e: sympy.Expr, prefix: SymT | Iterable[SymT]) -> bool:
|
| 101 |
+
return any(symbol_is_type(v, prefix) for v in e.free_symbols)
|
miniconda3/envs/ladir/l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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import dataclasses
|
| 5 |
+
import functools
|
| 6 |
+
import itertools
|
| 7 |
+
import logging
|
| 8 |
+
import math
|
| 9 |
+
import operator
|
| 10 |
+
from collections.abc import Callable
|
| 11 |
+
from typing import Generic, overload, SupportsFloat, TYPE_CHECKING, TypeGuard, TypeVar
|
| 12 |
+
from typing_extensions import TypeIs
|
| 13 |
+
|
| 14 |
+
import sympy
|
| 15 |
+
from sympy.logic.boolalg import Boolean as SympyBoolean, BooleanAtom
|
| 16 |
+
|
| 17 |
+
import torch
|
| 18 |
+
from torch._logging import LazyString
|
| 19 |
+
from torch._prims_common import dtype_to_type
|
| 20 |
+
|
| 21 |
+
from .functions import (
|
| 22 |
+
_keep_float,
|
| 23 |
+
FloatTrueDiv,
|
| 24 |
+
FloorDiv,
|
| 25 |
+
IntTrueDiv,
|
| 26 |
+
OpaqueUnaryFn_exp,
|
| 27 |
+
OpaqueUnaryFn_log,
|
| 28 |
+
OpaqueUnaryFn_log2,
|
| 29 |
+
OpaqueUnaryFn_sqrt,
|
| 30 |
+
PowByNatural,
|
| 31 |
+
RoundDecimal,
|
| 32 |
+
RoundToInt,
|
| 33 |
+
safe_pow,
|
| 34 |
+
ToFloat,
|
| 35 |
+
TruncToFloat,
|
| 36 |
+
TruncToInt,
|
| 37 |
+
)
|
| 38 |
+
from .interp import sympy_interp
|
| 39 |
+
from .numbers import int_oo, IntInfinity, NegativeIntInfinity
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
log = logging.getLogger(__name__)
|
| 43 |
+
|
| 44 |
+
__all__ = ["ValueRanges", "bound_sympy"]
|
| 45 |
+
|
| 46 |
+
_T = TypeVar("_T", sympy.Expr, SympyBoolean)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class ValueRangeError(RuntimeError):
|
| 50 |
+
pass
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
# Like sympify, but supports less stuff, and also ensures that direct
|
| 54 |
+
# sympy expressions don't have free variables
|
| 55 |
+
def simple_sympify(e):
|
| 56 |
+
if isinstance(e, bool):
|
| 57 |
+
return sympy.true if e else sympy.false
|
| 58 |
+
elif isinstance(e, int):
|
| 59 |
+
return sympy.Integer(e)
|
| 60 |
+
elif isinstance(e, float):
|
| 61 |
+
# infinity is special; we use it to bracket integers as well
|
| 62 |
+
if math.isinf(e):
|
| 63 |
+
return sympy.oo if e > 0 else -sympy.oo
|
| 64 |
+
return sympy.Float(e)
|
| 65 |
+
elif isinstance(e, sympy.Expr):
|
| 66 |
+
if not getattr(e, "is_number", False):
|
| 67 |
+
raise AssertionError(e)
|
| 68 |
+
# NaNs can occur when doing things like 0 * sympy.oo, but it is better
|
| 69 |
+
# if the operator notices this and takes care of it, because sometimes
|
| 70 |
+
# the NaN is inappropriate (for example, for ints, the [-oo, oo] range
|
| 71 |
+
# should go to zero when multiplied with [0, 0])
|
| 72 |
+
if e == sympy.nan:
|
| 73 |
+
raise AssertionError("sympy expression is NaN")
|
| 74 |
+
return e
|
| 75 |
+
elif isinstance(e, BooleanAtom):
|
| 76 |
+
return e
|
| 77 |
+
else:
|
| 78 |
+
raise AssertionError(f"not simple sympy type {type(e)}: {e}")
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
# Sympy atomics only. Unlike <=, it also works on Sympy bools.
|
| 82 |
+
def sympy_generic_le(lower, upper):
|
| 83 |
+
if isinstance(lower, sympy.Expr):
|
| 84 |
+
if not isinstance(upper, sympy.Expr):
|
| 85 |
+
raise AssertionError(
|
| 86 |
+
"upper must be a sympy.Expr when lower is a sympy.Expr"
|
| 87 |
+
)
|
| 88 |
+
# instead of lower <= upper, we do upper >= lower since upper is mostly int_oo
|
| 89 |
+
# and we have better code paths there.
|
| 90 |
+
return upper >= lower
|
| 91 |
+
else:
|
| 92 |
+
# only negative condition is True > False
|
| 93 |
+
if not isinstance(lower, SympyBoolean) or not isinstance(upper, SympyBoolean):
|
| 94 |
+
raise AssertionError((lower, upper))
|
| 95 |
+
return not (lower and not upper)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def vr_is_bool(vr: ValueRanges[_T]) -> TypeGuard[ValueRanges[SympyBoolean]]:
|
| 99 |
+
return vr.is_bool
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def vr_is_expr(vr: ValueRanges[_T]) -> TypeGuard[ValueRanges[sympy.Expr]]:
|
| 103 |
+
return not vr.is_bool
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def is_sympy_integer(value) -> TypeIs[sympy.Integer]:
|
| 107 |
+
return isinstance(value, sympy.Integer)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
ExprIn = int | float | sympy.Expr
|
| 111 |
+
BoolIn = bool | SympyBoolean
|
| 112 |
+
AllIn = ExprIn | BoolIn
|
| 113 |
+
ExprFn = Callable[[sympy.Expr], sympy.Expr]
|
| 114 |
+
ExprFn2 = Callable[[sympy.Expr, sympy.Expr], sympy.Expr]
|
| 115 |
+
BoolFn = Callable[[SympyBoolean], SympyBoolean]
|
| 116 |
+
BoolFn2 = Callable[[SympyBoolean, SympyBoolean], SympyBoolean]
|
| 117 |
+
AllFn = ExprFn | BoolFn
|
| 118 |
+
AllFn2 = ExprFn2 | BoolFn2
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
@dataclasses.dataclass(frozen=True)
|
| 122 |
+
class ValueRanges(Generic[_T]):
|
| 123 |
+
if TYPE_CHECKING:
|
| 124 |
+
# ruff doesn't understand circular references but mypy does
|
| 125 |
+
# pyrefly: ignore [unbound-name]
|
| 126 |
+
ExprVR = ValueRanges[sympy.Expr] # noqa: F821
|
| 127 |
+
# pyrefly: ignore [unbound-name]
|
| 128 |
+
BoolVR = ValueRanges[SympyBoolean] # noqa: F821
|
| 129 |
+
AllVR = ExprVR | BoolVR
|
| 130 |
+
|
| 131 |
+
# Although the type signature here suggests you can pass any
|
| 132 |
+
# sympy expression, in practice the analysis here only works
|
| 133 |
+
# with constant sympy expressions
|
| 134 |
+
lower: _T
|
| 135 |
+
upper: _T
|
| 136 |
+
is_bool: bool
|
| 137 |
+
is_int: bool
|
| 138 |
+
is_float: bool
|
| 139 |
+
|
| 140 |
+
def __repr__(self) -> str:
|
| 141 |
+
return f"VR[{self.lower}, {self.upper}]"
|
| 142 |
+
|
| 143 |
+
@overload
|
| 144 |
+
def __init__(
|
| 145 |
+
self: ValueRanges[sympy.Expr],
|
| 146 |
+
lower: ExprIn,
|
| 147 |
+
upper: ExprIn,
|
| 148 |
+
) -> None: ...
|
| 149 |
+
|
| 150 |
+
@overload
|
| 151 |
+
def __init__( # type: ignore[misc]
|
| 152 |
+
self: ValueRanges[SympyBoolean],
|
| 153 |
+
lower: BoolIn,
|
| 154 |
+
upper: BoolIn,
|
| 155 |
+
) -> None: ...
|
| 156 |
+
|
| 157 |
+
def __init__(self, lower: AllIn, upper: AllIn) -> None:
|
| 158 |
+
lower = simple_sympify(lower)
|
| 159 |
+
upper = simple_sympify(upper)
|
| 160 |
+
# TODO: when the bounds have free variables, this may be
|
| 161 |
+
# nontrivial to actually verify
|
| 162 |
+
try:
|
| 163 |
+
if not sympy_generic_le(lower, upper):
|
| 164 |
+
raise ValueRangeError(f"Invalid ranges [{lower}:{upper}]")
|
| 165 |
+
except TypeError as e:
|
| 166 |
+
raise TypeError(f"Could not compare {lower} <= {upper}") from e
|
| 167 |
+
|
| 168 |
+
is_bool_lower = isinstance(lower, SympyBoolean)
|
| 169 |
+
is_bool_upper = isinstance(upper, SympyBoolean)
|
| 170 |
+
if is_bool_lower != is_bool_upper:
|
| 171 |
+
raise AssertionError((lower, upper))
|
| 172 |
+
|
| 173 |
+
# Warning: is_int/is_float is best effort. We do pretty well in
|
| 174 |
+
# Dynamo, but in Inductor these attributes are often wrong because we
|
| 175 |
+
# are not very rigorous in dtype analysis. This is also why we need
|
| 176 |
+
# the flexible analysis for is_int: sometimes a sympy.oo pops in for
|
| 177 |
+
# an integer bound. I would /like/ for us not to do this, but it's
|
| 178 |
+
# too hard to push the invariant through right now.
|
| 179 |
+
if isinstance(lower, sympy.Integer) and upper == sympy.oo:
|
| 180 |
+
upper = int_oo
|
| 181 |
+
if isinstance(upper, sympy.Integer) and lower == -sympy.oo:
|
| 182 |
+
lower = -int_oo
|
| 183 |
+
# NB: [-int_oo, -int_oo] and [int_oo, int_oo] are allowed
|
| 184 |
+
integer_types = (sympy.Integer, NegativeIntInfinity, IntInfinity)
|
| 185 |
+
is_int_lower = isinstance(lower, integer_types)
|
| 186 |
+
is_int_upper = isinstance(upper, integer_types)
|
| 187 |
+
|
| 188 |
+
# Because this is a frozen class
|
| 189 |
+
object.__setattr__(self, "lower", lower)
|
| 190 |
+
object.__setattr__(self, "upper", upper)
|
| 191 |
+
# Unlike bool/int in Python, we don't report bools are ints
|
| 192 |
+
#
|
| 193 |
+
# NB: is_bool_lower == is_bool_upper, so we only need to check one
|
| 194 |
+
object.__setattr__(self, "is_bool", is_bool_lower)
|
| 195 |
+
object.__setattr__(
|
| 196 |
+
self,
|
| 197 |
+
"is_int",
|
| 198 |
+
not self.is_bool and is_int_lower and is_int_upper,
|
| 199 |
+
)
|
| 200 |
+
"""
|
| 201 |
+
# This assert is just impossible right now, too many sympy bugs
|
| 202 |
+
if self.is_int:
|
| 203 |
+
# NB: sympy will sometimes randomly lose the float-ness of zero,
|
| 204 |
+
# so we also need to account for that in the assertion here.
|
| 205 |
+
# See also https://github.com/sympy/sympy/issues/26620
|
| 206 |
+
assert isinstance(lower, sympy.Integer) or lower in [-sympy.oo, 0], (
|
| 207 |
+
lower,
|
| 208 |
+
upper,
|
| 209 |
+
)
|
| 210 |
+
assert isinstance(upper, sympy.Integer) or upper in [sympy.oo, 0], (lower, upper)
|
| 211 |
+
"""
|
| 212 |
+
# NB: [-oo, oo] always advertises as float!
|
| 213 |
+
object.__setattr__(self, "is_float", not self.is_bool and not self.is_int)
|
| 214 |
+
if not self.is_bool and not self.is_int and not self.is_float:
|
| 215 |
+
raise AssertionError((lower, upper))
|
| 216 |
+
|
| 217 |
+
def boolify(self) -> ValueRanges[SympyBoolean]:
|
| 218 |
+
if vr_is_bool(self):
|
| 219 |
+
return self
|
| 220 |
+
elif self == ValueRanges.unknown():
|
| 221 |
+
return ValueRanges.unknown_bool()
|
| 222 |
+
else:
|
| 223 |
+
raise AssertionError(f"not bool like {self}")
|
| 224 |
+
|
| 225 |
+
def __contains__(self, x: AllIn) -> bool:
|
| 226 |
+
return ValueRanges.wrap(x).issubset(self)
|
| 227 |
+
|
| 228 |
+
def issubset(self, other):
|
| 229 |
+
if other is self.unknown_int():
|
| 230 |
+
return True
|
| 231 |
+
return sympy_generic_le(other.lower, self.lower) and sympy_generic_le(
|
| 232 |
+
self.upper, other.upper
|
| 233 |
+
)
|
| 234 |
+
|
| 235 |
+
def tighten(self, other) -> ValueRanges:
|
| 236 |
+
"""Given two ValueRanges, returns their intersection"""
|
| 237 |
+
return self & other
|
| 238 |
+
|
| 239 |
+
# Intersection
|
| 240 |
+
@overload
|
| 241 |
+
def __and__(
|
| 242 |
+
self: ValueRanges[sympy.Expr],
|
| 243 |
+
other: ValueRanges[sympy.Expr],
|
| 244 |
+
) -> ValueRanges[sympy.Expr]: ...
|
| 245 |
+
|
| 246 |
+
@overload
|
| 247 |
+
def __and__( # type: ignore[misc]
|
| 248 |
+
self: ValueRanges[SympyBoolean],
|
| 249 |
+
other: ValueRanges[SympyBoolean],
|
| 250 |
+
) -> ValueRanges[SympyBoolean]: ...
|
| 251 |
+
|
| 252 |
+
def __and__(self: AllVR, other: AllVR) -> AllVR:
|
| 253 |
+
if other in (ValueRanges.unknown(), ValueRanges.unknown_int()):
|
| 254 |
+
return self
|
| 255 |
+
if self in (ValueRanges.unknown(), ValueRanges.unknown_int()):
|
| 256 |
+
return other
|
| 257 |
+
if self.is_bool != other.is_bool:
|
| 258 |
+
raise AssertionError((self, other))
|
| 259 |
+
if self.is_int != other.is_int:
|
| 260 |
+
raise AssertionError((self, other))
|
| 261 |
+
if self.is_float != other.is_float:
|
| 262 |
+
raise AssertionError((self, other))
|
| 263 |
+
if self.is_bool:
|
| 264 |
+
return ValueRanges(
|
| 265 |
+
sympy.Or(self.lower, other.lower), sympy.And(self.upper, other.upper)
|
| 266 |
+
)
|
| 267 |
+
else:
|
| 268 |
+
return ValueRanges(
|
| 269 |
+
sympy.Max(self.lower, other.lower), sympy.Min(self.upper, other.upper)
|
| 270 |
+
)
|
| 271 |
+
|
| 272 |
+
# Union
|
| 273 |
+
@overload
|
| 274 |
+
def __or__(
|
| 275 |
+
self: ValueRanges[sympy.Expr],
|
| 276 |
+
other: ValueRanges[sympy.Expr],
|
| 277 |
+
) -> ValueRanges[sympy.Expr]: ...
|
| 278 |
+
|
| 279 |
+
@overload
|
| 280 |
+
def __or__( # type: ignore[misc]
|
| 281 |
+
self: ValueRanges[SympyBoolean],
|
| 282 |
+
other: ValueRanges[SympyBoolean],
|
| 283 |
+
) -> ValueRanges[SympyBoolean]: ...
|
| 284 |
+
|
| 285 |
+
def __or__(self: AllVR, other: AllVR) -> AllVR:
|
| 286 |
+
if ValueRanges.unknown() in (self, other):
|
| 287 |
+
return ValueRanges.unknown()
|
| 288 |
+
if self.is_bool != other.is_bool:
|
| 289 |
+
raise AssertionError((self, other))
|
| 290 |
+
if self.is_int != other.is_int:
|
| 291 |
+
raise AssertionError((self, other))
|
| 292 |
+
if self.is_float != other.is_float:
|
| 293 |
+
raise AssertionError((self, other))
|
| 294 |
+
if self.is_bool:
|
| 295 |
+
return ValueRanges(
|
| 296 |
+
sympy.And(self.lower, other.lower), sympy.Or(self.upper, other.upper)
|
| 297 |
+
)
|
| 298 |
+
else:
|
| 299 |
+
return ValueRanges(
|
| 300 |
+
sympy.Min(self.lower, other.lower), sympy.Max(self.upper, other.upper)
|
| 301 |
+
)
|
| 302 |
+
|
| 303 |
+
def is_singleton(self) -> bool:
|
| 304 |
+
return self.lower == self.upper
|
| 305 |
+
|
| 306 |
+
@staticmethod
|
| 307 |
+
@functools.cache
|
| 308 |
+
def unknown() -> ValueRanges[sympy.Expr]:
|
| 309 |
+
return ValueRanges(-sympy.oo, sympy.oo)
|
| 310 |
+
|
| 311 |
+
@staticmethod
|
| 312 |
+
@functools.cache
|
| 313 |
+
def unknown_int() -> ValueRanges[sympy.Expr]:
|
| 314 |
+
return ValueRanges(-int_oo, int_oo)
|
| 315 |
+
|
| 316 |
+
@staticmethod
|
| 317 |
+
@functools.cache
|
| 318 |
+
def unknown_bool() -> ValueRanges[SympyBoolean]:
|
| 319 |
+
return ValueRanges(sympy.false, sympy.true)
|
| 320 |
+
|
| 321 |
+
@overload
|
| 322 |
+
@staticmethod
|
| 323 |
+
# work around the fact that bool and int overlap
|
| 324 |
+
def wrap(arg: ExprIn | ExprVR) -> ExprVR: # type: ignore[overload-overlap]
|
| 325 |
+
...
|
| 326 |
+
|
| 327 |
+
@overload
|
| 328 |
+
@staticmethod
|
| 329 |
+
def wrap(arg: BoolIn | BoolVR) -> BoolVR: # type: ignore[misc]
|
| 330 |
+
...
|
| 331 |
+
|
| 332 |
+
@staticmethod
|
| 333 |
+
def wrap(arg: AllIn | AllVR) -> AllVR:
|
| 334 |
+
if isinstance(arg, ValueRanges):
|
| 335 |
+
return arg
|
| 336 |
+
if isinstance(arg, float) and math.isnan(arg):
|
| 337 |
+
return ValueRanges.unknown()
|
| 338 |
+
# arg is either ExprIn or BoolIn, but we don't know it here
|
| 339 |
+
return ValueRanges(arg, arg) # type: ignore[arg-type]
|
| 340 |
+
|
| 341 |
+
@staticmethod
|
| 342 |
+
def increasing_map(x: ExprIn | ExprVR, fn: ExprFn) -> ExprVR:
|
| 343 |
+
"""Increasing: x <= y => f(x) <= f(y)."""
|
| 344 |
+
x = ValueRanges.wrap(x)
|
| 345 |
+
return ValueRanges(fn(x.lower), fn(x.upper))
|
| 346 |
+
|
| 347 |
+
@overload
|
| 348 |
+
@staticmethod
|
| 349 |
+
def decreasing_map(x: ExprIn | ExprVR, fn: ExprFn) -> ExprVR: ...
|
| 350 |
+
|
| 351 |
+
@overload
|
| 352 |
+
@staticmethod
|
| 353 |
+
def decreasing_map(x: BoolIn | BoolVR, fn: BoolFn) -> BoolVR: # type: ignore[misc]
|
| 354 |
+
...
|
| 355 |
+
|
| 356 |
+
@staticmethod
|
| 357 |
+
def decreasing_map(x: AllIn | AllVR, fn: AllFn) -> AllVR:
|
| 358 |
+
"""Decreasing: x <= y => f(x) >= f(y)."""
|
| 359 |
+
x = ValueRanges.wrap(x)
|
| 360 |
+
# consistently either Expr or Bool, but we don't know it here
|
| 361 |
+
return ValueRanges(fn(x.upper), fn(x.lower)) # type: ignore[arg-type]
|
| 362 |
+
|
| 363 |
+
@staticmethod
|
| 364 |
+
def monotone_map(x: ExprIn | ExprVR, fn: ExprFn) -> ExprVR:
|
| 365 |
+
"""It's increasing or decreasing."""
|
| 366 |
+
x = ValueRanges.wrap(x)
|
| 367 |
+
l = fn(x.lower)
|
| 368 |
+
u = fn(x.upper)
|
| 369 |
+
return ValueRanges(min(l, u), max(l, u))
|
| 370 |
+
|
| 371 |
+
@staticmethod
|
| 372 |
+
def convex_min_zero_map(x: ExprIn | ExprVR, fn: ExprFn) -> ExprVR:
|
| 373 |
+
"""Fn is convex and has a minimum at 0."""
|
| 374 |
+
x = ValueRanges.wrap(x)
|
| 375 |
+
if 0 in x:
|
| 376 |
+
upper = max(fn(x.lower), fn(x.upper))
|
| 377 |
+
upper = simple_sympify(upper)
|
| 378 |
+
if isinstance(upper, sympy.Float) or upper == sympy.oo:
|
| 379 |
+
return ValueRanges(0.0, upper)
|
| 380 |
+
return ValueRanges(0, upper)
|
| 381 |
+
return ValueRanges.monotone_map(x, fn)
|
| 382 |
+
|
| 383 |
+
@overload
|
| 384 |
+
@staticmethod
|
| 385 |
+
def coordinatewise_increasing_map(
|
| 386 |
+
x: ExprIn | ExprVR,
|
| 387 |
+
y: ExprIn | ExprVR,
|
| 388 |
+
fn: ExprFn2,
|
| 389 |
+
) -> ExprVR: ...
|
| 390 |
+
|
| 391 |
+
@overload
|
| 392 |
+
@staticmethod
|
| 393 |
+
def coordinatewise_increasing_map( # type: ignore[misc]
|
| 394 |
+
x: BoolIn | BoolVR,
|
| 395 |
+
y: BoolIn | BoolVR,
|
| 396 |
+
fn: BoolFn2,
|
| 397 |
+
) -> BoolVR: ...
|
| 398 |
+
|
| 399 |
+
@staticmethod
|
| 400 |
+
def coordinatewise_increasing_map(
|
| 401 |
+
x: AllIn | AllVR,
|
| 402 |
+
y: AllIn | AllVR,
|
| 403 |
+
fn: AllFn2,
|
| 404 |
+
) -> AllVR:
|
| 405 |
+
"""
|
| 406 |
+
It's increasing on each coordinate.
|
| 407 |
+
|
| 408 |
+
Mathematically:
|
| 409 |
+
For every 1 <= i <= n and x_i <= y_i we have that
|
| 410 |
+
f(x1, .., xn) <= f(x1, , yi, ..., xn)
|
| 411 |
+
"""
|
| 412 |
+
x, y = ValueRanges.wrap(x), ValueRanges.wrap(y)
|
| 413 |
+
return ValueRanges(
|
| 414 |
+
fn(x.lower, y.lower), # type: ignore[arg-type]
|
| 415 |
+
fn(x.upper, y.upper), # type: ignore[arg-type]
|
| 416 |
+
)
|
| 417 |
+
|
| 418 |
+
@classmethod
|
| 419 |
+
def coordinatewise_monotone_map(cls, x, y, fn):
|
| 420 |
+
"""It's increasing or decreasing on each coordinate."""
|
| 421 |
+
x, y = cls.wrap(x), cls.wrap(y)
|
| 422 |
+
products = [
|
| 423 |
+
fn(a, b)
|
| 424 |
+
for a, b in itertools.product([x.lower, x.upper], [y.lower, y.upper])
|
| 425 |
+
]
|
| 426 |
+
return ValueRanges(min(products), max(products))
|
| 427 |
+
|
| 428 |
+
|
| 429 |
+
class SymPyValueRangeAnalysis:
|
| 430 |
+
"""
|
| 431 |
+
It gives bounds on a SymPy operator given bounds on its arguments
|
| 432 |
+
See the function `bound_sympy` for a function that applies this logic to a full SymPy expression
|
| 433 |
+
"""
|
| 434 |
+
|
| 435 |
+
@staticmethod
|
| 436 |
+
def constant(value, dtype):
|
| 437 |
+
if isinstance(value, ValueRanges):
|
| 438 |
+
if not value.is_singleton():
|
| 439 |
+
raise AssertionError("ValueRanges must be a singleton for constant()")
|
| 440 |
+
value = value.lower
|
| 441 |
+
# NB: value is NOT a sympy expression, it's a constant!
|
| 442 |
+
is_python = isinstance(value, (int, float, bool))
|
| 443 |
+
if not is_python and not isinstance(
|
| 444 |
+
value, (BooleanAtom, sympy.Integer, sympy.Number)
|
| 445 |
+
):
|
| 446 |
+
raise AssertionError(f"not a supported constant type: {type(value)}")
|
| 447 |
+
|
| 448 |
+
# using nan makes subsequent computation throw, and for the purposes of optimization
|
| 449 |
+
# returning -math.inf - math.inf is equivalent to giving up
|
| 450 |
+
if isinstance(value, SupportsFloat) and math.isnan(value):
|
| 451 |
+
if dtype == torch.bool:
|
| 452 |
+
return ValueRanges.unknown_bool()
|
| 453 |
+
elif dtype.is_floating_point:
|
| 454 |
+
return ValueRanges.unknown()
|
| 455 |
+
else:
|
| 456 |
+
return ValueRanges.unknown_int()
|
| 457 |
+
|
| 458 |
+
if is_python:
|
| 459 |
+
type_ = dtype_to_type(dtype)
|
| 460 |
+
value = type_(value)
|
| 461 |
+
else:
|
| 462 |
+
# We do a type check on a best-effort basis
|
| 463 |
+
# We don't want to force a cast to sympy.Float if the value is Rational to avoid losing precision
|
| 464 |
+
if dtype == torch.bool:
|
| 465 |
+
if not isinstance(value, BooleanAtom):
|
| 466 |
+
raise AssertionError("expected BooleanAtom for bool dtype")
|
| 467 |
+
elif dtype.is_floating_point:
|
| 468 |
+
if value.is_finite and not value.is_real:
|
| 469 |
+
raise AssertionError(
|
| 470 |
+
"expected float-like sympy value for float dtype"
|
| 471 |
+
)
|
| 472 |
+
else:
|
| 473 |
+
# dtype is intXX
|
| 474 |
+
if not getattr(value, "is_integer", False):
|
| 475 |
+
raise AssertionError("expected integer sympy value for int dtype")
|
| 476 |
+
|
| 477 |
+
r = ValueRanges.wrap(value)
|
| 478 |
+
return r
|
| 479 |
+
|
| 480 |
+
@staticmethod
|
| 481 |
+
def to_dtype(a, dtype, src_dtype=None):
|
| 482 |
+
if dtype == torch.float64:
|
| 483 |
+
# pyrefly: ignore [bad-argument-type]
|
| 484 |
+
return ValueRanges.increasing_map(a, ToFloat)
|
| 485 |
+
elif dtype == torch.bool:
|
| 486 |
+
return ValueRanges.unknown_bool()
|
| 487 |
+
elif not dtype.is_floating_point:
|
| 488 |
+
return ValueRanges.unknown_int()
|
| 489 |
+
return ValueRanges.unknown()
|
| 490 |
+
|
| 491 |
+
@staticmethod
|
| 492 |
+
def trunc_to_int(a, dtype):
|
| 493 |
+
# pyrefly: ignore [bad-argument-type]
|
| 494 |
+
return ValueRanges.increasing_map(a, TruncToInt)
|
| 495 |
+
|
| 496 |
+
@staticmethod
|
| 497 |
+
def not_(a):
|
| 498 |
+
a = ValueRanges.wrap(a)
|
| 499 |
+
a = a.boolify()
|
| 500 |
+
if not a.is_bool:
|
| 501 |
+
raise AssertionError("not_ expects a boolean ValueRanges")
|
| 502 |
+
return ValueRanges.decreasing_map(a, sympy.Not)
|
| 503 |
+
|
| 504 |
+
@staticmethod
|
| 505 |
+
def or_(a, b):
|
| 506 |
+
return ValueRanges.coordinatewise_increasing_map(a, b, sympy.Or)
|
| 507 |
+
|
| 508 |
+
@staticmethod
|
| 509 |
+
def and_(a, b):
|
| 510 |
+
return ValueRanges.coordinatewise_increasing_map(a, b, sympy.And)
|
| 511 |
+
|
| 512 |
+
@staticmethod
|
| 513 |
+
def _bool_to_int(x):
|
| 514 |
+
if x.is_singleton():
|
| 515 |
+
return ValueRanges.wrap(sympy.Integer(1 if x.lower else 0))
|
| 516 |
+
else:
|
| 517 |
+
return ValueRanges(sympy.Integer(0), sympy.Integer(1))
|
| 518 |
+
|
| 519 |
+
@classmethod
|
| 520 |
+
def bitwise_and(cls, a, b):
|
| 521 |
+
a, b = ValueRanges.wrap(a), ValueRanges.wrap(b)
|
| 522 |
+
if a.is_bool and b.is_bool:
|
| 523 |
+
return cls.and_(a, b)
|
| 524 |
+
if a.is_bool:
|
| 525 |
+
a = cls._bool_to_int(a)
|
| 526 |
+
if b.is_bool:
|
| 527 |
+
b = cls._bool_to_int(b)
|
| 528 |
+
lower = min(a.lower, b.lower)
|
| 529 |
+
if lower < 0 and lower != -sympy.oo and lower != -int_oo:
|
| 530 |
+
# If both lower bounds are negative, then bits start like
|
| 531 |
+
# 1...10..., so the smallest possible value is 1...101...1.
|
| 532 |
+
# Thus, we need to find the next smallest power of 2 (inclusive).
|
| 533 |
+
try:
|
| 534 |
+
lower = -(1 << int(-lower - 1).bit_length())
|
| 535 |
+
except Exception:
|
| 536 |
+
lower = -int_oo
|
| 537 |
+
else:
|
| 538 |
+
lower = 0
|
| 539 |
+
return ValueRanges(lower, max(a.upper, b.upper))
|
| 540 |
+
|
| 541 |
+
@classmethod
|
| 542 |
+
def bitwise_or(cls, a, b):
|
| 543 |
+
a, b = ValueRanges.wrap(a), ValueRanges.wrap(b)
|
| 544 |
+
if a.is_bool and b.is_bool:
|
| 545 |
+
return cls.or_(a, b)
|
| 546 |
+
if a.is_bool:
|
| 547 |
+
a = cls._bool_to_int(a)
|
| 548 |
+
if b.is_bool:
|
| 549 |
+
b = cls._bool_to_int(b)
|
| 550 |
+
upper = max(a.upper, b.upper)
|
| 551 |
+
if upper == 0:
|
| 552 |
+
upper = 0
|
| 553 |
+
elif upper > 0 and upper != sympy.oo and upper != int_oo:
|
| 554 |
+
# If both upper bounds are positive, then the largest
|
| 555 |
+
# possible value is 01...1, so we need to find
|
| 556 |
+
# next largest power of 2 (exclusive), minus 1
|
| 557 |
+
try:
|
| 558 |
+
upper = (1 << int(upper).bit_length()) - 1
|
| 559 |
+
except Exception:
|
| 560 |
+
upper = int_oo
|
| 561 |
+
elif upper < 0:
|
| 562 |
+
upper = -1
|
| 563 |
+
return ValueRanges(min(a.lower, b.lower), upper)
|
| 564 |
+
|
| 565 |
+
@classmethod
|
| 566 |
+
def bitwise_xor(cls, a, b):
|
| 567 |
+
a, b = ValueRanges.wrap(a), ValueRanges.wrap(b)
|
| 568 |
+
if a.is_bool and b.is_bool:
|
| 569 |
+
bounds = {
|
| 570 |
+
a.lower ^ b.lower,
|
| 571 |
+
a.lower ^ b.upper,
|
| 572 |
+
a.upper ^ b.lower,
|
| 573 |
+
a.upper ^ b.upper,
|
| 574 |
+
}
|
| 575 |
+
|
| 576 |
+
has_false = any(bound == sympy.false for bound in bounds)
|
| 577 |
+
has_true = any(bound == sympy.true for bound in bounds)
|
| 578 |
+
|
| 579 |
+
if has_false and has_true:
|
| 580 |
+
lower, upper = sympy.false, sympy.true
|
| 581 |
+
elif has_true:
|
| 582 |
+
lower = upper = sympy.true
|
| 583 |
+
elif has_false:
|
| 584 |
+
lower = upper = sympy.false
|
| 585 |
+
else:
|
| 586 |
+
raise AssertionError(f"Non-boolean xor result: {bounds}")
|
| 587 |
+
|
| 588 |
+
return ValueRanges(lower, upper)
|
| 589 |
+
if a.is_bool:
|
| 590 |
+
a = cls._bool_to_int(a)
|
| 591 |
+
if b.is_bool:
|
| 592 |
+
b = cls._bool_to_int(b)
|
| 593 |
+
if (
|
| 594 |
+
a.lower == a.upper
|
| 595 |
+
and b.lower == b.upper
|
| 596 |
+
and is_sympy_integer(a.lower)
|
| 597 |
+
and is_sympy_integer(b.lower)
|
| 598 |
+
):
|
| 599 |
+
value_range = a.lower ^ b.lower
|
| 600 |
+
return ValueRanges(value_range, value_range)
|
| 601 |
+
return ValueRanges(-int_oo, int_oo)
|
| 602 |
+
|
| 603 |
+
@staticmethod
|
| 604 |
+
def eq(a, b):
|
| 605 |
+
a = ValueRanges.wrap(a)
|
| 606 |
+
b = ValueRanges.wrap(b)
|
| 607 |
+
if a.is_singleton() and b.is_singleton() and a.lower == b.lower:
|
| 608 |
+
return ValueRanges.wrap(sympy.true)
|
| 609 |
+
elif a.lower > b.upper or b.lower > a.upper: # ranges disjoint
|
| 610 |
+
return ValueRanges.wrap(sympy.false)
|
| 611 |
+
return ValueRanges(sympy.false, sympy.true)
|
| 612 |
+
|
| 613 |
+
@classmethod
|
| 614 |
+
def ne(cls, a, b):
|
| 615 |
+
return cls.not_(cls.eq(a, b))
|
| 616 |
+
|
| 617 |
+
@classmethod
|
| 618 |
+
def identity(cls, a):
|
| 619 |
+
return ValueRanges.wrap(a)
|
| 620 |
+
|
| 621 |
+
@classmethod
|
| 622 |
+
def lt(cls, a, b):
|
| 623 |
+
a = ValueRanges.wrap(a)
|
| 624 |
+
b = ValueRanges.wrap(b)
|
| 625 |
+
if a.is_bool != b.is_bool:
|
| 626 |
+
raise AssertionError(
|
| 627 |
+
"operands must both be boolean ValueRanges or both non-boolean"
|
| 628 |
+
)
|
| 629 |
+
if a.is_bool:
|
| 630 |
+
return cls.and_(cls.not_(a), b)
|
| 631 |
+
else:
|
| 632 |
+
if a.upper < b.lower:
|
| 633 |
+
return ValueRanges.wrap(sympy.true)
|
| 634 |
+
elif a.lower >= b.upper:
|
| 635 |
+
return ValueRanges.wrap(sympy.false)
|
| 636 |
+
return ValueRanges(sympy.false, sympy.true)
|
| 637 |
+
|
| 638 |
+
@classmethod
|
| 639 |
+
def gt(cls, a, b):
|
| 640 |
+
return cls.lt(b, a)
|
| 641 |
+
|
| 642 |
+
@classmethod
|
| 643 |
+
def le(cls, a, b):
|
| 644 |
+
return cls.not_(cls.gt(a, b))
|
| 645 |
+
|
| 646 |
+
@classmethod
|
| 647 |
+
def ge(cls, a, b):
|
| 648 |
+
return cls.not_(cls.lt(a, b))
|
| 649 |
+
|
| 650 |
+
@staticmethod
|
| 651 |
+
def add(a, b):
|
| 652 |
+
return ValueRanges.coordinatewise_increasing_map(
|
| 653 |
+
a, b, _keep_float(operator.add)
|
| 654 |
+
)
|
| 655 |
+
|
| 656 |
+
@classmethod
|
| 657 |
+
def mul(cls, a, b):
|
| 658 |
+
a = ValueRanges.wrap(a)
|
| 659 |
+
b = ValueRanges.wrap(b)
|
| 660 |
+
|
| 661 |
+
if a.is_bool != b.is_bool:
|
| 662 |
+
raise AssertionError(
|
| 663 |
+
"operands must both be boolean ValueRanges or both non-boolean"
|
| 664 |
+
)
|
| 665 |
+
if a.is_bool:
|
| 666 |
+
return cls.and_(a, b)
|
| 667 |
+
|
| 668 |
+
def safe_mul(a, b):
|
| 669 |
+
# Make unknown() * wrap(0.0) == wrap(0.0)
|
| 670 |
+
if a == 0.0 or a == 0:
|
| 671 |
+
return a
|
| 672 |
+
elif b == 0.0 or b == 0:
|
| 673 |
+
return b
|
| 674 |
+
else:
|
| 675 |
+
return a * b
|
| 676 |
+
|
| 677 |
+
return ValueRanges.coordinatewise_monotone_map(a, b, _keep_float(safe_mul))
|
| 678 |
+
|
| 679 |
+
@staticmethod
|
| 680 |
+
def int_truediv(a, b):
|
| 681 |
+
a = ValueRanges.wrap(a)
|
| 682 |
+
b = ValueRanges.wrap(b)
|
| 683 |
+
if 0 in b or ((-int_oo in a or int_oo in a) and (-int_oo in b or int_oo in b)):
|
| 684 |
+
return ValueRanges.unknown()
|
| 685 |
+
else:
|
| 686 |
+
return ValueRanges.coordinatewise_monotone_map(
|
| 687 |
+
a,
|
| 688 |
+
b,
|
| 689 |
+
# pyrefly: ignore [bad-argument-type]
|
| 690 |
+
_keep_float(IntTrueDiv),
|
| 691 |
+
)
|
| 692 |
+
|
| 693 |
+
@staticmethod
|
| 694 |
+
def truediv(a, b):
|
| 695 |
+
a = ValueRanges.wrap(a)
|
| 696 |
+
b = ValueRanges.wrap(b)
|
| 697 |
+
if 0 in b or (
|
| 698 |
+
(-sympy.oo in a or sympy.oo in a) and (-sympy.oo in b or sympy.oo in b)
|
| 699 |
+
):
|
| 700 |
+
return ValueRanges.unknown()
|
| 701 |
+
else:
|
| 702 |
+
return ValueRanges.coordinatewise_monotone_map(
|
| 703 |
+
a,
|
| 704 |
+
b,
|
| 705 |
+
# pyrefly: ignore [bad-argument-type]
|
| 706 |
+
_keep_float(FloatTrueDiv),
|
| 707 |
+
)
|
| 708 |
+
|
| 709 |
+
@staticmethod
|
| 710 |
+
def floordiv(a, b):
|
| 711 |
+
a = ValueRanges.wrap(a)
|
| 712 |
+
b = ValueRanges.wrap(b)
|
| 713 |
+
|
| 714 |
+
# TODO We shall assume division is always valid probably.
|
| 715 |
+
if 0 in b:
|
| 716 |
+
if b.lower >= 0 and a.lower >= 0:
|
| 717 |
+
return ValueRanges(0, int_oo)
|
| 718 |
+
if b.upper <= 0 and a.upper <= 0:
|
| 719 |
+
return ValueRanges(0, int_oo)
|
| 720 |
+
if b.upper <= 0 and a.lower >= 0:
|
| 721 |
+
return ValueRanges(-int_oo, 0)
|
| 722 |
+
if b.lower >= 0 and a.upper <= 0:
|
| 723 |
+
return ValueRanges(-int_oo, 0)
|
| 724 |
+
return ValueRanges.unknown_int()
|
| 725 |
+
products = []
|
| 726 |
+
for x, y in itertools.product([a.lower, a.upper], [b.lower, b.upper]):
|
| 727 |
+
r = FloorDiv(x, y)
|
| 728 |
+
if r is sympy.nan:
|
| 729 |
+
products.append((sympy.sign(x) * sympy.sign(y)) * int_oo)
|
| 730 |
+
else:
|
| 731 |
+
products.append(r)
|
| 732 |
+
|
| 733 |
+
return ValueRanges(min(products), max(products))
|
| 734 |
+
|
| 735 |
+
@classmethod
|
| 736 |
+
def mod(cls, x, y):
|
| 737 |
+
x = ValueRanges.wrap(x)
|
| 738 |
+
y = ValueRanges.wrap(y)
|
| 739 |
+
# nb. We implement C semantics
|
| 740 |
+
|
| 741 |
+
def c_mod(a, b):
|
| 742 |
+
ret = abs(a) % abs(b)
|
| 743 |
+
if a < 0:
|
| 744 |
+
ret *= -1
|
| 745 |
+
return ret
|
| 746 |
+
|
| 747 |
+
def c_div(a, b):
|
| 748 |
+
x = a / b
|
| 749 |
+
return sympy.Integer(x) if x.is_finite and x not in (int_oo, -int_oo) else x
|
| 750 |
+
|
| 751 |
+
if 0 in y:
|
| 752 |
+
return ValueRanges.unknown_int()
|
| 753 |
+
elif y.is_singleton():
|
| 754 |
+
y_val = abs(y.lower)
|
| 755 |
+
# If it wraps, we need to take the whole interval
|
| 756 |
+
|
| 757 |
+
# The function is locally linear if they are in the same class
|
| 758 |
+
if c_div(x.lower, y_val) == c_div(x.upper, y_val):
|
| 759 |
+
return ValueRanges.increasing_map(x, lambda u: c_mod(u, y_val))
|
| 760 |
+
if x.upper < 0:
|
| 761 |
+
# Negative case
|
| 762 |
+
return ValueRanges(-y_val + 1, 0)
|
| 763 |
+
elif x.lower > 0:
|
| 764 |
+
# Positive case
|
| 765 |
+
return ValueRanges(0, y_val - 1)
|
| 766 |
+
else:
|
| 767 |
+
# Mixed case
|
| 768 |
+
lower = max(-y_val + 1, x.lower)
|
| 769 |
+
upper = min(y_val - 1, x.upper)
|
| 770 |
+
return ValueRanges(lower, upper)
|
| 771 |
+
else:
|
| 772 |
+
# Too difficult, we bail out
|
| 773 |
+
upper = cls.abs(y).upper - 1
|
| 774 |
+
return ValueRanges(-upper, upper)
|
| 775 |
+
|
| 776 |
+
@classmethod
|
| 777 |
+
def python_mod(cls, x, y):
|
| 778 |
+
"""Python-style modulo: result has same sign as divisor.
|
| 779 |
+
|
| 780 |
+
Assumes valid input where y is never 0.
|
| 781 |
+
- When y > 0: result is in [0, y - 1]
|
| 782 |
+
- When y < 0: result is in [y + 1, 0]
|
| 783 |
+
"""
|
| 784 |
+
|
| 785 |
+
x = ValueRanges.wrap(x)
|
| 786 |
+
y = ValueRanges.wrap(y)
|
| 787 |
+
if x.lower >= 0 and y.lower >= 0:
|
| 788 |
+
return SymPyValueRangeAnalysis.mod(x, y)
|
| 789 |
+
lower = y.lower + 1 if y.lower < 0 else 0
|
| 790 |
+
upper = y.upper - 1 if y.upper > 0 else 0
|
| 791 |
+
return ValueRanges(lower, upper)
|
| 792 |
+
|
| 793 |
+
@classmethod
|
| 794 |
+
def modular_indexing(cls, a, b, c):
|
| 795 |
+
return cls.mod(cls.floordiv(a, b), c)
|
| 796 |
+
|
| 797 |
+
@classmethod
|
| 798 |
+
def is_non_overlapping_and_dense_indicator(cls, *args):
|
| 799 |
+
return ValueRanges.unknown_int()
|
| 800 |
+
|
| 801 |
+
@classmethod
|
| 802 |
+
def pow_by_natural(cls, a, b):
|
| 803 |
+
a = ValueRanges.wrap(a)
|
| 804 |
+
b = ValueRanges.wrap(b)
|
| 805 |
+
if a.is_singleton() and b.is_singleton():
|
| 806 |
+
return ValueRanges.wrap(safe_pow(a.lower, b.lower))
|
| 807 |
+
# NB: Exclude zero, because zero is special
|
| 808 |
+
elif a.lower >= 1:
|
| 809 |
+
# We should know that b >= 0 but we may have forgotten this fact due
|
| 810 |
+
# to replacements, so don't assert it, but DO clamp it to prevent
|
| 811 |
+
# degenerate problems
|
| 812 |
+
# pyrefly: ignore [no-matching-overload]
|
| 813 |
+
return ValueRanges.coordinatewise_increasing_map(
|
| 814 |
+
a, b & ValueRanges(0, int_oo), PowByNatural
|
| 815 |
+
)
|
| 816 |
+
elif b.is_singleton():
|
| 817 |
+
if b.lower % 2 == 0:
|
| 818 |
+
# x^n where n is even
|
| 819 |
+
return ValueRanges.convex_min_zero_map(
|
| 820 |
+
a, lambda x: safe_pow(x, b.lower)
|
| 821 |
+
)
|
| 822 |
+
else:
|
| 823 |
+
# x^n where n is odd
|
| 824 |
+
return ValueRanges.increasing_map(a, lambda x: safe_pow(x, b.lower))
|
| 825 |
+
else:
|
| 826 |
+
# a is potentially negative, and we don't know if the exponent is
|
| 827 |
+
# even or odd. So just conservatively set the upper and lower
|
| 828 |
+
# bound based on what the maximum absolute value could be, in both
|
| 829 |
+
# directions
|
| 830 |
+
max_base = max(a.upper, -a.lower)
|
| 831 |
+
return ValueRanges(
|
| 832 |
+
-(safe_pow(max_base, b.upper)), safe_pow(max_base, b.upper)
|
| 833 |
+
)
|
| 834 |
+
|
| 835 |
+
@classmethod
|
| 836 |
+
def pow(cls, a, b):
|
| 837 |
+
return ValueRanges.unknown()
|
| 838 |
+
|
| 839 |
+
# We could implement all this, but for floating point pow, is there
|
| 840 |
+
# really a point?
|
| 841 |
+
"""
|
| 842 |
+
a = ValueRanges.wrap(a)
|
| 843 |
+
b = ValueRanges.wrap(b)
|
| 844 |
+
|
| 845 |
+
# Not implemented yet. It's a bit tricky
|
| 846 |
+
# If you want to implement it, compute the partial derivatives of a ** b
|
| 847 |
+
# and check the ranges where the function is increasing / decreasing
|
| 848 |
+
# Another non-tight way of doing this is defaulting to doing noting that for a > 0, a ** b == exp(b * log(a))
|
| 849 |
+
# If this second option is implemented, by carefult about the types and possible infinities here and there.
|
| 850 |
+
if not b.is_singleton():
|
| 851 |
+
return ValueRanges.unknown()
|
| 852 |
+
|
| 853 |
+
b = b.lower
|
| 854 |
+
if a.is_singleton():
|
| 855 |
+
a = a.lower
|
| 856 |
+
r = a**b
|
| 857 |
+
if not r.is_finite:
|
| 858 |
+
return ValueRanges.unknown()
|
| 859 |
+
return ValueRanges.wrap(r)
|
| 860 |
+
|
| 861 |
+
if b == 0:
|
| 862 |
+
if not a.lower.is_finite:
|
| 863 |
+
return ValueRanges.unknown()
|
| 864 |
+
return ValueRanges.wrap(1.0)
|
| 865 |
+
|
| 866 |
+
if b < 0:
|
| 867 |
+
a = cls.reciprocal(a)
|
| 868 |
+
b = -b
|
| 869 |
+
|
| 870 |
+
if a == ValueRanges.unknown():
|
| 871 |
+
return ValueRanges.unknown()
|
| 872 |
+
|
| 873 |
+
# If the base is positive, then we're good, otherwise nothing's defined
|
| 874 |
+
if a.lower >= 0:
|
| 875 |
+
return ValueRanges.increasing_map(a, lambda x: x**b)
|
| 876 |
+
else:
|
| 877 |
+
return ValueRanges.unknown()
|
| 878 |
+
"""
|
| 879 |
+
|
| 880 |
+
@staticmethod
|
| 881 |
+
def reciprocal(x):
|
| 882 |
+
"""Needed as it's used in pow, but it won't appear on a SymPy expression"""
|
| 883 |
+
x = ValueRanges.wrap(x)
|
| 884 |
+
if 0 in x:
|
| 885 |
+
return ValueRanges.unknown()
|
| 886 |
+
else:
|
| 887 |
+
return ValueRanges.decreasing_map(x, lambda y: FloatTrueDiv(1.0, y)) # type: ignore[operator]
|
| 888 |
+
|
| 889 |
+
@staticmethod
|
| 890 |
+
def abs(x):
|
| 891 |
+
return ValueRanges.convex_min_zero_map(x, abs)
|
| 892 |
+
|
| 893 |
+
@staticmethod
|
| 894 |
+
def exp(x):
|
| 895 |
+
return ValueRanges.increasing_map(x, OpaqueUnaryFn_exp)
|
| 896 |
+
|
| 897 |
+
@staticmethod
|
| 898 |
+
def log(x):
|
| 899 |
+
x = ValueRanges.wrap(x)
|
| 900 |
+
if x.lower <= 0:
|
| 901 |
+
return ValueRanges.unknown()
|
| 902 |
+
return ValueRanges.increasing_map(x, OpaqueUnaryFn_log)
|
| 903 |
+
|
| 904 |
+
@staticmethod
|
| 905 |
+
def log2(x):
|
| 906 |
+
x = ValueRanges.wrap(x)
|
| 907 |
+
if x.lower <= 0:
|
| 908 |
+
return ValueRanges.unknown()
|
| 909 |
+
return ValueRanges.increasing_map(x, OpaqueUnaryFn_log2)
|
| 910 |
+
|
| 911 |
+
@classmethod
|
| 912 |
+
def minimum(cls, a, b):
|
| 913 |
+
return cls.min_or_max(a, b, sympy.Min)
|
| 914 |
+
|
| 915 |
+
@classmethod
|
| 916 |
+
def maximum(cls, a, b):
|
| 917 |
+
return cls.min_or_max(a, b, sympy.Max)
|
| 918 |
+
|
| 919 |
+
@staticmethod
|
| 920 |
+
def min_or_max(a, b, fn):
|
| 921 |
+
a = ValueRanges.wrap(a)
|
| 922 |
+
b = ValueRanges.wrap(b)
|
| 923 |
+
return ValueRanges.coordinatewise_increasing_map(a, b, fn)
|
| 924 |
+
|
| 925 |
+
@classmethod
|
| 926 |
+
def floor_to_int(cls, x, dtype):
|
| 927 |
+
return ValueRanges.increasing_map(x, sympy.functions.elementary.integers.floor)
|
| 928 |
+
|
| 929 |
+
@classmethod
|
| 930 |
+
def ceil_to_int(cls, x, dtype):
|
| 931 |
+
return ValueRanges.increasing_map(
|
| 932 |
+
x, sympy.functions.elementary.integers.ceiling
|
| 933 |
+
)
|
| 934 |
+
|
| 935 |
+
# I think these implementations are sound. The hazard here is that sympy
|
| 936 |
+
# will carry out the floor/ceil at too high precision and then something
|
| 937 |
+
# bad will happen when we convert it to float.
|
| 938 |
+
#
|
| 939 |
+
# For truncation, the implementation is clearly sound, because the desired
|
| 940 |
+
# target float is always exactly representable, since you're just chopping
|
| 941 |
+
# off bits the mantissa. But what about ceil/floor?
|
| 942 |
+
#
|
| 943 |
+
# The important constraint here is that we're not defining floor on
|
| 944 |
+
# arbitrary real numbers, only representable float numbers. So we can
|
| 945 |
+
# take advantage of the fact that before we reach the first
|
| 946 |
+
# unrepresentable integer in floating point space, we have the range of
|
| 947 |
+
# numbers corresponding to exponent zero: all integers, with no fractional
|
| 948 |
+
# amounts. floor/ceil is an identity operation in this case. In the
|
| 949 |
+
# range below here, representable floating point numbers are spaced
|
| 950 |
+
# exactly 1/2 apart, and notably, both the floor/ceil are defined floating
|
| 951 |
+
# point numbers. There is no "gap" as you step up to the next exponent.
|
| 952 |
+
|
| 953 |
+
@classmethod
|
| 954 |
+
def floor(cls, x):
|
| 955 |
+
return ValueRanges.increasing_map(
|
| 956 |
+
x, _keep_float(sympy.functions.elementary.integers.floor)
|
| 957 |
+
)
|
| 958 |
+
|
| 959 |
+
@classmethod
|
| 960 |
+
def ceil(cls, x):
|
| 961 |
+
return ValueRanges.increasing_map(
|
| 962 |
+
x, _keep_float(sympy.functions.elementary.integers.ceiling)
|
| 963 |
+
)
|
| 964 |
+
|
| 965 |
+
@classmethod
|
| 966 |
+
def round_decimal(cls, number, ndigits):
|
| 967 |
+
if not ndigits.is_singleton():
|
| 968 |
+
return ValueRanges.unknown()
|
| 969 |
+
|
| 970 |
+
ndigits = ndigits.lower
|
| 971 |
+
# We can't use functools.partial here since sympy doesn't support keyword arguments, but we have to bind
|
| 972 |
+
# the second parameter.
|
| 973 |
+
fn = lambda number: RoundDecimal(number, ndigits) # type: ignore[misc, assignment] # noqa: E731
|
| 974 |
+
|
| 975 |
+
return ValueRanges.increasing_map(number, fn)
|
| 976 |
+
|
| 977 |
+
@classmethod
|
| 978 |
+
def round_to_int(cls, number, dtype):
|
| 979 |
+
# pyrefly: ignore [bad-argument-type]
|
| 980 |
+
return ValueRanges.increasing_map(number, RoundToInt)
|
| 981 |
+
|
| 982 |
+
# It's used in some models on symints
|
| 983 |
+
@staticmethod
|
| 984 |
+
def sqrt(x):
|
| 985 |
+
x = ValueRanges.wrap(x)
|
| 986 |
+
if x.lower < 0:
|
| 987 |
+
return ValueRanges.unknown()
|
| 988 |
+
return ValueRanges.increasing_map(x, OpaqueUnaryFn_sqrt)
|
| 989 |
+
|
| 990 |
+
@staticmethod
|
| 991 |
+
def where(a, b, c):
|
| 992 |
+
b = ValueRanges.wrap(b)
|
| 993 |
+
c = ValueRanges.wrap(c)
|
| 994 |
+
a = a.boolify()
|
| 995 |
+
# We sometimes write unknown without specifying the type correctly
|
| 996 |
+
# In particular, we do that when initialising the bounds for loads in bounds.py
|
| 997 |
+
if b.is_bool != c.is_bool and ValueRanges.unknown() not in (b, c):
|
| 998 |
+
raise AssertionError(
|
| 999 |
+
"where() requires b and c to have the same boolean-ness or allow unknown()"
|
| 1000 |
+
)
|
| 1001 |
+
if b.is_bool:
|
| 1002 |
+
return ValueRanges(sympy.And(b.lower, c.lower), sympy.Or(b.upper, c.upper))
|
| 1003 |
+
else:
|
| 1004 |
+
return ValueRanges(sympy.Min(b.lower, c.lower), sympy.Max(b.upper, c.upper))
|
| 1005 |
+
|
| 1006 |
+
# expr_cond_pair is used to represent a single (expr, condition) pair in piecewise.
|
| 1007 |
+
# We just return the value range of the expression and its corresponding condition as a tuple
|
| 1008 |
+
# and defer the analysis to piecewise
|
| 1009 |
+
@staticmethod
|
| 1010 |
+
def expr_cond_pair(a, b):
|
| 1011 |
+
b = b.boolify()
|
| 1012 |
+
return (a, b)
|
| 1013 |
+
|
| 1014 |
+
# piecewise function can be used to convert a SymBool to SymInt:
|
| 1015 |
+
# int_expr = Piecewise((1, bool_expr), (0, True)), it evaluates to 1 when sym_bool is True and 0 otherwise.
|
| 1016 |
+
#
|
| 1017 |
+
# ranges is a sequence of (expr_range, condition_range) pairs. The range pair is constructed in expr_cond_pair.
|
| 1018 |
+
# The ValueRange of Piecewise is just the union of all expr ranges whose condition expr can be True.
|
| 1019 |
+
@staticmethod
|
| 1020 |
+
def piecewise(*ranges):
|
| 1021 |
+
init_range = None
|
| 1022 |
+
for expr_range, cond_range in ranges:
|
| 1023 |
+
if sympy.true in cond_range:
|
| 1024 |
+
if init_range is None:
|
| 1025 |
+
init_range = expr_range
|
| 1026 |
+
else:
|
| 1027 |
+
init_range = init_range | expr_range
|
| 1028 |
+
return init_range
|
| 1029 |
+
|
| 1030 |
+
@staticmethod
|
| 1031 |
+
def cos(x):
|
| 1032 |
+
# TODO: We should tighten value ranges
|
| 1033 |
+
# If input range span is pi + 2*pi*k, then output range is (-1, 1)
|
| 1034 |
+
# otherwise the minimum of the value of the function on the extremes
|
| 1035 |
+
return ValueRanges(-1.0, 1.0)
|
| 1036 |
+
|
| 1037 |
+
@staticmethod
|
| 1038 |
+
def cosh(x):
|
| 1039 |
+
return ValueRanges(0.0, sympy.oo)
|
| 1040 |
+
"""
|
| 1041 |
+
x = ValueRanges.wrap(x)
|
| 1042 |
+
if x.lower > 0:
|
| 1043 |
+
return ValueRanges.increasing_map(x, OpaqueUnaryFn_cosh)
|
| 1044 |
+
elif x.upper < 0:
|
| 1045 |
+
return ValueRanges.decreasing_map(x, OpaqueUnaryFn_cosh)
|
| 1046 |
+
return ValueRanges(0.0, sympy.oo)
|
| 1047 |
+
"""
|
| 1048 |
+
|
| 1049 |
+
@staticmethod
|
| 1050 |
+
def sin(x):
|
| 1051 |
+
# TODO: We should tighten value ranges
|
| 1052 |
+
# See details on cos
|
| 1053 |
+
return ValueRanges(-1.0, 1.0)
|
| 1054 |
+
|
| 1055 |
+
@staticmethod
|
| 1056 |
+
def sinh(x):
|
| 1057 |
+
# return ValueRanges.increasing_map(x, OpaqueUnaryFn_sinh)
|
| 1058 |
+
return ValueRanges(-sympy.oo, sympy.oo)
|
| 1059 |
+
|
| 1060 |
+
@staticmethod
|
| 1061 |
+
def tan(x):
|
| 1062 |
+
return ValueRanges(-sympy.oo, sympy.oo)
|
| 1063 |
+
|
| 1064 |
+
@staticmethod
|
| 1065 |
+
def tanh(x):
|
| 1066 |
+
# return ValueRanges.increasing_map(x, OpaqueUnaryFn_tanh)
|
| 1067 |
+
return ValueRanges(-sympy.oo, sympy.oo)
|
| 1068 |
+
|
| 1069 |
+
@staticmethod
|
| 1070 |
+
def asin(x):
|
| 1071 |
+
return ValueRanges(-sympy.oo, sympy.oo)
|
| 1072 |
+
"""
|
| 1073 |
+
x = ValueRanges.wrap(x)
|
| 1074 |
+
if -1 <= x.lower and x.upper <= 1:
|
| 1075 |
+
return ValueRanges.increasing_map(x, OpaqueUnaryFn_asinh)
|
| 1076 |
+
return ValueRanges.unknown()
|
| 1077 |
+
"""
|
| 1078 |
+
|
| 1079 |
+
@staticmethod
|
| 1080 |
+
def acos(x):
|
| 1081 |
+
return ValueRanges(-sympy.oo, sympy.oo)
|
| 1082 |
+
"""
|
| 1083 |
+
x = ValueRanges.wrap(x)
|
| 1084 |
+
if -1 <= x.lower and x.upper <= 1:
|
| 1085 |
+
return ValueRanges.decreasing_map(x, OpaqueUnaryFn_acos)
|
| 1086 |
+
return ValueRanges.unknown()
|
| 1087 |
+
"""
|
| 1088 |
+
|
| 1089 |
+
@staticmethod
|
| 1090 |
+
def atan(x):
|
| 1091 |
+
return ValueRanges(-sympy.oo, sympy.oo)
|
| 1092 |
+
# return ValueRanges.increasing_map(x, OpaqueUnaryFn_atan)
|
| 1093 |
+
|
| 1094 |
+
@staticmethod
|
| 1095 |
+
def trunc(x):
|
| 1096 |
+
# pyrefly: ignore [bad-argument-type]
|
| 1097 |
+
return ValueRanges.increasing_map(x, TruncToFloat)
|
| 1098 |
+
|
| 1099 |
+
|
| 1100 |
+
def bound_sympy(
|
| 1101 |
+
expr: sympy.Expr, ranges: dict[sympy.Symbol, ValueRanges] | None = None
|
| 1102 |
+
) -> ValueRanges:
|
| 1103 |
+
log.debug(
|
| 1104 |
+
"bound_sympy(%s)%s",
|
| 1105 |
+
expr,
|
| 1106 |
+
LazyString(
|
| 1107 |
+
lambda: (
|
| 1108 |
+
"\n"
|
| 1109 |
+
+ "\n".join(
|
| 1110 |
+
f" {k}: {r}" for k, r in ranges.items() if k in expr.free_symbols
|
| 1111 |
+
)
|
| 1112 |
+
if ranges
|
| 1113 |
+
else ""
|
| 1114 |
+
)
|
| 1115 |
+
),
|
| 1116 |
+
)
|
| 1117 |
+
if isinstance(expr, sympy.Number):
|
| 1118 |
+
return ValueRanges.wrap(expr)
|
| 1119 |
+
|
| 1120 |
+
ranges = ranges or {}
|
| 1121 |
+
|
| 1122 |
+
# If there's a tracing context, augment available constrained ranges.
|
| 1123 |
+
context = torch._guards.TracingContext.try_get()
|
| 1124 |
+
if context and context.fake_mode and context.fake_mode.shape_env:
|
| 1125 |
+
if ranges:
|
| 1126 |
+
ranges = {**context.fake_mode.shape_env.var_to_range, **ranges}
|
| 1127 |
+
else:
|
| 1128 |
+
ranges = context.fake_mode.shape_env.var_to_range
|
| 1129 |
+
|
| 1130 |
+
def missing_handler(s):
|
| 1131 |
+
if s.is_integer: # type: ignore[attr-defined]
|
| 1132 |
+
if s.is_positive: # type: ignore[attr-defined]
|
| 1133 |
+
vr = ValueRanges(1, int_oo)
|
| 1134 |
+
elif s.is_nonnegative: # type: ignore[attr-defined]
|
| 1135 |
+
vr = ValueRanges(0, int_oo)
|
| 1136 |
+
else:
|
| 1137 |
+
vr = ValueRanges.unknown_int()
|
| 1138 |
+
else:
|
| 1139 |
+
# Don't bother trying very hard here
|
| 1140 |
+
vr = ValueRanges.unknown()
|
| 1141 |
+
return vr
|
| 1142 |
+
|
| 1143 |
+
return sympy_interp(
|
| 1144 |
+
SymPyValueRangeAnalysis, ranges, expr, missing_handler=missing_handler
|
| 1145 |
+
)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/_thunk.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections.abc import Callable
|
| 2 |
+
from typing import Generic, TypeVar
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
R = TypeVar("R")
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class Thunk(Generic[R]):
|
| 9 |
+
"""
|
| 10 |
+
A simple lazy evaluation implementation that lets you delay
|
| 11 |
+
execution of a function. It properly handles releasing the
|
| 12 |
+
function once it is forced.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
f: Callable[[], R] | None
|
| 16 |
+
r: R | None
|
| 17 |
+
|
| 18 |
+
__slots__ = ["f", "r"]
|
| 19 |
+
|
| 20 |
+
def __init__(self, f: Callable[[], R]) -> None:
|
| 21 |
+
self.f = f
|
| 22 |
+
self.r = None
|
| 23 |
+
|
| 24 |
+
def force(self) -> R:
|
| 25 |
+
if self.f is None:
|
| 26 |
+
return self.r # type: ignore[return-value]
|
| 27 |
+
self.r = self.f()
|
| 28 |
+
self.f = None
|
| 29 |
+
return self.r
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/_traceback.py
ADDED
|
@@ -0,0 +1,260 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import contextlib
|
| 3 |
+
import inspect
|
| 4 |
+
import os.path
|
| 5 |
+
import tempfile
|
| 6 |
+
import traceback
|
| 7 |
+
from types import TracebackType
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
# This file contains utilities for ensuring dynamically compile()'d
|
| 11 |
+
# code fragments display their line numbers in backtraces.
|
| 12 |
+
#
|
| 13 |
+
# The constraints:
|
| 14 |
+
#
|
| 15 |
+
# - We don't have control over the user exception printer (in particular,
|
| 16 |
+
# we cannot assume the linecache trick will work, c.f.
|
| 17 |
+
# https://stackoverflow.com/q/50515651/23845 )
|
| 18 |
+
#
|
| 19 |
+
# - We don't want to create temporary files every time we compile()
|
| 20 |
+
# some code; file creation should happen lazily only at exception
|
| 21 |
+
# time. Arguably, you *should* be willing to write out your
|
| 22 |
+
# generated Python code to file system, but in some situations
|
| 23 |
+
# (esp. library code) it would violate user expectation to write
|
| 24 |
+
# to the file system, so we try to avoid it. In particular, we'd
|
| 25 |
+
# like to keep the files around, so users can open up the files
|
| 26 |
+
# mentioned in the trace; if the file is invisible, we want to
|
| 27 |
+
# avoid clogging up the filesystem.
|
| 28 |
+
#
|
| 29 |
+
# If this is not a constraint for you, there is a substantially simpler
|
| 30 |
+
# way to implement the functionality in this PR: instead of using
|
| 31 |
+
# eval/exec directly, just always write a Python file to filesystem
|
| 32 |
+
# and compile that.
|
| 33 |
+
#
|
| 34 |
+
# - You have control over a context where the compiled code will get
|
| 35 |
+
# executed, so that we can interpose while the stack is unwinding
|
| 36 |
+
# (otherwise, we have no way to interpose on the exception printing
|
| 37 |
+
# process.)
|
| 38 |
+
#
|
| 39 |
+
# There are two things you have to do to make use of the utilities here:
|
| 40 |
+
#
|
| 41 |
+
# - When you compile your source code, you must save its string source
|
| 42 |
+
# in its f_globals under the magic name "__compile_source__"
|
| 43 |
+
#
|
| 44 |
+
# - Before running the compiled code, enter the
|
| 45 |
+
# report_compile_source_on_error() context manager.
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
@contextlib.contextmanager
|
| 49 |
+
def report_compile_source_on_error():
|
| 50 |
+
try:
|
| 51 |
+
yield
|
| 52 |
+
except Exception as exc:
|
| 53 |
+
tb = exc.__traceback__
|
| 54 |
+
|
| 55 |
+
# Walk the traceback, looking for frames that have
|
| 56 |
+
# source attached
|
| 57 |
+
stack = []
|
| 58 |
+
while tb is not None:
|
| 59 |
+
filename = tb.tb_frame.f_code.co_filename
|
| 60 |
+
source = tb.tb_frame.f_globals.get("__compile_source__")
|
| 61 |
+
|
| 62 |
+
if filename == "<string>" and source is not None:
|
| 63 |
+
# What black magic are we doing here? Intuitively, what
|
| 64 |
+
# we would like to do is overwrite the co_filename on any
|
| 65 |
+
# frames that were generated from exec/eval so that they
|
| 66 |
+
# point to a temporary file that has the actual line
|
| 67 |
+
# information, so Python's default error printer can print
|
| 68 |
+
# useful line information on it.
|
| 69 |
+
#
|
| 70 |
+
# Writing out the temporary file is easy. But overwriting
|
| 71 |
+
# co_filename is not! You can't modify the code object
|
| 72 |
+
# associated with a frame. You can, however, reconstruct
|
| 73 |
+
# a traceback with entirely new frames from scratch, so that's
|
| 74 |
+
# what we do. But there's another problem, which is how to
|
| 75 |
+
# make the frame?
|
| 76 |
+
#
|
| 77 |
+
# The black magic is we make a frankenstein frame and code
|
| 78 |
+
# object which resembles the original frame/code enough so
|
| 79 |
+
# that it will print properly under traceback and the default
|
| 80 |
+
# error printer, but IT IS NOT THE ORIGINAL FRAME (you
|
| 81 |
+
# couldn't, e.g., execute its code with different variables
|
| 82 |
+
# and expect it to work.)
|
| 83 |
+
|
| 84 |
+
# Don't delete the temporary file so the user can inspect it
|
| 85 |
+
# TODO: This creates a temporary file for every frame, but we
|
| 86 |
+
# technically only need one per distinct __compile_source__
|
| 87 |
+
with tempfile.NamedTemporaryFile(
|
| 88 |
+
mode="w", delete=False, suffix=".py"
|
| 89 |
+
) as f:
|
| 90 |
+
f.write(source)
|
| 91 |
+
# Create a frame. Python doesn't let you construct
|
| 92 |
+
# FrameType directly, so just make one with compile
|
| 93 |
+
frame = tb.tb_frame
|
| 94 |
+
code = compile("__inspect_currentframe()", f.name, "eval")
|
| 95 |
+
code = code.replace(co_name=frame.f_code.co_name)
|
| 96 |
+
# Python 3.11 only
|
| 97 |
+
if hasattr(frame.f_code, "co_linetable"):
|
| 98 |
+
# We can't copy ALL of the metadata over, because you
|
| 99 |
+
# can cause Python to segfault this way. What exactly
|
| 100 |
+
# do we need? We need enough information for
|
| 101 |
+
# traceback to be able to print the exception
|
| 102 |
+
# correctly. Code reading Lib/traceback.py reveals
|
| 103 |
+
# that traceback calls code.co_positions() in order to
|
| 104 |
+
# get the augmented line/col numbers. Objects/codeobject.c,
|
| 105 |
+
# specifically _PyCode_InitAddressRange, reveals that
|
| 106 |
+
# this iterator is initialized from co_linetable and
|
| 107 |
+
# co_firstfileno. So copy these we must!
|
| 108 |
+
code = code.replace( # type: ignore[call-arg]
|
| 109 |
+
co_linetable=frame.f_code.co_linetable, # type: ignore[attr-defined]
|
| 110 |
+
co_firstlineno=frame.f_code.co_firstlineno, # type: ignore[attr-defined]
|
| 111 |
+
)
|
| 112 |
+
fake_frame = eval(
|
| 113 |
+
code,
|
| 114 |
+
frame.f_globals,
|
| 115 |
+
{**frame.f_locals, "__inspect_currentframe": inspect.currentframe},
|
| 116 |
+
)
|
| 117 |
+
fake_tb = TracebackType(None, fake_frame, tb.tb_lasti, tb.tb_lineno)
|
| 118 |
+
stack.append(fake_tb)
|
| 119 |
+
else:
|
| 120 |
+
stack.append(tb)
|
| 121 |
+
|
| 122 |
+
tb = tb.tb_next
|
| 123 |
+
|
| 124 |
+
# Reconstruct the linked list
|
| 125 |
+
tb_next = None
|
| 126 |
+
for tb in reversed(stack):
|
| 127 |
+
tb.tb_next = tb_next
|
| 128 |
+
tb_next = tb
|
| 129 |
+
|
| 130 |
+
raise exc.with_traceback(tb_next) # noqa: B904
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def shorten_filename(fn, *, base=None):
|
| 134 |
+
"""Shorten a source filepath, with the assumption that torch/ subdirectories don't need to be shown to user."""
|
| 135 |
+
if base is None:
|
| 136 |
+
base = os.path.dirname(os.path.dirname(__file__))
|
| 137 |
+
# Truncate torch/foo.py to foo.py
|
| 138 |
+
try:
|
| 139 |
+
prefix = os.path.commonpath([fn, base])
|
| 140 |
+
except ValueError:
|
| 141 |
+
return fn
|
| 142 |
+
else:
|
| 143 |
+
return fn[len(prefix) + 1 :]
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def format_frame(frame, *, base=None, line=False) -> str:
|
| 147 |
+
"""
|
| 148 |
+
Format a FrameSummary in a short way, without printing full absolute path or code.
|
| 149 |
+
|
| 150 |
+
The idea is the result fits on a single line.
|
| 151 |
+
"""
|
| 152 |
+
extra_line = ""
|
| 153 |
+
if line:
|
| 154 |
+
extra_line = f"{frame.line} # "
|
| 155 |
+
return f"{extra_line}{shorten_filename(frame.filename, base=base)}:{frame.lineno} in {frame.name}"
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def format_traceback_short(tb):
|
| 159 |
+
"""Format a TracebackType in a short way, printing only the inner-most frame."""
|
| 160 |
+
return format_frame(traceback.extract_tb(tb)[-1])
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
class CapturedTraceback:
|
| 164 |
+
__slots__ = ["tb", "skip"]
|
| 165 |
+
|
| 166 |
+
def __init__(self, tb, skip=0) -> None:
|
| 167 |
+
self.tb = tb
|
| 168 |
+
self.skip = skip
|
| 169 |
+
|
| 170 |
+
def cleanup(self) -> None:
|
| 171 |
+
self.tb = None
|
| 172 |
+
|
| 173 |
+
def summary(self):
|
| 174 |
+
import torch._C._profiler
|
| 175 |
+
|
| 176 |
+
if self.tb is None:
|
| 177 |
+
# TODO: Maybe indicate that the traceback was elided?
|
| 178 |
+
return traceback.StackSummary()
|
| 179 |
+
|
| 180 |
+
return _extract_symbolized_tb(
|
| 181 |
+
torch._C._profiler.symbolize_tracebacks([self.tb])[0], self.skip
|
| 182 |
+
)
|
| 183 |
+
|
| 184 |
+
def __getstate__(self):
|
| 185 |
+
return (
|
| 186 |
+
None,
|
| 187 |
+
{
|
| 188 |
+
"tb": None, # TB is not pickleable
|
| 189 |
+
"skip": self.skip,
|
| 190 |
+
},
|
| 191 |
+
)
|
| 192 |
+
|
| 193 |
+
@staticmethod
|
| 194 |
+
def extract(*, script=False, cpp=False, skip=0):
|
| 195 |
+
"""
|
| 196 |
+
Like traceback.extract_stack(), but faster (approximately 20x faster); it
|
| 197 |
+
is fast enough that you can unconditionally log stacks this way as part of
|
| 198 |
+
normal execution. It returns a torch._C._profiler.CapturedTraceback
|
| 199 |
+
object that must be formatted specially with format_captured_tb.
|
| 200 |
+
|
| 201 |
+
By default, this only reports Python backtraces (like extract_stack). You
|
| 202 |
+
can set the script/cpp kwargs to also turn on TorchScript/C++ trace
|
| 203 |
+
reporting.
|
| 204 |
+
"""
|
| 205 |
+
import torch._C._profiler
|
| 206 |
+
|
| 207 |
+
if script or cpp:
|
| 208 |
+
if skip != 0:
|
| 209 |
+
raise AssertionError("skip with script/cpp NYI")
|
| 210 |
+
|
| 211 |
+
return CapturedTraceback(
|
| 212 |
+
torch._C._profiler.gather_traceback(python=True, script=script, cpp=cpp),
|
| 213 |
+
# Elide extract() frame if we don't have script/cpp frames. If
|
| 214 |
+
# we do have those frames, it doesn't work so force zero.
|
| 215 |
+
0 if script or cpp else skip + 1,
|
| 216 |
+
)
|
| 217 |
+
|
| 218 |
+
def format(self):
|
| 219 |
+
"""
|
| 220 |
+
Formats a single torch._C._profiler.CapturedTraceback into a list of
|
| 221 |
+
strings equivalent to the output of traceback.format_list. Note that if
|
| 222 |
+
pass it CapturedTraceback with C++ traces, it is better not to use this
|
| 223 |
+
function and use the batch formatting API format_captured_tbs to amortize
|
| 224 |
+
the cost of symbolization
|
| 225 |
+
"""
|
| 226 |
+
return traceback.format_list(self.summary())
|
| 227 |
+
|
| 228 |
+
@staticmethod
|
| 229 |
+
def format_all(tbs):
|
| 230 |
+
"""
|
| 231 |
+
Bulk version of CapturedTraceback.format. Returns a list of list of strings.
|
| 232 |
+
"""
|
| 233 |
+
import torch._C._profiler
|
| 234 |
+
|
| 235 |
+
# Directly populate tracebacks that already have cached summaries
|
| 236 |
+
rs: list[list[str] | None] = []
|
| 237 |
+
delayed_idxs = []
|
| 238 |
+
for i, tb in enumerate(tbs):
|
| 239 |
+
if tb.tb is None:
|
| 240 |
+
rs.append([])
|
| 241 |
+
else:
|
| 242 |
+
rs.append(None)
|
| 243 |
+
delayed_idxs.append(i)
|
| 244 |
+
|
| 245 |
+
torch._C._profiler.symbolize_tracebacks([tbs[i].tb for i in delayed_idxs])
|
| 246 |
+
for i in delayed_idxs:
|
| 247 |
+
rs[i] = traceback.format_list(tbs[i].summary())
|
| 248 |
+
|
| 249 |
+
return rs
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
def _extract_symbolized_tb(tb, skip):
|
| 253 |
+
"""
|
| 254 |
+
Given a symbolized traceback from symbolize_tracebacks, return a StackSummary object of
|
| 255 |
+
pre-processed stack trace entries.
|
| 256 |
+
"""
|
| 257 |
+
stack = traceback.StackSummary()
|
| 258 |
+
for f in reversed(tb[skip:]):
|
| 259 |
+
stack.append(traceback.FrameSummary(f["filename"], f["line"], f["name"]))
|
| 260 |
+
return stack
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/_triton.py
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
| 2 |
+
import hashlib
|
| 3 |
+
from typing import Any
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
@functools.cache
|
| 7 |
+
def has_triton_package() -> bool:
|
| 8 |
+
try:
|
| 9 |
+
import triton # noqa: F401
|
| 10 |
+
|
| 11 |
+
return True
|
| 12 |
+
except ImportError:
|
| 13 |
+
return False
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
@functools.cache
|
| 17 |
+
def get_triton_version(fallback: tuple[int, int] = (0, 0)) -> tuple[int, int]:
|
| 18 |
+
try:
|
| 19 |
+
import triton
|
| 20 |
+
|
| 21 |
+
major, minor = tuple(int(v) for v in triton.__version__.split(".")[:2])
|
| 22 |
+
return (major, minor)
|
| 23 |
+
except ImportError:
|
| 24 |
+
return fallback
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@functools.cache
|
| 28 |
+
def _device_supports_tma() -> bool:
|
| 29 |
+
import torch
|
| 30 |
+
|
| 31 |
+
return (
|
| 32 |
+
torch.cuda.is_available()
|
| 33 |
+
and torch.cuda.get_device_capability() >= (9, 0)
|
| 34 |
+
and not torch.version.hip
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
@functools.cache
|
| 39 |
+
def has_triton_experimental_host_tma() -> bool:
|
| 40 |
+
if has_triton_package():
|
| 41 |
+
if _device_supports_tma():
|
| 42 |
+
try:
|
| 43 |
+
from triton.tools.experimental_descriptor import ( # noqa: F401
|
| 44 |
+
create_1d_tma_descriptor,
|
| 45 |
+
create_2d_tma_descriptor,
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
try:
|
| 49 |
+
from triton.tools.experimental_descriptor import enable_in_pytorch
|
| 50 |
+
|
| 51 |
+
return enable_in_pytorch()
|
| 52 |
+
except ImportError:
|
| 53 |
+
return True
|
| 54 |
+
except ImportError:
|
| 55 |
+
pass
|
| 56 |
+
|
| 57 |
+
return False
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
@functools.cache
|
| 61 |
+
def has_triton_tensor_descriptor_host_tma() -> bool:
|
| 62 |
+
if has_triton_package():
|
| 63 |
+
if _device_supports_tma():
|
| 64 |
+
try:
|
| 65 |
+
from triton.tools.tensor_descriptor import ( # noqa: F401
|
| 66 |
+
TensorDescriptor,
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
return True
|
| 70 |
+
except ImportError:
|
| 71 |
+
pass
|
| 72 |
+
|
| 73 |
+
return False
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
@functools.cache
|
| 77 |
+
def has_triton_tma() -> bool:
|
| 78 |
+
return has_triton_tensor_descriptor_host_tma() or has_triton_experimental_host_tma()
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
@functools.cache
|
| 82 |
+
def has_triton_tma_device() -> bool:
|
| 83 |
+
if has_triton_package():
|
| 84 |
+
import torch
|
| 85 |
+
|
| 86 |
+
if (
|
| 87 |
+
torch.cuda.is_available()
|
| 88 |
+
and torch.cuda.get_device_capability() >= (9, 0)
|
| 89 |
+
and not torch.version.hip
|
| 90 |
+
) or torch.xpu.is_available():
|
| 91 |
+
# old API
|
| 92 |
+
try:
|
| 93 |
+
from triton.language.extra.cuda import ( # noqa: F401
|
| 94 |
+
experimental_device_tensormap_create1d,
|
| 95 |
+
experimental_device_tensormap_create2d,
|
| 96 |
+
)
|
| 97 |
+
|
| 98 |
+
return True
|
| 99 |
+
except ImportError:
|
| 100 |
+
pass
|
| 101 |
+
|
| 102 |
+
# new API
|
| 103 |
+
try:
|
| 104 |
+
from triton.language import make_tensor_descriptor # noqa: F401
|
| 105 |
+
|
| 106 |
+
return True
|
| 107 |
+
except ImportError:
|
| 108 |
+
pass
|
| 109 |
+
|
| 110 |
+
return False
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
@functools.cache
|
| 114 |
+
def has_datacenter_blackwell_tma_device() -> bool:
|
| 115 |
+
import torch
|
| 116 |
+
|
| 117 |
+
if (
|
| 118 |
+
torch.cuda.is_available()
|
| 119 |
+
and torch.cuda.get_device_capability() >= (10, 0)
|
| 120 |
+
and torch.cuda.get_device_capability() < (11, 0)
|
| 121 |
+
and not torch.version.hip
|
| 122 |
+
):
|
| 123 |
+
return has_triton_tma_device() and has_triton_tensor_descriptor_host_tma()
|
| 124 |
+
|
| 125 |
+
return False
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
@functools.lru_cache(None)
|
| 129 |
+
def has_triton_stable_tma_api() -> bool:
|
| 130 |
+
if has_triton_package():
|
| 131 |
+
import torch
|
| 132 |
+
|
| 133 |
+
if (
|
| 134 |
+
torch.cuda.is_available()
|
| 135 |
+
and torch.cuda.get_device_capability() >= (9, 0)
|
| 136 |
+
and not torch.version.hip
|
| 137 |
+
) or torch.xpu.is_available():
|
| 138 |
+
try:
|
| 139 |
+
from triton.language import make_tensor_descriptor # noqa: F401
|
| 140 |
+
|
| 141 |
+
return True
|
| 142 |
+
except ImportError:
|
| 143 |
+
pass
|
| 144 |
+
return False
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
@functools.cache
|
| 148 |
+
def has_triton() -> bool:
|
| 149 |
+
if not has_triton_package():
|
| 150 |
+
return False
|
| 151 |
+
|
| 152 |
+
from torch._inductor.config import triton_disable_device_detection
|
| 153 |
+
|
| 154 |
+
if triton_disable_device_detection:
|
| 155 |
+
return False
|
| 156 |
+
|
| 157 |
+
from torch._dynamo.device_interface import get_interface_for_device
|
| 158 |
+
|
| 159 |
+
def cuda_extra_check(device_interface: Any) -> bool:
|
| 160 |
+
return device_interface.Worker.get_device_properties().major >= 7
|
| 161 |
+
|
| 162 |
+
def cpu_extra_check(device_interface: Any) -> bool:
|
| 163 |
+
import triton.backends
|
| 164 |
+
|
| 165 |
+
return "cpu" in triton.backends.backends
|
| 166 |
+
|
| 167 |
+
def _return_true(device_interface: Any) -> bool:
|
| 168 |
+
return True
|
| 169 |
+
|
| 170 |
+
triton_supported_devices = {
|
| 171 |
+
"cuda": cuda_extra_check,
|
| 172 |
+
"xpu": _return_true,
|
| 173 |
+
"cpu": cpu_extra_check,
|
| 174 |
+
"mtia": _return_true,
|
| 175 |
+
}
|
| 176 |
+
|
| 177 |
+
def is_device_compatible_with_triton() -> bool:
|
| 178 |
+
for device, extra_check in triton_supported_devices.items():
|
| 179 |
+
device_interface = get_interface_for_device(device)
|
| 180 |
+
if device_interface.is_available() and extra_check(device_interface):
|
| 181 |
+
return True
|
| 182 |
+
return False
|
| 183 |
+
|
| 184 |
+
return is_device_compatible_with_triton()
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
@functools.cache
|
| 188 |
+
def triton_backend() -> Any:
|
| 189 |
+
from triton.compiler.compiler import make_backend
|
| 190 |
+
from triton.runtime.driver import driver
|
| 191 |
+
|
| 192 |
+
target = driver.active.get_current_target()
|
| 193 |
+
return make_backend(target)
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
@functools.cache
|
| 197 |
+
def triton_hash_with_backend() -> str:
|
| 198 |
+
from torch._inductor.runtime.triton_compat import triton_key
|
| 199 |
+
|
| 200 |
+
backend = triton_backend()
|
| 201 |
+
key = f"{triton_key()}-{backend.hash()}"
|
| 202 |
+
|
| 203 |
+
# Hash is upper case so that it can't contain any Python keywords.
|
| 204 |
+
return hashlib.sha256(key.encode("utf-8")).hexdigest().upper()
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/_typing_utils.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Miscellaneous utilities to aid with typing."""
|
| 2 |
+
|
| 3 |
+
from typing import TypeVar
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
# Helper to turn Optional[T] into T when we know None either isn't
|
| 7 |
+
# possible or should trigger an exception.
|
| 8 |
+
T = TypeVar("T")
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def not_none(obj: T | None) -> T:
|
| 12 |
+
if obj is None:
|
| 13 |
+
raise TypeError("Invariant encountered: value was None when it should not be")
|
| 14 |
+
return obj
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/_zip.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import argparse
|
| 3 |
+
import glob
|
| 4 |
+
import os
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from zipfile import ZipFile
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
# Exclude some standard library modules to:
|
| 10 |
+
# 1. Slim down the final zipped file size
|
| 11 |
+
# 2. Remove functionality we don't want to support.
|
| 12 |
+
DENY_LIST = [
|
| 13 |
+
# Interface to unix databases
|
| 14 |
+
"dbm",
|
| 15 |
+
# ncurses bindings (terminal interfaces)
|
| 16 |
+
"curses",
|
| 17 |
+
# Tcl/Tk GUI
|
| 18 |
+
"tkinter",
|
| 19 |
+
"tkinter",
|
| 20 |
+
# Tests for the standard library
|
| 21 |
+
"test",
|
| 22 |
+
"tests",
|
| 23 |
+
"idle_test",
|
| 24 |
+
"__phello__.foo.py",
|
| 25 |
+
# importlib frozen modules. These are already baked into CPython.
|
| 26 |
+
"_bootstrap.py",
|
| 27 |
+
"_bootstrap_external.py",
|
| 28 |
+
]
|
| 29 |
+
|
| 30 |
+
strip_file_dir = ""
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def remove_prefix(text, prefix):
|
| 34 |
+
if text.startswith(prefix):
|
| 35 |
+
return text[len(prefix) :]
|
| 36 |
+
return text
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def write_to_zip(file_path, strip_file_path, zf, prepend_str="") -> None:
|
| 40 |
+
stripped_file_path = prepend_str + remove_prefix(file_path, strip_file_dir + "/")
|
| 41 |
+
path = Path(stripped_file_path)
|
| 42 |
+
if path.name in DENY_LIST:
|
| 43 |
+
return
|
| 44 |
+
zf.write(file_path, stripped_file_path)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def main() -> None:
|
| 48 |
+
global strip_file_dir
|
| 49 |
+
parser = argparse.ArgumentParser(description="Zip py source")
|
| 50 |
+
parser.add_argument("paths", nargs="*", help="Paths to zip.")
|
| 51 |
+
parser.add_argument(
|
| 52 |
+
"--install-dir", "--install_dir", help="Root directory for all output files"
|
| 53 |
+
)
|
| 54 |
+
parser.add_argument(
|
| 55 |
+
"--strip-dir",
|
| 56 |
+
"--strip_dir",
|
| 57 |
+
help="The absolute directory we want to remove from zip",
|
| 58 |
+
)
|
| 59 |
+
parser.add_argument(
|
| 60 |
+
"--prepend-str",
|
| 61 |
+
"--prepend_str",
|
| 62 |
+
help="A string to prepend onto all paths of a file in the zip",
|
| 63 |
+
default="",
|
| 64 |
+
)
|
| 65 |
+
parser.add_argument("--zip-name", "--zip_name", help="Output zip name")
|
| 66 |
+
|
| 67 |
+
args = parser.parse_args()
|
| 68 |
+
|
| 69 |
+
zip_file_name = args.install_dir + "/" + args.zip_name
|
| 70 |
+
strip_file_dir = args.strip_dir
|
| 71 |
+
prepend_str = args.prepend_str
|
| 72 |
+
with ZipFile(zip_file_name, mode="w") as zf:
|
| 73 |
+
for p in sorted(args.paths):
|
| 74 |
+
if os.path.isdir(p):
|
| 75 |
+
files = glob.glob(p + "/**/*.py", recursive=True)
|
| 76 |
+
for file_path in sorted(files):
|
| 77 |
+
# strip the absolute path
|
| 78 |
+
write_to_zip(
|
| 79 |
+
file_path, strip_file_dir + "/", zf, prepend_str=prepend_str
|
| 80 |
+
)
|
| 81 |
+
else:
|
| 82 |
+
write_to_zip(p, strip_file_dir + "/", zf, prepend_str=prepend_str)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
if __name__ == "__main__":
|
| 86 |
+
main() # pragma: no cover
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/backcompat/__init__.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from torch._C import (
|
| 3 |
+
_get_backcompat_broadcast_warn,
|
| 4 |
+
_get_backcompat_keepdim_warn,
|
| 5 |
+
_set_backcompat_broadcast_warn,
|
| 6 |
+
_set_backcompat_keepdim_warn,
|
| 7 |
+
)
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class Warning:
|
| 11 |
+
def __init__(self, setter, getter) -> None:
|
| 12 |
+
self.setter = setter
|
| 13 |
+
self.getter = getter
|
| 14 |
+
|
| 15 |
+
def set_enabled(self, value) -> None:
|
| 16 |
+
self.setter(value)
|
| 17 |
+
|
| 18 |
+
def get_enabled(self):
|
| 19 |
+
return self.getter()
|
| 20 |
+
|
| 21 |
+
enabled = property(get_enabled, set_enabled)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
broadcast_warning = Warning(
|
| 25 |
+
_set_backcompat_broadcast_warn, _get_backcompat_broadcast_warn
|
| 26 |
+
)
|
| 27 |
+
keepdim_warning = Warning(_set_backcompat_keepdim_warn, _get_backcompat_keepdim_warn)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/backend_registration.py
ADDED
|
@@ -0,0 +1,521 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
from torch._C import _get_privateuse1_backend_name, _rename_privateuse1_backend
|
| 5 |
+
from torch.overrides import handle_torch_function, has_torch_function_unary
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
__all__ = [
|
| 9 |
+
"rename_privateuse1_backend",
|
| 10 |
+
"generate_methods_for_privateuse1_backend",
|
| 11 |
+
]
|
| 12 |
+
|
| 13 |
+
# TODO: Should use `torch._C._get_privateuse1_backend_name()` to get
|
| 14 |
+
# renamed-backend name for `privateuse1`, but the func will cause an
|
| 15 |
+
# error with torch.jit.script, so we use the global variable named
|
| 16 |
+
# `_privateuse1_backend_name`.
|
| 17 |
+
_privateuse1_backend_name = "privateuseone"
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def rename_privateuse1_backend(backend_name: str) -> None:
|
| 21 |
+
r"""
|
| 22 |
+
Rename the privateuse1 backend device to make it more convenient to use as a device name within PyTorch APIs.
|
| 23 |
+
|
| 24 |
+
The steps are:
|
| 25 |
+
|
| 26 |
+
(1) (In C++) implement kernels for various torch operations, and register them
|
| 27 |
+
to the PrivateUse1 dispatch key.
|
| 28 |
+
(2) (In python) call torch.utils.rename_privateuse1_backend("foo")
|
| 29 |
+
|
| 30 |
+
You can now use "foo" as an ordinary device string in python.
|
| 31 |
+
|
| 32 |
+
Note: this API can only be called once per process. Attempting to change
|
| 33 |
+
the external backend after it's already been set will result in an error.
|
| 34 |
+
|
| 35 |
+
Note(AMP): If you want to support AMP on your device, you can register a custom backend module.
|
| 36 |
+
The backend must register a custom backend module with ``torch._register_device_module("foo", BackendModule)``.
|
| 37 |
+
BackendModule needs to have the following API's:
|
| 38 |
+
|
| 39 |
+
(1) ``get_amp_supported_dtype() -> List[torch.dtype]``
|
| 40 |
+
get the supported dtypes on your "foo" device in AMP, maybe the "foo" device supports one more dtype.
|
| 41 |
+
|
| 42 |
+
Note(random): If you want to support to set seed for your device, BackendModule needs to have the following API's:
|
| 43 |
+
|
| 44 |
+
(1) ``_is_in_bad_fork() -> bool``
|
| 45 |
+
Return ``True`` if now it is in bad_fork, else return ``False``.
|
| 46 |
+
|
| 47 |
+
(2) ``manual_seed_all(seed int) -> None``
|
| 48 |
+
Sets the seed for generating random numbers for your devices.
|
| 49 |
+
|
| 50 |
+
(3) ``device_count() -> int``
|
| 51 |
+
Returns the number of "foo"s available.
|
| 52 |
+
|
| 53 |
+
(4) ``get_rng_state(device: Union[int, str, torch.device] = 'foo') -> Tensor``
|
| 54 |
+
Returns a list of ByteTensor representing the random number states of all devices.
|
| 55 |
+
|
| 56 |
+
(5) ``set_rng_state(new_state: Tensor, device: Union[int, str, torch.device] = 'foo') -> None``
|
| 57 |
+
Sets the random number generator state of the specified "foo" device.
|
| 58 |
+
|
| 59 |
+
And there are some common funcs:
|
| 60 |
+
|
| 61 |
+
(1) ``is_available() -> bool``
|
| 62 |
+
Returns a bool indicating if "foo" is currently available.
|
| 63 |
+
|
| 64 |
+
(2) ``current_device() -> int``
|
| 65 |
+
Returns the index of a currently selected device.
|
| 66 |
+
|
| 67 |
+
For more details, see https://pytorch.org/tutorials/advanced/extend_dispatcher.html#get-a-dispatch-key-for-your-backend
|
| 68 |
+
For an existing example, see https://github.com/bdhirsh/pytorch_open_registration_example
|
| 69 |
+
|
| 70 |
+
Example::
|
| 71 |
+
|
| 72 |
+
>>> # xdoctest: +SKIP("failing")
|
| 73 |
+
>>> torch.utils.rename_privateuse1_backend("foo")
|
| 74 |
+
# This will work, assuming that you've implemented the right C++ kernels
|
| 75 |
+
# to implement torch.ones.
|
| 76 |
+
>>> a = torch.ones(2, device="foo")
|
| 77 |
+
|
| 78 |
+
"""
|
| 79 |
+
_rename_privateuse1_backend(backend_name)
|
| 80 |
+
global _privateuse1_backend_name
|
| 81 |
+
_privateuse1_backend_name = backend_name
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def _check_register_once(module, attr) -> None:
|
| 85 |
+
if hasattr(module, attr):
|
| 86 |
+
raise RuntimeError(
|
| 87 |
+
f"The custom device module of {module} has already been registered with {attr}"
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def _normalization_device(
|
| 92 |
+
custom_backend_name: str, device: int | str | torch.device | None = None
|
| 93 |
+
) -> int:
|
| 94 |
+
def _get_current_device_index():
|
| 95 |
+
_get_device_index = "current_device"
|
| 96 |
+
if hasattr(torch, custom_backend_name) and hasattr(
|
| 97 |
+
getattr(torch, custom_backend_name), _get_device_index
|
| 98 |
+
):
|
| 99 |
+
return getattr(getattr(torch, custom_backend_name), _get_device_index)()
|
| 100 |
+
else:
|
| 101 |
+
# The default device index is 0.
|
| 102 |
+
return 0
|
| 103 |
+
|
| 104 |
+
if device is None:
|
| 105 |
+
return _get_current_device_index()
|
| 106 |
+
# if isinstance(device, str), this means that the parameter passed in is in the string format "foo:0"
|
| 107 |
+
# convert str object to torch.device object, and then process it uniformly
|
| 108 |
+
elif isinstance(device, str):
|
| 109 |
+
device = torch.device(device)
|
| 110 |
+
|
| 111 |
+
# variable device can only be torch.device type or int type
|
| 112 |
+
if isinstance(device, torch.device):
|
| 113 |
+
if device.type != custom_backend_name:
|
| 114 |
+
raise RuntimeError(f"Invalid device, must be {custom_backend_name} device")
|
| 115 |
+
elif device.index is None:
|
| 116 |
+
device_idx = _get_current_device_index()
|
| 117 |
+
else:
|
| 118 |
+
device_idx = device.index
|
| 119 |
+
# if isinstance(device, int), we can take the index number directly
|
| 120 |
+
else:
|
| 121 |
+
device_idx = device
|
| 122 |
+
return device_idx
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def _generate_tensor_methods_for_privateuse1_backend(custom_backend_name: str) -> None:
|
| 126 |
+
@property # type: ignore[misc]
|
| 127 |
+
def wrap_tensor_backend(self: torch.Tensor) -> bool:
|
| 128 |
+
if has_torch_function_unary(self):
|
| 129 |
+
# TODO mypy doesn't support @property, see: https://github.com/python/mypy/issues/6185
|
| 130 |
+
return handle_torch_function(wrap_tensor_backend.__get__, (self,), self) # type: ignore[attr-defined]
|
| 131 |
+
return self.device.type == custom_backend_name
|
| 132 |
+
|
| 133 |
+
_check_register_once(torch.Tensor, f"is_{custom_backend_name}")
|
| 134 |
+
wrap_tensor_backend.fget.__name__ = f"is_{custom_backend_name}" # type: ignore[attr-defined]
|
| 135 |
+
setattr(torch.Tensor, f"is_{custom_backend_name}", wrap_tensor_backend)
|
| 136 |
+
|
| 137 |
+
def wrap_tensor_to(
|
| 138 |
+
self: torch.Tensor,
|
| 139 |
+
device: int | torch.device | None = None,
|
| 140 |
+
non_blocking=False,
|
| 141 |
+
**kwargs,
|
| 142 |
+
) -> torch.Tensor:
|
| 143 |
+
r"""Perform Tensor device conversion. Call the to operator implementation.
|
| 144 |
+
|
| 145 |
+
.. note::
|
| 146 |
+
If the ``self`` Tensor already
|
| 147 |
+
has the correct :class:`torch.device`, then ``self`` is returned.
|
| 148 |
+
Otherwise, the returned tensor is a copy of ``self`` with the desired :class:`torch.device`.
|
| 149 |
+
|
| 150 |
+
Args:
|
| 151 |
+
device (int, optional): if specified, all parameters will be copied to that device
|
| 152 |
+
non_blocking (bool): If ``True`` and the source is in pinned memory,
|
| 153 |
+
the copy will be asynchronous with respect to the host. Otherwise,
|
| 154 |
+
the argument has no effect.
|
| 155 |
+
**kwargs (dict): For compatibility, may contain the key ``memory_format`` argument.
|
| 156 |
+
"""
|
| 157 |
+
if has_torch_function_unary(self):
|
| 158 |
+
return handle_torch_function(
|
| 159 |
+
wrap_tensor_to,
|
| 160 |
+
(self,),
|
| 161 |
+
self,
|
| 162 |
+
device=device,
|
| 163 |
+
non_blocking=False,
|
| 164 |
+
**kwargs,
|
| 165 |
+
)
|
| 166 |
+
device_idx = _normalization_device(custom_backend_name, device)
|
| 167 |
+
return self.to(
|
| 168 |
+
device=torch.device(f"{custom_backend_name}:{device_idx}"),
|
| 169 |
+
non_blocking=non_blocking,
|
| 170 |
+
**kwargs,
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
_check_register_once(torch.Tensor, custom_backend_name)
|
| 174 |
+
wrap_tensor_to.__name__ = custom_backend_name
|
| 175 |
+
setattr(torch.Tensor, custom_backend_name, wrap_tensor_to)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def _generate_module_methods_for_privateuse1_backend(custom_backend_name: str) -> None:
|
| 179 |
+
# Generate Module attributes and methods depends on Tensor methods,
|
| 180 |
+
# so we need to check whether Tensor methods is already registered.
|
| 181 |
+
if not hasattr(torch.Tensor, custom_backend_name):
|
| 182 |
+
raise RuntimeError(
|
| 183 |
+
f"Can not automatically generate {custom_backend_name}() method for torch.nn.Module."
|
| 184 |
+
f"Because torch.Tensor doesn't has the method {custom_backend_name}()."
|
| 185 |
+
f"For this error, you can try setting for_tensor=True."
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
def wrap_module_to(
|
| 189 |
+
self: torch.nn.modules.module.T,
|
| 190 |
+
device: int | torch.device | None = None,
|
| 191 |
+
) -> torch.nn.modules.module.T:
|
| 192 |
+
r"""Move all model parameters and buffers to the custom device.
|
| 193 |
+
|
| 194 |
+
This also makes associated parameters and buffers different objects. So
|
| 195 |
+
it should be called before constructing optimizer if the module will
|
| 196 |
+
live on device while being optimized.
|
| 197 |
+
|
| 198 |
+
.. note::
|
| 199 |
+
This method modifies the module in-place.
|
| 200 |
+
|
| 201 |
+
Args:
|
| 202 |
+
device (int, optional): if specified, all parameters will be copied to that device
|
| 203 |
+
"""
|
| 204 |
+
# pyrefly: ignore [missing-attribute]
|
| 205 |
+
return self._apply(lambda t: getattr(t, custom_backend_name)(device))
|
| 206 |
+
|
| 207 |
+
_check_register_once(torch.nn.Module, custom_backend_name)
|
| 208 |
+
setattr(torch.nn.Module, custom_backend_name, wrap_module_to)
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def _generate_packed_sequence_methods_for_privateuse1_backend(
|
| 212 |
+
custom_backend_name: str,
|
| 213 |
+
) -> None:
|
| 214 |
+
# Generate PackedSequence Module attributes and methods depends on Tensor methods,
|
| 215 |
+
# so we need to check whether Tensor methods is already registered.
|
| 216 |
+
if not hasattr(torch.Tensor, f"is_{custom_backend_name}") or not hasattr(
|
| 217 |
+
torch.Tensor, custom_backend_name
|
| 218 |
+
):
|
| 219 |
+
raise RuntimeError(
|
| 220 |
+
f"Can not automatically generate is_{custom_backend_name}() or "
|
| 221 |
+
f"{custom_backend_name}() method for torch.nn.utils.rnn.PackedSequence."
|
| 222 |
+
f"Because torch.Tensor doesn't has the method is_{custom_backend_name}()"
|
| 223 |
+
f"or {custom_backend_name}()."
|
| 224 |
+
f"For this error, you can try setting for_tensor=True."
|
| 225 |
+
)
|
| 226 |
+
|
| 227 |
+
@property # type: ignore[misc]
|
| 228 |
+
def wrap_tensor_backend(self: torch.nn.utils.rnn.PackedSequence) -> bool:
|
| 229 |
+
return self.data.device.type == custom_backend_name
|
| 230 |
+
|
| 231 |
+
_check_register_once(torch.nn.utils.rnn.PackedSequence, f"is_{custom_backend_name}")
|
| 232 |
+
setattr(
|
| 233 |
+
torch.nn.utils.rnn.PackedSequence,
|
| 234 |
+
f"is_{custom_backend_name}",
|
| 235 |
+
wrap_tensor_backend,
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
def wrap_module_to(
|
| 239 |
+
self: torch.nn.utils.rnn.PackedSequence, *args, **kwargs
|
| 240 |
+
) -> torch.nn.utils.rnn.PackedSequence:
|
| 241 |
+
r"""Move all model parameters and buffers to the custom device.
|
| 242 |
+
|
| 243 |
+
This also makes associated parameters and buffers different objects. So
|
| 244 |
+
it should be called before constructing optimizer if the module will
|
| 245 |
+
live on device while being optimized.
|
| 246 |
+
|
| 247 |
+
.. note::
|
| 248 |
+
This method modifies the module in-place.
|
| 249 |
+
|
| 250 |
+
Args:
|
| 251 |
+
device (int, optional): if specified, all parameters will be copied to that device
|
| 252 |
+
"""
|
| 253 |
+
ex = torch.tensor((), dtype=self.data.dtype, device=self.data.device).to(
|
| 254 |
+
# pyrefly: ignore [not-iterable]
|
| 255 |
+
*args,
|
| 256 |
+
**kwargs,
|
| 257 |
+
)
|
| 258 |
+
if ex.device.type == custom_backend_name:
|
| 259 |
+
# pyrefly: ignore [not-iterable]
|
| 260 |
+
return self.to(*args, **kwargs)
|
| 261 |
+
kwargs.update({"device": custom_backend_name})
|
| 262 |
+
# pyrefly: ignore [not-iterable]
|
| 263 |
+
return self.to(*args, **kwargs)
|
| 264 |
+
|
| 265 |
+
_check_register_once(torch.nn.utils.rnn.PackedSequence, custom_backend_name)
|
| 266 |
+
setattr(torch.nn.utils.rnn.PackedSequence, custom_backend_name, wrap_module_to)
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
def _generate_storage_methods_for_privateuse1_backend(
|
| 270 |
+
custom_backend_name: str, unsupported_dtype: list[torch.dtype] | None = None
|
| 271 |
+
) -> None:
|
| 272 |
+
# Attribute is registered in the _StorageBase class
|
| 273 |
+
# and UntypedStorage obtains through inheritance.
|
| 274 |
+
@property # type: ignore[misc]
|
| 275 |
+
def wrap_storage_backend(self: torch.storage._StorageBase) -> bool:
|
| 276 |
+
r"""Return the internal :class:`torch.UntypedStorage`."""
|
| 277 |
+
return self.device.type == custom_backend_name
|
| 278 |
+
|
| 279 |
+
_check_register_once(torch.storage._StorageBase, f"is_{custom_backend_name}")
|
| 280 |
+
setattr(
|
| 281 |
+
torch.storage._StorageBase, f"is_{custom_backend_name}", wrap_storage_backend
|
| 282 |
+
)
|
| 283 |
+
|
| 284 |
+
def wrap_storage_to(self, device=None, non_blocking=False):
|
| 285 |
+
r"""Return a copy of this object in custom device memory.
|
| 286 |
+
|
| 287 |
+
If this object is already in device memory and on the correct device, then
|
| 288 |
+
no copy is performed and the original object is returned.
|
| 289 |
+
|
| 290 |
+
Args:
|
| 291 |
+
device (int): The destination device id. Defaults to the current device.
|
| 292 |
+
non_blocking (bool): If ``True`` and the source is in pinned memory,
|
| 293 |
+
the copy will be asynchronous with respect to the host. Otherwise,
|
| 294 |
+
the argument has no effect.
|
| 295 |
+
"""
|
| 296 |
+
# There should be a judgment related to storage device and a judgment related to storage type,
|
| 297 |
+
# but it depends on the extended function, so this part is temporarily omitted in the automatic generation.
|
| 298 |
+
device_idx = _normalization_device(custom_backend_name, device)
|
| 299 |
+
|
| 300 |
+
if getattr(self, f"is_{custom_backend_name}"):
|
| 301 |
+
# storage has already on expected device.
|
| 302 |
+
if self.get_device() == device_idx:
|
| 303 |
+
return self
|
| 304 |
+
# For sparse storage, custom need to extend the implementation by themselves.
|
| 305 |
+
if self.is_sparse:
|
| 306 |
+
raise RuntimeError(
|
| 307 |
+
f"Can not support a sparse storage move to {custom_backend_name} backend"
|
| 308 |
+
)
|
| 309 |
+
# create untyped_storage and copy data
|
| 310 |
+
untyped_storage = torch.UntypedStorage(
|
| 311 |
+
self.size(), device=torch.device(f"{custom_backend_name}:{device_idx}")
|
| 312 |
+
)
|
| 313 |
+
untyped_storage.copy_(self, non_blocking)
|
| 314 |
+
return untyped_storage
|
| 315 |
+
|
| 316 |
+
_check_register_once(torch.storage._StorageBase, custom_backend_name)
|
| 317 |
+
setattr(torch.storage._StorageBase, custom_backend_name, wrap_storage_to)
|
| 318 |
+
|
| 319 |
+
# Register the corresponding attribute for the TypedStorage class.
|
| 320 |
+
# When the TypedStorage class is removed, the registration is also removed.
|
| 321 |
+
|
| 322 |
+
@property # type: ignore[misc]
|
| 323 |
+
def wrap_typed_storage_backend(self: torch.storage.TypedStorage) -> bool:
|
| 324 |
+
torch.storage._warn_typed_storage_removal()
|
| 325 |
+
return self._untyped_storage.device.type == custom_backend_name
|
| 326 |
+
|
| 327 |
+
_check_register_once(torch.TypedStorage, f"is_{custom_backend_name}")
|
| 328 |
+
setattr(
|
| 329 |
+
torch.storage.TypedStorage,
|
| 330 |
+
f"is_{custom_backend_name}",
|
| 331 |
+
wrap_typed_storage_backend,
|
| 332 |
+
)
|
| 333 |
+
|
| 334 |
+
def wrap_typed_storage_to(
|
| 335 |
+
self: torch.storage.TypedStorage, device=None, non_blocking=False, **kwargs
|
| 336 |
+
) -> torch.storage.TypedStorage:
|
| 337 |
+
torch.storage._warn_typed_storage_removal()
|
| 338 |
+
if unsupported_dtype and self.dtype in unsupported_dtype:
|
| 339 |
+
raise RuntimeError(
|
| 340 |
+
f"Cannot create {custom_backend_name} storage "
|
| 341 |
+
f"as {self.dtype} dtype is not supported by this backend"
|
| 342 |
+
)
|
| 343 |
+
custom_backend_storage: torch.UntypedStorage = getattr(
|
| 344 |
+
self._untyped_storage, custom_backend_name
|
| 345 |
+
)(device, non_blocking, **kwargs)
|
| 346 |
+
return self._new_wrapped_storage(custom_backend_storage)
|
| 347 |
+
|
| 348 |
+
_check_register_once(torch.TypedStorage, custom_backend_name)
|
| 349 |
+
setattr(torch.TypedStorage, custom_backend_name, wrap_typed_storage_to)
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
def generate_methods_for_privateuse1_backend(
|
| 353 |
+
for_tensor: bool = True,
|
| 354 |
+
for_module: bool = True,
|
| 355 |
+
for_packed_sequence: bool = True,
|
| 356 |
+
for_storage: bool = False,
|
| 357 |
+
unsupported_dtype: list[torch.dtype] | None = None,
|
| 358 |
+
) -> None:
|
| 359 |
+
r"""
|
| 360 |
+
Automatically generate attributes and methods for the custom backend after rename privateuse1 backend.
|
| 361 |
+
|
| 362 |
+
In the default scenario, storage-related methods will not be generated automatically.
|
| 363 |
+
|
| 364 |
+
When you implement kernels for various torch operations, and register them to the PrivateUse1 dispatch key.
|
| 365 |
+
And call the function torch.rename_privateuse1_backend("foo") to rename your backend name.
|
| 366 |
+
At this point, you can easily register specific methods and attributes by calling this function.
|
| 367 |
+
Just like torch.Tensor.foo(), torch.Tensor.is_foo, torch.Storage.foo(), torch.Storage.is_foo.
|
| 368 |
+
|
| 369 |
+
Note: We recommend you use generic functions (check devices are equal or to(device=)).
|
| 370 |
+
We provide these methods for convenience only and they will be "monkey patched" onto the objects
|
| 371 |
+
and so will not be properly typed. For Storage methods generate, if you need to support sparse data storage,
|
| 372 |
+
you need to extend the implementation yourself.
|
| 373 |
+
|
| 374 |
+
Args:
|
| 375 |
+
for_tensor (bool): whether register related methods for torch.Tensor class.
|
| 376 |
+
for_module (bool): whether register related methods for torch.nn.Module class.
|
| 377 |
+
for_storage (bool): whether register related methods for torch.Storage class.
|
| 378 |
+
unsupported_dtype (List[torch.dtype]): takes effect only when the storage method needs to be generated,
|
| 379 |
+
indicating that the storage does not support the torch.dtype type.
|
| 380 |
+
|
| 381 |
+
Example::
|
| 382 |
+
|
| 383 |
+
>>> # xdoctest: +SKIP("failing")
|
| 384 |
+
>>> torch.utils.rename_privateuse1_backend("foo")
|
| 385 |
+
>>> torch.utils.generate_methods_for_privateuse1_backend()
|
| 386 |
+
# Then automatically generate backend-related attributes and methods.
|
| 387 |
+
>>> a = torch.tensor(2).foo()
|
| 388 |
+
>>> a.is_foo
|
| 389 |
+
>>> hasattr(torch.nn.Module, 'foo')
|
| 390 |
+
"""
|
| 391 |
+
custom_backend_name = _get_privateuse1_backend_name()
|
| 392 |
+
|
| 393 |
+
if for_tensor:
|
| 394 |
+
_generate_tensor_methods_for_privateuse1_backend(custom_backend_name)
|
| 395 |
+
|
| 396 |
+
if for_module:
|
| 397 |
+
_generate_module_methods_for_privateuse1_backend(custom_backend_name)
|
| 398 |
+
|
| 399 |
+
if for_storage:
|
| 400 |
+
_generate_storage_methods_for_privateuse1_backend(
|
| 401 |
+
custom_backend_name, unsupported_dtype
|
| 402 |
+
)
|
| 403 |
+
|
| 404 |
+
if for_packed_sequence:
|
| 405 |
+
_generate_packed_sequence_methods_for_privateuse1_backend(custom_backend_name)
|
| 406 |
+
|
| 407 |
+
|
| 408 |
+
def _get_custom_mod_func(func_name: str):
|
| 409 |
+
r"""
|
| 410 |
+
Return the func named `func_name` defined in custom device module. If not defined,
|
| 411 |
+
return `None`. And the func is registered with `torch.utils.rename_privateuse1_backend('foo')`
|
| 412 |
+
and `torch._register_device_module('foo', BackendModule)`.
|
| 413 |
+
If the custom device module or the func is not defined, it will give warning or error message.
|
| 414 |
+
Args:
|
| 415 |
+
func_name (str): return the callable func named func_name defined in custom device module.
|
| 416 |
+
Example::
|
| 417 |
+
class DummyfooModule:
|
| 418 |
+
@staticmethod
|
| 419 |
+
def is_available():
|
| 420 |
+
return True
|
| 421 |
+
@staticmethod
|
| 422 |
+
def func_name(*args, **kwargs):
|
| 423 |
+
....
|
| 424 |
+
torch.utils.rename_privateuse1_backend("foo")
|
| 425 |
+
torch._register_device_module("foo", DummyfooModule)
|
| 426 |
+
foo_is_available_func = torch.utils.backend_registration._get_custom_mod_func("is_available")
|
| 427 |
+
if foo_is_available_func:
|
| 428 |
+
foo_is_available = foo_is_available_func()
|
| 429 |
+
func_ = torch.utils.backend_registration._get_custom_mod_func("func_name")
|
| 430 |
+
if func_:
|
| 431 |
+
result = func_(*args, **kwargs)
|
| 432 |
+
Attention: This function is not meant to be used directly by users, which is why
|
| 433 |
+
it is marked as private. It is a convenience function for backend implementers to
|
| 434 |
+
more easily call the hooks into their backend extensions.
|
| 435 |
+
"""
|
| 436 |
+
if not isinstance(func_name, str):
|
| 437 |
+
raise AssertionError(f"func_name must be `str`, but got `{type(func_name)}`.")
|
| 438 |
+
backend_name = _get_privateuse1_backend_name()
|
| 439 |
+
custom_device_mod = getattr(torch, backend_name, None)
|
| 440 |
+
function = getattr(custom_device_mod, func_name, None)
|
| 441 |
+
if custom_device_mod is None or function is None:
|
| 442 |
+
message = f"Try to call torch.{backend_name}.{func_name}. The backend must register a custom backend "
|
| 443 |
+
message += f"module with `torch._register_device_module('{backend_name}', BackendModule)`. And "
|
| 444 |
+
message += f"BackendModule needs to have the following API's:\n `{func_name}(*args, **kwargs)`. \n"
|
| 445 |
+
raise RuntimeError(message)
|
| 446 |
+
return function
|
| 447 |
+
|
| 448 |
+
|
| 449 |
+
class _DummyBackendModule:
|
| 450 |
+
def is_initialized(self) -> bool:
|
| 451 |
+
return True
|
| 452 |
+
|
| 453 |
+
def is_available(self) -> bool:
|
| 454 |
+
return True
|
| 455 |
+
|
| 456 |
+
def current_device(self) -> int:
|
| 457 |
+
return 0
|
| 458 |
+
|
| 459 |
+
def _is_in_bad_fork(self) -> bool:
|
| 460 |
+
return False
|
| 461 |
+
|
| 462 |
+
def manual_seed_all(self, seed: int) -> None:
|
| 463 |
+
pass
|
| 464 |
+
|
| 465 |
+
def device_count(self) -> int:
|
| 466 |
+
return 1
|
| 467 |
+
|
| 468 |
+
|
| 469 |
+
class _DummyPrivateUse1Hook(torch._C._acc.PrivateUse1Hooks):
|
| 470 |
+
def is_available(self) -> bool:
|
| 471 |
+
return True
|
| 472 |
+
|
| 473 |
+
def has_primary_context(self, dev_id) -> bool:
|
| 474 |
+
return True
|
| 475 |
+
|
| 476 |
+
def is_built(self) -> bool:
|
| 477 |
+
return True
|
| 478 |
+
|
| 479 |
+
|
| 480 |
+
class _DummyDeviceGuard(torch._C._acc.DeviceGuard):
|
| 481 |
+
def type_(self):
|
| 482 |
+
return torch._C._autograd.DeviceType.PrivateUse1
|
| 483 |
+
|
| 484 |
+
|
| 485 |
+
def _setup_privateuseone_for_python_backend(
|
| 486 |
+
rename=None, backend_module=None, hook=None, device_guard=None
|
| 487 |
+
) -> None:
|
| 488 |
+
"""This function will prepare the PrivateUse1 dispatch key to be used as a python backend.
|
| 489 |
+
|
| 490 |
+
WARNING: this API is experimental and might change without notice.
|
| 491 |
+
|
| 492 |
+
Formally, this registers things that Pytorch expects a registered backend
|
| 493 |
+
in C++ to have: including device guards, hooks, and backend modules and what not.
|
| 494 |
+
|
| 495 |
+
after this call, one can use `torch.library` to write Ops for this dispatch key
|
| 496 |
+
and expect it to behave like a backend registered in C++.
|
| 497 |
+
|
| 498 |
+
See the unit test at test/test_privateuseone_python_backend.py for more details.
|
| 499 |
+
|
| 500 |
+
Args:
|
| 501 |
+
rename: str | None, if passed in, we will rename privateuseone backend to
|
| 502 |
+
the name given.
|
| 503 |
+
backend_module: object | None, if passed in None, we will use DummyBackendModule
|
| 504 |
+
hook: object | None, if passed in None, we will use DummyPrivateUse1Hook
|
| 505 |
+
device_guard: object | None, if passed in None, we will use DummyDeviceGuard
|
| 506 |
+
"""
|
| 507 |
+
# NOTE: the ordering of which these functions are called is important.
|
| 508 |
+
if rename is not None:
|
| 509 |
+
torch.utils.rename_privateuse1_backend(rename)
|
| 510 |
+
else:
|
| 511 |
+
rename = "privateuseone"
|
| 512 |
+
torch.utils.generate_methods_for_privateuse1_backend()
|
| 513 |
+
if backend_module is None:
|
| 514 |
+
backend_module = _DummyBackendModule()
|
| 515 |
+
if hook is None:
|
| 516 |
+
hook = _DummyPrivateUse1Hook()
|
| 517 |
+
if device_guard is None:
|
| 518 |
+
device_guard = _DummyDeviceGuard()
|
| 519 |
+
torch._register_device_module(rename, backend_module)
|
| 520 |
+
torch._C._acc.register_python_privateuseone_hook(hook)
|
| 521 |
+
torch._C._acc.register_python_privateuseone_device_guard(device_guard)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/benchmark/__init__.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from torch.utils.benchmark.utils.common import * # noqa: F403
|
| 2 |
+
from torch.utils.benchmark.utils.timer import * # noqa: F403
|
| 3 |
+
from torch.utils.benchmark.utils.compare import * # noqa: F403
|
| 4 |
+
from torch.utils.benchmark.utils.fuzzer import * # noqa: F403
|
| 5 |
+
from torch.utils.benchmark.utils.valgrind_wrapper.timer_interface import * # noqa: F403
|
| 6 |
+
from torch.utils.benchmark.utils.sparse_fuzzer import * # noqa: F403
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/benchmark/examples/__init__.py
ADDED
|
File without changes
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/benchmark/examples/compare.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
"""Example of Timer and Compare APIs:
|
| 3 |
+
|
| 4 |
+
$ python -m examples.compare
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import pickle
|
| 8 |
+
import sys
|
| 9 |
+
import time
|
| 10 |
+
|
| 11 |
+
import torch
|
| 12 |
+
|
| 13 |
+
import torch.utils.benchmark as benchmark_utils
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class FauxTorch:
|
| 17 |
+
"""Emulate different versions of pytorch.
|
| 18 |
+
|
| 19 |
+
In normal circumstances this would be done with multiple processes
|
| 20 |
+
writing serialized measurements, but this simplifies that model to
|
| 21 |
+
make the example clearer.
|
| 22 |
+
"""
|
| 23 |
+
def __init__(self, real_torch, extra_ns_per_element) -> None:
|
| 24 |
+
self._real_torch = real_torch
|
| 25 |
+
self._extra_ns_per_element = extra_ns_per_element
|
| 26 |
+
|
| 27 |
+
def extra_overhead(self, result):
|
| 28 |
+
# time.sleep has a ~65 us overhead, so only fake a
|
| 29 |
+
# per-element overhead if numel is large enough.
|
| 30 |
+
numel = int(result.numel())
|
| 31 |
+
if numel > 5000:
|
| 32 |
+
time.sleep(numel * self._extra_ns_per_element * 1e-9)
|
| 33 |
+
return result
|
| 34 |
+
|
| 35 |
+
def add(self, *args, **kwargs):
|
| 36 |
+
return self.extra_overhead(self._real_torch.add(*args, **kwargs))
|
| 37 |
+
|
| 38 |
+
def mul(self, *args, **kwargs):
|
| 39 |
+
return self.extra_overhead(self._real_torch.mul(*args, **kwargs))
|
| 40 |
+
|
| 41 |
+
def cat(self, *args, **kwargs):
|
| 42 |
+
return self.extra_overhead(self._real_torch.cat(*args, **kwargs))
|
| 43 |
+
|
| 44 |
+
def matmul(self, *args, **kwargs):
|
| 45 |
+
return self.extra_overhead(self._real_torch.matmul(*args, **kwargs))
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def main() -> None:
|
| 49 |
+
tasks = [
|
| 50 |
+
("add", "add", "torch.add(x, y)"),
|
| 51 |
+
("add", "add (extra +0)", "torch.add(x, y + zero)"),
|
| 52 |
+
]
|
| 53 |
+
|
| 54 |
+
serialized_results = []
|
| 55 |
+
repeats = 2
|
| 56 |
+
timers = [
|
| 57 |
+
benchmark_utils.Timer(
|
| 58 |
+
stmt=stmt,
|
| 59 |
+
globals={
|
| 60 |
+
"torch": torch if branch == "master" else FauxTorch(torch, overhead_ns),
|
| 61 |
+
"x": torch.ones((size, 4)),
|
| 62 |
+
"y": torch.ones((1, 4)),
|
| 63 |
+
"zero": torch.zeros(()),
|
| 64 |
+
},
|
| 65 |
+
label=label,
|
| 66 |
+
sub_label=sub_label,
|
| 67 |
+
description=f"size: {size}",
|
| 68 |
+
env=branch,
|
| 69 |
+
num_threads=num_threads,
|
| 70 |
+
)
|
| 71 |
+
for branch, overhead_ns in [("master", None), ("my_branch", 1), ("severe_regression", 5)]
|
| 72 |
+
for label, sub_label, stmt in tasks
|
| 73 |
+
for size in [1, 10, 100, 1000, 10000, 50000]
|
| 74 |
+
for num_threads in [1, 4]
|
| 75 |
+
]
|
| 76 |
+
|
| 77 |
+
for i, timer in enumerate(timers * repeats):
|
| 78 |
+
serialized_results.append(pickle.dumps(
|
| 79 |
+
timer.blocked_autorange(min_run_time=0.05)
|
| 80 |
+
))
|
| 81 |
+
print(f"\r{i + 1} / {len(timers) * repeats}", end="")
|
| 82 |
+
sys.stdout.flush()
|
| 83 |
+
print()
|
| 84 |
+
|
| 85 |
+
comparison = benchmark_utils.Compare([
|
| 86 |
+
pickle.loads(i) for i in serialized_results
|
| 87 |
+
])
|
| 88 |
+
|
| 89 |
+
print("== Unformatted " + "=" * 80 + "\n" + "/" * 95 + "\n")
|
| 90 |
+
comparison.print()
|
| 91 |
+
|
| 92 |
+
print("== Formatted " + "=" * 80 + "\n" + "/" * 93 + "\n")
|
| 93 |
+
comparison.trim_significant_figures()
|
| 94 |
+
comparison.colorize()
|
| 95 |
+
comparison.print()
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
if __name__ == "__main__":
|
| 99 |
+
main()
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/benchmark/examples/fuzzer.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
"""Example of the Timer and Fuzzer APIs:
|
| 3 |
+
|
| 4 |
+
$ python -m examples.fuzzer
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import sys
|
| 8 |
+
|
| 9 |
+
import torch.utils.benchmark as benchmark_utils
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def main() -> None:
|
| 13 |
+
add_fuzzer = benchmark_utils.Fuzzer(
|
| 14 |
+
parameters=[
|
| 15 |
+
[
|
| 16 |
+
benchmark_utils.FuzzedParameter(
|
| 17 |
+
name=f"k{i}",
|
| 18 |
+
minval=16,
|
| 19 |
+
maxval=16 * 1024,
|
| 20 |
+
distribution="loguniform",
|
| 21 |
+
) for i in range(3)
|
| 22 |
+
],
|
| 23 |
+
benchmark_utils.FuzzedParameter(
|
| 24 |
+
name="d",
|
| 25 |
+
distribution={2: 0.6, 3: 0.4},
|
| 26 |
+
),
|
| 27 |
+
],
|
| 28 |
+
tensors=[
|
| 29 |
+
[
|
| 30 |
+
benchmark_utils.FuzzedTensor(
|
| 31 |
+
name=name,
|
| 32 |
+
size=("k0", "k1", "k2"),
|
| 33 |
+
dim_parameter="d",
|
| 34 |
+
probability_contiguous=0.75,
|
| 35 |
+
min_elements=64 * 1024,
|
| 36 |
+
max_elements=128 * 1024,
|
| 37 |
+
) for name in ("x", "y")
|
| 38 |
+
],
|
| 39 |
+
],
|
| 40 |
+
seed=0,
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
n = 250
|
| 44 |
+
measurements = []
|
| 45 |
+
for i, (tensors, tensor_properties, _) in enumerate(add_fuzzer.take(n=n)):
|
| 46 |
+
x, x_order = tensors["x"], str(tensor_properties["x"]["order"])
|
| 47 |
+
y, y_order = tensors["y"], str(tensor_properties["y"]["order"])
|
| 48 |
+
shape = ", ".join(tuple(f'{i:>4}' for i in x.shape))
|
| 49 |
+
|
| 50 |
+
description = "".join([
|
| 51 |
+
f"{x.numel():>7} | {shape:<16} | ",
|
| 52 |
+
f"{'contiguous' if x.is_contiguous() else x_order:<12} | ",
|
| 53 |
+
f"{'contiguous' if y.is_contiguous() else y_order:<12} | ",
|
| 54 |
+
])
|
| 55 |
+
|
| 56 |
+
timer = benchmark_utils.Timer(
|
| 57 |
+
stmt="x + y",
|
| 58 |
+
globals=tensors,
|
| 59 |
+
description=description,
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
measurements.append(timer.blocked_autorange(min_run_time=0.1))
|
| 63 |
+
measurements[-1].metadata = {"numel": x.numel()}
|
| 64 |
+
print(f"\r{i + 1} / {n}", end="")
|
| 65 |
+
sys.stdout.flush()
|
| 66 |
+
print()
|
| 67 |
+
|
| 68 |
+
# More string munging to make pretty output.
|
| 69 |
+
print(f"Average attempts per valid config: {1. / (1. - add_fuzzer.rejection_rate):.1f}")
|
| 70 |
+
|
| 71 |
+
def time_fn(m):
|
| 72 |
+
return m.median / m.metadata["numel"]
|
| 73 |
+
measurements.sort(key=time_fn)
|
| 74 |
+
|
| 75 |
+
template = f"{{:>6}}{' ' * 19}Size Shape{' ' * 13}X order Y order\n{'-' * 80}"
|
| 76 |
+
print(template.format("Best:"))
|
| 77 |
+
for m in measurements[:15]:
|
| 78 |
+
print(f"{time_fn(m) * 1e9:>4.1f} ns / element {m.description}")
|
| 79 |
+
|
| 80 |
+
print("\n" + template.format("Worst:"))
|
| 81 |
+
for m in measurements[-15:]:
|
| 82 |
+
print(f"{time_fn(m) * 1e9:>4.1f} ns / element {m.description}")
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
if __name__ == "__main__":
|
| 86 |
+
main()
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/benchmark/examples/op_benchmark.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
"""Example use of Timer and op fuzzers to measure kernel performance.
|
| 3 |
+
|
| 4 |
+
$ python -m examples.op_benchmark
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import numpy as np
|
| 8 |
+
import torch
|
| 9 |
+
|
| 10 |
+
from torch.utils.benchmark import Timer
|
| 11 |
+
from torch.utils.benchmark.op_fuzzers.binary import BinaryOpFuzzer
|
| 12 |
+
from torch.utils.benchmark.op_fuzzers.unary import UnaryOpFuzzer
|
| 13 |
+
import operator
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
_MEASURE_TIME = 1.0
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def assert_dicts_equal(dict_0, dict_1) -> None:
|
| 20 |
+
"""Builtin dict comparison will not compare numpy arrays.
|
| 21 |
+
e.g.
|
| 22 |
+
x = {"a": np.ones((2, 1))}
|
| 23 |
+
x == x # Raises ValueError
|
| 24 |
+
"""
|
| 25 |
+
if set(dict_0.keys()) != set(dict_0.keys()):
|
| 26 |
+
raise AssertionError("dicts must have the same keys")
|
| 27 |
+
if all(np.all(v != dict_1[k]) for k, v in dict_0.items() if k != "dtype"):
|
| 28 |
+
raise AssertionError("dict values differ for keys other than 'dtype'")
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def run(n, stmt, fuzzer_cls) -> None:
|
| 32 |
+
float_iter = fuzzer_cls(seed=0, dtype=torch.float32).take(n)
|
| 33 |
+
int_iter = fuzzer_cls(seed=0, dtype=torch.int32).take(n)
|
| 34 |
+
raw_results = []
|
| 35 |
+
for i, (float_values, int_values) in enumerate(zip(float_iter, int_iter, strict=True)):
|
| 36 |
+
float_tensors, float_tensor_params, float_params = float_values
|
| 37 |
+
int_tensors, int_tensor_params, int_params = int_values
|
| 38 |
+
|
| 39 |
+
# This benchmark assumes that the two fuzzers generate identically
|
| 40 |
+
# sized and strided Tensors, since the same seed is used.
|
| 41 |
+
assert_dicts_equal(float_params, int_params)
|
| 42 |
+
assert_dicts_equal(float_tensor_params["x"], int_tensor_params["x"])
|
| 43 |
+
|
| 44 |
+
float_measurement, int_measurement = (
|
| 45 |
+
Timer(
|
| 46 |
+
stmt,
|
| 47 |
+
globals=tensors,
|
| 48 |
+
).blocked_autorange(min_run_time=_MEASURE_TIME)
|
| 49 |
+
for tensors in (float_tensors, int_tensors)
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
descriptions = []
|
| 53 |
+
for name in float_tensors:
|
| 54 |
+
shape_str = "(" + ", ".join([
|
| 55 |
+
f"2 ** {int(np.log2(i))}"
|
| 56 |
+
if 2 ** int(np.log2(i)) == i and i > 1
|
| 57 |
+
else str(i)
|
| 58 |
+
for i in float_tensors[name].shape
|
| 59 |
+
]) + ")"
|
| 60 |
+
order = float_tensor_params[name]["order"]
|
| 61 |
+
order_str = ("" if all(order == np.arange(len(order))) else str(tuple(order)))
|
| 62 |
+
steps = float_tensor_params[name]["steps"]
|
| 63 |
+
steps_str = str(steps) if sum(steps) > len(steps) else ""
|
| 64 |
+
descriptions.append((name, shape_str, order_str, steps_str))
|
| 65 |
+
raw_results.append((float_measurement, int_measurement, descriptions))
|
| 66 |
+
|
| 67 |
+
print(f"\r{i + 1} / {n}", end="")
|
| 68 |
+
print()
|
| 69 |
+
|
| 70 |
+
parsed_results, name_len, shape_len, order_len, steps_len = [], 0, 0, 0, 0
|
| 71 |
+
for float_measurement, int_measurement, descriptions in raw_results:
|
| 72 |
+
t_float = float_measurement.median * 1e6
|
| 73 |
+
t_int = int_measurement.median * 1e6
|
| 74 |
+
rel_diff = abs(t_float - t_int) / (t_float + t_int) * 2
|
| 75 |
+
parsed_results.append((t_float, t_int, rel_diff, descriptions))
|
| 76 |
+
for name, shape, order, steps in descriptions:
|
| 77 |
+
name_len = max(name_len, len(name))
|
| 78 |
+
shape_len = max(shape_len, len(shape))
|
| 79 |
+
order_len = max(order_len, len(order))
|
| 80 |
+
steps_len = max(steps_len, len(steps))
|
| 81 |
+
|
| 82 |
+
parsed_results.sort(key=operator.itemgetter(2))
|
| 83 |
+
|
| 84 |
+
print(f"stmt: {stmt}")
|
| 85 |
+
print(f" diff faster{'':>17}{' ' * name_len} ", end="")
|
| 86 |
+
print(f"{'shape'.ljust(shape_len)}{'':>16}{'order'.ljust(order_len)}", end="")
|
| 87 |
+
print(f" steps\n{'-' * 100}")
|
| 88 |
+
for results, spacer in [(parsed_results[:10], "..."), (parsed_results[-10:], "")]:
|
| 89 |
+
for t_float, t_int, rel_diff, descriptions in results:
|
| 90 |
+
time_str = [f"{rel_diff * 100:>4.1f}% {'int' if t_int < t_float else 'float':<20}"]
|
| 91 |
+
time_str.extend(["".ljust(len(time_str[0])) for _ in descriptions[:-1]])
|
| 92 |
+
for t_str, (name, shape, order, steps) in zip(time_str, descriptions, strict=True):
|
| 93 |
+
name = f"{name}:".ljust(name_len + 1)
|
| 94 |
+
shape = shape.ljust(shape_len + 10)
|
| 95 |
+
order = order.ljust(order_len)
|
| 96 |
+
print(f"{t_str} {name} {shape}| {order} | {steps}")
|
| 97 |
+
print(spacer)
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def main() -> None:
|
| 101 |
+
run(n=100, stmt="torch.median(x, dim=0)", fuzzer_cls=UnaryOpFuzzer)
|
| 102 |
+
run(n=100, stmt="torch.square(x)", fuzzer_cls=UnaryOpFuzzer)
|
| 103 |
+
run(n=100, stmt="x + y", fuzzer_cls=BinaryOpFuzzer)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
if __name__ == "__main__":
|
| 107 |
+
main()
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/benchmark/examples/simple_timeit.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Trivial use of Timer API:
|
| 2 |
+
|
| 3 |
+
$ python -m examples.simple_timeit
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
|
| 8 |
+
import torch.utils.benchmark as benchmark_utils
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def main() -> None:
|
| 12 |
+
timer = benchmark_utils.Timer(
|
| 13 |
+
stmt="x + y",
|
| 14 |
+
globals={"x": torch.ones((4, 8)), "y": torch.ones((1, 8))},
|
| 15 |
+
label="Broadcasting add (4x8)",
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
for i in range(3):
|
| 19 |
+
print(f"Run: {i}\n{'-' * 40}")
|
| 20 |
+
print(f"timeit:\n{timer.timeit(10000)}\n")
|
| 21 |
+
print(f"autorange:\n{timer.blocked_autorange()}\n\n")
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
if __name__ == "__main__":
|
| 25 |
+
main()
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/benchmark/examples/spectral_ops_fuzz_test.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
"""Microbenchmarks for the torch.fft module"""
|
| 3 |
+
from argparse import ArgumentParser
|
| 4 |
+
from collections import namedtuple
|
| 5 |
+
from collections.abc import Iterable
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
import torch.fft
|
| 9 |
+
from torch.utils import benchmark
|
| 10 |
+
from torch.utils.benchmark.op_fuzzers.spectral import SpectralOpFuzzer
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def _dim_options(ndim):
|
| 14 |
+
if ndim == 1:
|
| 15 |
+
return [None]
|
| 16 |
+
elif ndim == 2:
|
| 17 |
+
return [0, 1, None]
|
| 18 |
+
elif ndim == 3:
|
| 19 |
+
return [0, 1, 2, (0, 1), (0, 2), None]
|
| 20 |
+
raise ValueError(f"Expected ndim in range 1-3, got {ndim}")
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def run_benchmark(name: str, function: object, dtype: torch.dtype, seed: int, device: str, samples: int,
|
| 24 |
+
probability_regular: float):
|
| 25 |
+
cuda = device == 'cuda'
|
| 26 |
+
spectral_fuzzer = SpectralOpFuzzer(seed=seed, dtype=dtype, cuda=cuda,
|
| 27 |
+
probability_regular=probability_regular)
|
| 28 |
+
results = []
|
| 29 |
+
for tensors, tensor_params, params in spectral_fuzzer.take(samples):
|
| 30 |
+
shape = [params['k0'], params['k1'], params['k2']][:params['ndim']]
|
| 31 |
+
str_shape = ' x '.join([f"{s:<4}" for s in shape])
|
| 32 |
+
sub_label = f"{str_shape} {'' if tensor_params['x']['is_contiguous'] else '(discontiguous)'}"
|
| 33 |
+
for dim in _dim_options(params['ndim']):
|
| 34 |
+
for nthreads in (1, 4, 16) if not cuda else (1,):
|
| 35 |
+
measurement = benchmark.Timer(
|
| 36 |
+
stmt='func(x, dim=dim)',
|
| 37 |
+
globals={'func': function, 'x': tensors['x'], 'dim': dim},
|
| 38 |
+
label=f"{name}_{device}",
|
| 39 |
+
sub_label=sub_label,
|
| 40 |
+
description=f"dim={dim}",
|
| 41 |
+
num_threads=nthreads,
|
| 42 |
+
).blocked_autorange(min_run_time=1)
|
| 43 |
+
measurement.metadata = {
|
| 44 |
+
'name': name,
|
| 45 |
+
'device': device,
|
| 46 |
+
'dim': dim,
|
| 47 |
+
'shape': shape,
|
| 48 |
+
}
|
| 49 |
+
measurement.metadata.update(tensor_params['x'])
|
| 50 |
+
results.append(measurement)
|
| 51 |
+
return results
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
Benchmark = namedtuple('Benchmark', ['name', 'function', 'dtype'])
|
| 55 |
+
BENCHMARKS = [
|
| 56 |
+
Benchmark('fft_real', torch.fft.fftn, torch.float32),
|
| 57 |
+
Benchmark('fft_complex', torch.fft.fftn, torch.complex64),
|
| 58 |
+
Benchmark('ifft', torch.fft.ifftn, torch.complex64),
|
| 59 |
+
Benchmark('rfft', torch.fft.rfftn, torch.float32),
|
| 60 |
+
Benchmark('irfft', torch.fft.irfftn, torch.complex64),
|
| 61 |
+
]
|
| 62 |
+
BENCHMARK_MAP = {b.name: b for b in BENCHMARKS}
|
| 63 |
+
BENCHMARK_NAMES = [b.name for b in BENCHMARKS]
|
| 64 |
+
DEVICE_NAMES = ['cpu', 'cuda']
|
| 65 |
+
|
| 66 |
+
def _output_csv(file, results) -> None:
|
| 67 |
+
file.write('benchmark,device,num_threads,numel,shape,contiguous,dim,mean (us),median (us),iqr (us)\n')
|
| 68 |
+
for measurement in results:
|
| 69 |
+
metadata = measurement.metadata
|
| 70 |
+
device, dim, shape, name, numel, contiguous = (
|
| 71 |
+
metadata['device'], metadata['dim'], metadata['shape'],
|
| 72 |
+
metadata['name'], metadata['numel'], metadata['is_contiguous'])
|
| 73 |
+
|
| 74 |
+
if isinstance(dim, Iterable):
|
| 75 |
+
dim_str = '-'.join(str(d) for d in dim)
|
| 76 |
+
else:
|
| 77 |
+
dim_str = str(dim)
|
| 78 |
+
shape_str = 'x'.join(str(s) for s in shape)
|
| 79 |
+
|
| 80 |
+
print(name, device, measurement.task_spec.num_threads, numel, shape_str, contiguous, dim_str, # type: ignore[possibly-undefined]
|
| 81 |
+
measurement.mean * 1e6, measurement.median * 1e6, measurement.iqr * 1e6,
|
| 82 |
+
sep=',', file=file)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
if __name__ == '__main__':
|
| 86 |
+
parser = ArgumentParser(description=__doc__)
|
| 87 |
+
parser.add_argument('--device', type=str, choices=DEVICE_NAMES, nargs='+', default=DEVICE_NAMES)
|
| 88 |
+
parser.add_argument('--bench', type=str, choices=BENCHMARK_NAMES, nargs='+', default=BENCHMARK_NAMES)
|
| 89 |
+
parser.add_argument('--seed', type=int, default=0)
|
| 90 |
+
parser.add_argument('--samples', type=int, default=10)
|
| 91 |
+
parser.add_argument('--probability-regular', '--probability_regular', type=float, default=1.0)
|
| 92 |
+
parser.add_argument('-o', '--output', type=str)
|
| 93 |
+
args = parser.parse_args()
|
| 94 |
+
|
| 95 |
+
num_benchmarks = len(args.device) * len(args.bench)
|
| 96 |
+
i = 0
|
| 97 |
+
results = []
|
| 98 |
+
for device in args.device:
|
| 99 |
+
for bench in (BENCHMARK_MAP[b] for b in args.bench):
|
| 100 |
+
results += run_benchmark(
|
| 101 |
+
name=bench.name, function=bench.function, dtype=bench.dtype,
|
| 102 |
+
seed=args.seed, device=device, samples=args.samples,
|
| 103 |
+
probability_regular=args.probability_regular)
|
| 104 |
+
i += 1
|
| 105 |
+
print(f'Completed {bench.name} benchmark on {device} ({i} of {num_benchmarks})')
|
| 106 |
+
|
| 107 |
+
if args.output is not None:
|
| 108 |
+
with open(args.output, 'w') as f:
|
| 109 |
+
_output_csv(f, results)
|
| 110 |
+
|
| 111 |
+
compare = benchmark.Compare(results)
|
| 112 |
+
compare.trim_significant_figures()
|
| 113 |
+
compare.colorize()
|
| 114 |
+
compare.print()
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/benchmark/op_fuzzers/__init__.py
ADDED
|
File without changes
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/benchmark/op_fuzzers/binary.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import numpy as np
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
from torch.utils.benchmark import Fuzzer, FuzzedParameter, ParameterAlias, FuzzedTensor
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
_MIN_DIM_SIZE = 16
|
| 9 |
+
_MAX_DIM_SIZE = 16 * 1024 ** 2
|
| 10 |
+
_POW_TWO_SIZES = tuple(2 ** i for i in range(
|
| 11 |
+
int(np.log2(_MIN_DIM_SIZE)),
|
| 12 |
+
int(np.log2(_MAX_DIM_SIZE)) + 1,
|
| 13 |
+
))
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class BinaryOpFuzzer(Fuzzer):
|
| 17 |
+
def __init__(self, seed, dtype=torch.float32, cuda=False) -> None:
|
| 18 |
+
super().__init__(
|
| 19 |
+
parameters=[
|
| 20 |
+
# Dimensionality of x and y. (e.g. 1D, 2D, or 3D.)
|
| 21 |
+
FuzzedParameter("dim", distribution={1: 0.3, 2: 0.4, 3: 0.3}, strict=True),
|
| 22 |
+
|
| 23 |
+
# Shapes for `x` and `y`.
|
| 24 |
+
# It is important to test all shapes, however
|
| 25 |
+
# powers of two are especially important and therefore
|
| 26 |
+
# warrant special attention. This is done by generating
|
| 27 |
+
# both a value drawn from all integers between the min and
|
| 28 |
+
# max allowed values, and another from only the powers of two
|
| 29 |
+
# (both distributions are loguniform) and then randomly
|
| 30 |
+
# selecting between the two.
|
| 31 |
+
# Moreover, `y` will occasionally have singleton
|
| 32 |
+
# dimensions in order to test broadcasting.
|
| 33 |
+
[
|
| 34 |
+
FuzzedParameter(
|
| 35 |
+
name=f"k_any_{i}",
|
| 36 |
+
minval=_MIN_DIM_SIZE,
|
| 37 |
+
maxval=_MAX_DIM_SIZE,
|
| 38 |
+
distribution="loguniform",
|
| 39 |
+
) for i in range(3)
|
| 40 |
+
],
|
| 41 |
+
[
|
| 42 |
+
FuzzedParameter(
|
| 43 |
+
name=f"k_pow2_{i}",
|
| 44 |
+
distribution={size: 1. / len(_POW_TWO_SIZES) for size in _POW_TWO_SIZES}
|
| 45 |
+
) for i in range(3)
|
| 46 |
+
],
|
| 47 |
+
[
|
| 48 |
+
FuzzedParameter(
|
| 49 |
+
name=f"k{i}",
|
| 50 |
+
distribution={
|
| 51 |
+
ParameterAlias(f"k_any_{i}"): 0.8,
|
| 52 |
+
ParameterAlias(f"k_pow2_{i}"): 0.2,
|
| 53 |
+
},
|
| 54 |
+
strict=True,
|
| 55 |
+
) for i in range(3)
|
| 56 |
+
],
|
| 57 |
+
|
| 58 |
+
[
|
| 59 |
+
FuzzedParameter(
|
| 60 |
+
name=f"y_k{i}",
|
| 61 |
+
distribution={
|
| 62 |
+
ParameterAlias(f"k{i}"): 0.8,
|
| 63 |
+
1: 0.2,
|
| 64 |
+
},
|
| 65 |
+
strict=True,
|
| 66 |
+
) for i in range(3)
|
| 67 |
+
],
|
| 68 |
+
|
| 69 |
+
# Steps for `x` and `y`. (Benchmarks strided memory access.)
|
| 70 |
+
[
|
| 71 |
+
FuzzedParameter(
|
| 72 |
+
name=f"{name}_step_{i}",
|
| 73 |
+
distribution={1: 0.8, 2: 0.06, 4: 0.06, 8: 0.04, 16: 0.04},
|
| 74 |
+
)
|
| 75 |
+
for i in range(3)
|
| 76 |
+
for name in ("x", "y")
|
| 77 |
+
],
|
| 78 |
+
|
| 79 |
+
# Repeatable entropy for downstream applications.
|
| 80 |
+
FuzzedParameter(name="random_value", minval=0, maxval=2 ** 32 - 1, distribution="uniform"),
|
| 81 |
+
],
|
| 82 |
+
tensors=[
|
| 83 |
+
FuzzedTensor(
|
| 84 |
+
name="x",
|
| 85 |
+
size=("k0", "k1", "k2"),
|
| 86 |
+
steps=("x_step_0", "x_step_1", "x_step_2"),
|
| 87 |
+
probability_contiguous=0.75,
|
| 88 |
+
min_elements=4 * 1024,
|
| 89 |
+
max_elements=32 * 1024 ** 2,
|
| 90 |
+
max_allocation_bytes=2 * 1024**3, # 2 GB
|
| 91 |
+
dim_parameter="dim",
|
| 92 |
+
dtype=dtype,
|
| 93 |
+
cuda=cuda,
|
| 94 |
+
),
|
| 95 |
+
FuzzedTensor(
|
| 96 |
+
name="y",
|
| 97 |
+
size=("y_k0", "y_k1", "y_k2"),
|
| 98 |
+
steps=("x_step_0", "x_step_1", "x_step_2"),
|
| 99 |
+
probability_contiguous=0.75,
|
| 100 |
+
max_allocation_bytes=2 * 1024**3, # 2 GB
|
| 101 |
+
dim_parameter="dim",
|
| 102 |
+
dtype=dtype,
|
| 103 |
+
cuda=cuda,
|
| 104 |
+
),
|
| 105 |
+
],
|
| 106 |
+
seed=seed,
|
| 107 |
+
)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/benchmark/op_fuzzers/sparse_binary.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import numpy as np
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
from torch.utils.benchmark import Fuzzer, FuzzedParameter, ParameterAlias, FuzzedSparseTensor
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
_MIN_DIM_SIZE = 16
|
| 9 |
+
_MAX_DIM_SIZE = 16 * 1024 ** 2
|
| 10 |
+
_POW_TWO_SIZES = tuple(2 ** i for i in range(
|
| 11 |
+
int(np.log2(_MIN_DIM_SIZE)),
|
| 12 |
+
int(np.log2(_MAX_DIM_SIZE)) + 1,
|
| 13 |
+
))
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class BinaryOpSparseFuzzer(Fuzzer):
|
| 17 |
+
def __init__(self, seed, dtype=torch.float32, cuda=False) -> None:
|
| 18 |
+
super().__init__(
|
| 19 |
+
parameters=[
|
| 20 |
+
# Dimensionality of x and y. (e.g. 1D, 2D, or 3D.)
|
| 21 |
+
FuzzedParameter("dim_parameter", distribution={1: 0.3, 2: 0.4, 3: 0.3}, strict=True),
|
| 22 |
+
FuzzedParameter(
|
| 23 |
+
name="sparse_dim",
|
| 24 |
+
distribution={1: 0.4, 2: 0.4, 3: 0.2},
|
| 25 |
+
strict=True
|
| 26 |
+
),
|
| 27 |
+
# Shapes for `x` and `y`.
|
| 28 |
+
# It is important to test all shapes, however
|
| 29 |
+
# powers of two are especially important and therefore
|
| 30 |
+
# warrant special attention. This is done by generating
|
| 31 |
+
# both a value drawn from all integers between the min and
|
| 32 |
+
# max allowed values, and another from only the powers of two
|
| 33 |
+
# (both distributions are loguniform) and then randomly
|
| 34 |
+
# selecting between the two.
|
| 35 |
+
# Moreover, `y` will occasionally have singleton
|
| 36 |
+
# dimensions in order to test broadcasting.
|
| 37 |
+
[
|
| 38 |
+
FuzzedParameter(
|
| 39 |
+
name=f"k_any_{i}",
|
| 40 |
+
minval=_MIN_DIM_SIZE,
|
| 41 |
+
maxval=_MAX_DIM_SIZE,
|
| 42 |
+
distribution="loguniform",
|
| 43 |
+
) for i in range(3)
|
| 44 |
+
],
|
| 45 |
+
[
|
| 46 |
+
FuzzedParameter(
|
| 47 |
+
name=f"k_pow2_{i}",
|
| 48 |
+
distribution={size: 1. / len(_POW_TWO_SIZES) for size in _POW_TWO_SIZES}
|
| 49 |
+
) for i in range(3)
|
| 50 |
+
],
|
| 51 |
+
[
|
| 52 |
+
FuzzedParameter(
|
| 53 |
+
name=f"k{i}",
|
| 54 |
+
distribution={
|
| 55 |
+
ParameterAlias(f"k_any_{i}"): 0.8,
|
| 56 |
+
ParameterAlias(f"k_pow2_{i}"): 0.2,
|
| 57 |
+
},
|
| 58 |
+
strict=True,
|
| 59 |
+
) for i in range(3)
|
| 60 |
+
],
|
| 61 |
+
[
|
| 62 |
+
FuzzedParameter(
|
| 63 |
+
name=f"y_k{i}",
|
| 64 |
+
distribution={
|
| 65 |
+
ParameterAlias(f"k{i}"): 1.0},
|
| 66 |
+
strict=True,
|
| 67 |
+
) for i in range(3)
|
| 68 |
+
],
|
| 69 |
+
FuzzedParameter(
|
| 70 |
+
name="density",
|
| 71 |
+
distribution={0.1: 0.4, 0.05: 0.3, 0.01: 0.3},
|
| 72 |
+
),
|
| 73 |
+
FuzzedParameter(
|
| 74 |
+
name="coalesced",
|
| 75 |
+
distribution={True: 0.5, False: 0.5},
|
| 76 |
+
),
|
| 77 |
+
# Repeatable entropy for downstream applications.
|
| 78 |
+
FuzzedParameter(name="random_value", minval=0, maxval=2 ** 32 - 1, distribution="uniform"),
|
| 79 |
+
],
|
| 80 |
+
tensors=[
|
| 81 |
+
FuzzedSparseTensor(
|
| 82 |
+
name="x",
|
| 83 |
+
size=("k0", "k1", "k2"),
|
| 84 |
+
dim_parameter="dim_parameter",
|
| 85 |
+
sparse_dim="sparse_dim",
|
| 86 |
+
density="density",
|
| 87 |
+
coalesced="coalesced",
|
| 88 |
+
min_elements=4 * 1024,
|
| 89 |
+
max_elements=32 * 1024 ** 2,
|
| 90 |
+
dtype=dtype,
|
| 91 |
+
cuda=cuda,
|
| 92 |
+
),
|
| 93 |
+
FuzzedSparseTensor(
|
| 94 |
+
name="y",
|
| 95 |
+
size=("y_k0", "y_k1", "y_k2"),
|
| 96 |
+
dim_parameter="dim_parameter",
|
| 97 |
+
sparse_dim="sparse_dim",
|
| 98 |
+
density="density",
|
| 99 |
+
coalesced="coalesced",
|
| 100 |
+
min_elements=4 * 1024,
|
| 101 |
+
max_elements=32 * 1024 ** 2,
|
| 102 |
+
dtype=dtype,
|
| 103 |
+
cuda=cuda,
|
| 104 |
+
),
|
| 105 |
+
],
|
| 106 |
+
seed=seed,
|
| 107 |
+
)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/benchmark/op_fuzzers/sparse_unary.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import TYPE_CHECKING
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
import torch
|
| 7 |
+
|
| 8 |
+
if TYPE_CHECKING:
|
| 9 |
+
from torch.types import _dtype
|
| 10 |
+
|
| 11 |
+
from torch.utils.benchmark import Fuzzer, FuzzedParameter, ParameterAlias, FuzzedSparseTensor
|
| 12 |
+
|
| 13 |
+
__all__ = ["UnaryOpSparseFuzzer"]
|
| 14 |
+
|
| 15 |
+
_MIN_DIM_SIZE = 16
|
| 16 |
+
_MAX_DIM_SIZE = 16 * 1024 ** 2
|
| 17 |
+
_POW_TWO_SIZES = tuple(2 ** i for i in range(
|
| 18 |
+
int(np.log2(_MIN_DIM_SIZE)),
|
| 19 |
+
int(np.log2(_MAX_DIM_SIZE)) + 1,
|
| 20 |
+
))
|
| 21 |
+
|
| 22 |
+
class UnaryOpSparseFuzzer(Fuzzer):
|
| 23 |
+
def __init__(self, seed: int | None, dtype: _dtype | None = None, cuda: bool = False) -> None:
|
| 24 |
+
if dtype is None:
|
| 25 |
+
dtype = getattr(torch, 'float32', None)
|
| 26 |
+
super().__init__(
|
| 27 |
+
parameters=[
|
| 28 |
+
# Sparse dim parameter of x. (e.g. 1D, 2D, or 3D.)
|
| 29 |
+
FuzzedParameter("dim_parameter", distribution={1: 0.3, 2: 0.4, 3: 0.3}, strict=True),
|
| 30 |
+
FuzzedParameter(
|
| 31 |
+
name="sparse_dim",
|
| 32 |
+
distribution={1: 0.4, 2: 0.4, 3: 0.2},
|
| 33 |
+
strict=True
|
| 34 |
+
),
|
| 35 |
+
# Shapes for `x`.
|
| 36 |
+
# It is important to test all shapes, however
|
| 37 |
+
# powers of two are especially important and therefore
|
| 38 |
+
# warrant special attention. This is done by generating
|
| 39 |
+
# both a value drawn from all integers between the min and
|
| 40 |
+
# max allowed values, and another from only the powers of two
|
| 41 |
+
# (both distributions are loguniform) and then randomly
|
| 42 |
+
# selecting between the two.
|
| 43 |
+
[
|
| 44 |
+
FuzzedParameter(
|
| 45 |
+
name=f"k_any_{i}",
|
| 46 |
+
minval=_MIN_DIM_SIZE,
|
| 47 |
+
maxval=_MAX_DIM_SIZE,
|
| 48 |
+
distribution="loguniform",
|
| 49 |
+
) for i in range(3)
|
| 50 |
+
],
|
| 51 |
+
[
|
| 52 |
+
FuzzedParameter(
|
| 53 |
+
name=f"k_pow2_{i}",
|
| 54 |
+
distribution={size: 1. / len(_POW_TWO_SIZES) for size in _POW_TWO_SIZES}
|
| 55 |
+
) for i in range(3)
|
| 56 |
+
],
|
| 57 |
+
[
|
| 58 |
+
FuzzedParameter(
|
| 59 |
+
name=f"k{i}",
|
| 60 |
+
distribution={
|
| 61 |
+
ParameterAlias(f"k_any_{i}"): 0.8,
|
| 62 |
+
ParameterAlias(f"k_pow2_{i}"): 0.2,
|
| 63 |
+
},
|
| 64 |
+
strict=True,
|
| 65 |
+
) for i in range(3)
|
| 66 |
+
],
|
| 67 |
+
FuzzedParameter(
|
| 68 |
+
name="density",
|
| 69 |
+
distribution={0.1: 0.4, 0.05: 0.3, 0.01: 0.3},
|
| 70 |
+
),
|
| 71 |
+
FuzzedParameter(
|
| 72 |
+
name="coalesced",
|
| 73 |
+
distribution={True: 0.5, False: 0.5},
|
| 74 |
+
),
|
| 75 |
+
FuzzedParameter(name="random_value", minval=0, maxval=2 ** 32 - 1, distribution="uniform"),
|
| 76 |
+
],
|
| 77 |
+
tensors=[
|
| 78 |
+
FuzzedSparseTensor(
|
| 79 |
+
name="x",
|
| 80 |
+
size=("k0", "k1", "k2"),
|
| 81 |
+
dim_parameter="dim_parameter",
|
| 82 |
+
sparse_dim="sparse_dim",
|
| 83 |
+
min_elements=4 * 1024,
|
| 84 |
+
max_elements=32 * 1024 ** 2,
|
| 85 |
+
density="density",
|
| 86 |
+
coalesced="coalesced",
|
| 87 |
+
dtype=dtype,
|
| 88 |
+
cuda=cuda,
|
| 89 |
+
),
|
| 90 |
+
],
|
| 91 |
+
seed=seed,
|
| 92 |
+
)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/benchmark/op_fuzzers/spectral.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import math
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
from torch.utils import benchmark
|
| 6 |
+
from torch.utils.benchmark import FuzzedParameter, FuzzedTensor, ParameterAlias
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
__all__ = ['SpectralOpFuzzer']
|
| 10 |
+
|
| 11 |
+
MIN_DIM_SIZE = 16
|
| 12 |
+
MAX_DIM_SIZE = 16 * 1024
|
| 13 |
+
|
| 14 |
+
def power_range(upper_bound, base):
|
| 15 |
+
return (base ** i for i in range(int(math.log(upper_bound, base)) + 1))
|
| 16 |
+
|
| 17 |
+
# List of regular numbers from MIN_DIM_SIZE to MAX_DIM_SIZE
|
| 18 |
+
# These numbers factorize into multiples of prime factors 2, 3, and 5 only
|
| 19 |
+
# and are usually the fastest in FFT implementations.
|
| 20 |
+
REGULAR_SIZES = []
|
| 21 |
+
for i in power_range(MAX_DIM_SIZE, 2):
|
| 22 |
+
for j in power_range(MAX_DIM_SIZE // i, 3):
|
| 23 |
+
ij = i * j
|
| 24 |
+
for k in power_range(MAX_DIM_SIZE // ij, 5):
|
| 25 |
+
ijk = ij * k
|
| 26 |
+
if ijk > MIN_DIM_SIZE:
|
| 27 |
+
REGULAR_SIZES.append(ijk)
|
| 28 |
+
REGULAR_SIZES.sort()
|
| 29 |
+
|
| 30 |
+
class SpectralOpFuzzer(benchmark.Fuzzer):
|
| 31 |
+
def __init__(self, *, seed: int, dtype=torch.float64,
|
| 32 |
+
cuda: bool = False, probability_regular: float = 1.0) -> None:
|
| 33 |
+
super().__init__(
|
| 34 |
+
parameters=[
|
| 35 |
+
# Dimensionality of x. (e.g. 1D, 2D, or 3D.)
|
| 36 |
+
FuzzedParameter("ndim", distribution={1: 0.3, 2: 0.4, 3: 0.3}, strict=True),
|
| 37 |
+
|
| 38 |
+
# Shapes for `x`.
|
| 39 |
+
# It is important to test all shapes, however
|
| 40 |
+
# regular sizes are especially important to the FFT and therefore
|
| 41 |
+
# warrant special attention. This is done by generating
|
| 42 |
+
# both a value drawn from all integers between the min and
|
| 43 |
+
# max allowed values, and another from only the regular numbers
|
| 44 |
+
# (both distributions are loguniform) and then randomly
|
| 45 |
+
# selecting between the two.
|
| 46 |
+
[
|
| 47 |
+
FuzzedParameter(
|
| 48 |
+
name=f"k_any_{i}",
|
| 49 |
+
minval=MIN_DIM_SIZE,
|
| 50 |
+
maxval=MAX_DIM_SIZE,
|
| 51 |
+
distribution="loguniform",
|
| 52 |
+
) for i in range(3)
|
| 53 |
+
],
|
| 54 |
+
[
|
| 55 |
+
FuzzedParameter(
|
| 56 |
+
name=f"k_regular_{i}",
|
| 57 |
+
distribution={size: 1. / len(REGULAR_SIZES) for size in REGULAR_SIZES}
|
| 58 |
+
) for i in range(3)
|
| 59 |
+
],
|
| 60 |
+
[
|
| 61 |
+
FuzzedParameter(
|
| 62 |
+
name=f"k{i}",
|
| 63 |
+
distribution={
|
| 64 |
+
ParameterAlias(f"k_regular_{i}"): probability_regular,
|
| 65 |
+
ParameterAlias(f"k_any_{i}"): 1 - probability_regular,
|
| 66 |
+
},
|
| 67 |
+
strict=True,
|
| 68 |
+
) for i in range(3)
|
| 69 |
+
],
|
| 70 |
+
|
| 71 |
+
# Steps for `x`. (Benchmarks strided memory access.)
|
| 72 |
+
[
|
| 73 |
+
FuzzedParameter(
|
| 74 |
+
name=f"step_{i}",
|
| 75 |
+
distribution={1: 0.8, 2: 0.06, 4: 0.06, 8: 0.04, 16: 0.04},
|
| 76 |
+
) for i in range(3)
|
| 77 |
+
],
|
| 78 |
+
],
|
| 79 |
+
tensors=[
|
| 80 |
+
FuzzedTensor(
|
| 81 |
+
name="x",
|
| 82 |
+
size=("k0", "k1", "k2"),
|
| 83 |
+
steps=("step_0", "step_1", "step_2"),
|
| 84 |
+
probability_contiguous=0.75,
|
| 85 |
+
min_elements=4 * 1024,
|
| 86 |
+
max_elements=32 * 1024 ** 2,
|
| 87 |
+
max_allocation_bytes=2 * 1024**3, # 2 GB
|
| 88 |
+
dim_parameter="ndim",
|
| 89 |
+
dtype=dtype,
|
| 90 |
+
cuda=cuda,
|
| 91 |
+
),
|
| 92 |
+
],
|
| 93 |
+
seed=seed,
|
| 94 |
+
)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/benchmark/op_fuzzers/unary.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import numpy as np
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
from torch.utils.benchmark import Fuzzer, FuzzedParameter, ParameterAlias, FuzzedTensor
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
_MIN_DIM_SIZE = 16
|
| 9 |
+
_MAX_DIM_SIZE = 16 * 1024 ** 2
|
| 10 |
+
_POW_TWO_SIZES = tuple(2 ** i for i in range(
|
| 11 |
+
int(np.log2(_MIN_DIM_SIZE)),
|
| 12 |
+
int(np.log2(_MAX_DIM_SIZE)) + 1,
|
| 13 |
+
))
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class UnaryOpFuzzer(Fuzzer):
|
| 17 |
+
def __init__(self, seed, dtype=torch.float32, cuda=False) -> None:
|
| 18 |
+
super().__init__(
|
| 19 |
+
parameters=[
|
| 20 |
+
# Dimensionality of x. (e.g. 1D, 2D, or 3D.)
|
| 21 |
+
FuzzedParameter("dim", distribution={1: 0.3, 2: 0.4, 3: 0.3}, strict=True),
|
| 22 |
+
|
| 23 |
+
# Shapes for `x`.
|
| 24 |
+
# It is important to test all shapes, however
|
| 25 |
+
# powers of two are especially important and therefore
|
| 26 |
+
# warrant special attention. This is done by generating
|
| 27 |
+
# both a value drawn from all integers between the min and
|
| 28 |
+
# max allowed values, and another from only the powers of two
|
| 29 |
+
# (both distributions are loguniform) and then randomly
|
| 30 |
+
# selecting between the two.
|
| 31 |
+
[
|
| 32 |
+
FuzzedParameter(
|
| 33 |
+
name=f"k_any_{i}",
|
| 34 |
+
minval=_MIN_DIM_SIZE,
|
| 35 |
+
maxval=_MAX_DIM_SIZE,
|
| 36 |
+
distribution="loguniform",
|
| 37 |
+
) for i in range(3)
|
| 38 |
+
],
|
| 39 |
+
[
|
| 40 |
+
FuzzedParameter(
|
| 41 |
+
name=f"k_pow2_{i}",
|
| 42 |
+
distribution={size: 1. / len(_POW_TWO_SIZES) for size in _POW_TWO_SIZES}
|
| 43 |
+
) for i in range(3)
|
| 44 |
+
],
|
| 45 |
+
[
|
| 46 |
+
FuzzedParameter(
|
| 47 |
+
name=f"k{i}",
|
| 48 |
+
distribution={
|
| 49 |
+
ParameterAlias(f"k_any_{i}"): 0.8,
|
| 50 |
+
ParameterAlias(f"k_pow2_{i}"): 0.2,
|
| 51 |
+
},
|
| 52 |
+
strict=True,
|
| 53 |
+
) for i in range(3)
|
| 54 |
+
],
|
| 55 |
+
|
| 56 |
+
# Steps for `x`. (Benchmarks strided memory access.)
|
| 57 |
+
[
|
| 58 |
+
FuzzedParameter(
|
| 59 |
+
name=f"x_step_{i}",
|
| 60 |
+
distribution={1: 0.8, 2: 0.06, 4: 0.06, 8: 0.04, 16: 0.04},
|
| 61 |
+
) for i in range(3)
|
| 62 |
+
],
|
| 63 |
+
|
| 64 |
+
# Repeatable entropy for downstream applications.
|
| 65 |
+
FuzzedParameter(name="random_value", minval=0, maxval=2 ** 32 - 1, distribution="uniform"),
|
| 66 |
+
],
|
| 67 |
+
tensors=[
|
| 68 |
+
FuzzedTensor(
|
| 69 |
+
name="x",
|
| 70 |
+
size=("k0", "k1", "k2"),
|
| 71 |
+
steps=("x_step_0", "x_step_1", "x_step_2"),
|
| 72 |
+
probability_contiguous=0.75,
|
| 73 |
+
min_elements=4 * 1024,
|
| 74 |
+
max_elements=32 * 1024 ** 2,
|
| 75 |
+
max_allocation_bytes=2 * 1024**3, # 2 GB
|
| 76 |
+
dim_parameter="dim",
|
| 77 |
+
dtype=dtype,
|
| 78 |
+
cuda=cuda,
|
| 79 |
+
),
|
| 80 |
+
],
|
| 81 |
+
seed=seed,
|
| 82 |
+
)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/benchmark/utils/__init__.py
ADDED
|
File without changes
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/benchmark/utils/_stubs.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any
|
| 2 |
+
from collections.abc import Callable
|
| 3 |
+
from typing_extensions import Protocol, runtime_checkable
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class TimerClass(Protocol):
|
| 7 |
+
"""This is the portion of the `timeit.Timer` API used by benchmark utils."""
|
| 8 |
+
def __init__(
|
| 9 |
+
self,
|
| 10 |
+
stmt: str,
|
| 11 |
+
setup: str,
|
| 12 |
+
timer: Callable[[], float],
|
| 13 |
+
globals: dict[str, Any],
|
| 14 |
+
**kwargs: Any,
|
| 15 |
+
) -> None:
|
| 16 |
+
...
|
| 17 |
+
|
| 18 |
+
def timeit(self, number: int) -> float:
|
| 19 |
+
...
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@runtime_checkable
|
| 23 |
+
class TimeitModuleType(Protocol):
|
| 24 |
+
"""Modules generated from `timeit_template.cpp`."""
|
| 25 |
+
def timeit(self, number: int) -> float:
|
| 26 |
+
...
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class CallgrindModuleType(Protocol):
|
| 30 |
+
"""Replicates the valgrind endpoints in `torch._C`.
|
| 31 |
+
|
| 32 |
+
These bindings are used to collect Callgrind profiles on earlier versions
|
| 33 |
+
of PyTorch and will eventually be removed.
|
| 34 |
+
"""
|
| 35 |
+
__file__: str
|
| 36 |
+
__name__: str
|
| 37 |
+
|
| 38 |
+
def _valgrind_supported_platform(self) -> bool:
|
| 39 |
+
...
|
| 40 |
+
|
| 41 |
+
def _valgrind_toggle(self) -> None:
|
| 42 |
+
...
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/benchmark/utils/common.py
ADDED
|
@@ -0,0 +1,359 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Base shared classes and utilities."""
|
| 2 |
+
|
| 3 |
+
import collections
|
| 4 |
+
import contextlib
|
| 5 |
+
import dataclasses
|
| 6 |
+
import os
|
| 7 |
+
import shutil
|
| 8 |
+
import tempfile
|
| 9 |
+
import textwrap
|
| 10 |
+
import time
|
| 11 |
+
from typing import cast, Any
|
| 12 |
+
from collections.abc import Iterable, Iterator
|
| 13 |
+
import uuid
|
| 14 |
+
|
| 15 |
+
import torch
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
__all__ = ["TaskSpec", "Measurement", "select_unit", "unit_to_english", "trim_sigfig", "ordered_unique", "set_torch_threads"]
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
_MAX_SIGNIFICANT_FIGURES = 4
|
| 22 |
+
_MIN_CONFIDENCE_INTERVAL = 25e-9 # 25 ns
|
| 23 |
+
|
| 24 |
+
# Measurement will include a warning if the distribution is suspect. All
|
| 25 |
+
# runs are expected to have some variation; these parameters set the
|
| 26 |
+
# thresholds.
|
| 27 |
+
_IQR_WARN_THRESHOLD = 0.1
|
| 28 |
+
_IQR_GROSS_WARN_THRESHOLD = 0.25
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@dataclasses.dataclass(init=True, repr=False, eq=True, frozen=True)
|
| 32 |
+
class TaskSpec:
|
| 33 |
+
"""Container for information used to define a Timer. (except globals)"""
|
| 34 |
+
stmt: str
|
| 35 |
+
setup: str
|
| 36 |
+
global_setup: str = ""
|
| 37 |
+
label: str | None = None
|
| 38 |
+
sub_label: str | None = None
|
| 39 |
+
description: str | None = None
|
| 40 |
+
env: str | None = None
|
| 41 |
+
num_threads: int = 1
|
| 42 |
+
|
| 43 |
+
@property
|
| 44 |
+
def title(self) -> str:
|
| 45 |
+
"""Best effort attempt at a string label for the measurement."""
|
| 46 |
+
if self.label is not None:
|
| 47 |
+
return self.label + (f": {self.sub_label}" if self.sub_label else "")
|
| 48 |
+
elif "\n" not in self.stmt:
|
| 49 |
+
return self.stmt + (f": {self.sub_label}" if self.sub_label else "")
|
| 50 |
+
return (
|
| 51 |
+
f"stmt:{f' ({self.sub_label})' if self.sub_label else ''}\n"
|
| 52 |
+
f"{textwrap.indent(self.stmt, ' ')}"
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
def setup_str(self) -> str:
|
| 56 |
+
return (
|
| 57 |
+
"" if (self.setup == "pass" or not self.setup)
|
| 58 |
+
else f"setup:\n{textwrap.indent(self.setup, ' ')}" if "\n" in self.setup
|
| 59 |
+
else f"setup: {self.setup}"
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
def summarize(self) -> str:
|
| 63 |
+
"""Build TaskSpec portion of repr string for other containers."""
|
| 64 |
+
sections = [
|
| 65 |
+
self.title,
|
| 66 |
+
self.description or "",
|
| 67 |
+
self.setup_str(),
|
| 68 |
+
]
|
| 69 |
+
return "\n".join([f"{i}\n" if "\n" in i else i for i in sections if i])
|
| 70 |
+
|
| 71 |
+
_TASKSPEC_FIELDS = tuple(i.name for i in dataclasses.fields(TaskSpec))
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
@dataclasses.dataclass(init=True, repr=False)
|
| 75 |
+
class Measurement:
|
| 76 |
+
"""The result of a Timer measurement.
|
| 77 |
+
|
| 78 |
+
This class stores one or more measurements of a given statement. It is
|
| 79 |
+
serializable and provides several convenience methods
|
| 80 |
+
(including a detailed __repr__) for downstream consumers.
|
| 81 |
+
"""
|
| 82 |
+
number_per_run: int
|
| 83 |
+
raw_times: list[float]
|
| 84 |
+
task_spec: TaskSpec
|
| 85 |
+
metadata: dict[Any, Any] | None = None # Reserved for user payloads.
|
| 86 |
+
|
| 87 |
+
def __post_init__(self) -> None:
|
| 88 |
+
self._sorted_times: tuple[float, ...] = ()
|
| 89 |
+
self._warnings: tuple[str, ...] = ()
|
| 90 |
+
self._median: float = -1.0
|
| 91 |
+
self._mean: float = -1.0
|
| 92 |
+
self._p25: float = -1.0
|
| 93 |
+
self._p75: float = -1.0
|
| 94 |
+
|
| 95 |
+
def __getattr__(self, name: str) -> Any:
|
| 96 |
+
# Forward TaskSpec fields for convenience.
|
| 97 |
+
if name in _TASKSPEC_FIELDS:
|
| 98 |
+
return getattr(self.task_spec, name)
|
| 99 |
+
return super().__getattribute__(name)
|
| 100 |
+
|
| 101 |
+
# =========================================================================
|
| 102 |
+
# == Convenience methods for statistics ===================================
|
| 103 |
+
# =========================================================================
|
| 104 |
+
#
|
| 105 |
+
# These methods use raw time divided by number_per_run; this is an
|
| 106 |
+
# extrapolation and hides the fact that different number_per_run will
|
| 107 |
+
# result in different amortization of overheads, however if Timer has
|
| 108 |
+
# selected an appropriate number_per_run then this is a non-issue, and
|
| 109 |
+
# forcing users to handle that division would result in a poor experience.
|
| 110 |
+
@property
|
| 111 |
+
def times(self) -> list[float]:
|
| 112 |
+
return [t / self.number_per_run for t in self.raw_times]
|
| 113 |
+
|
| 114 |
+
@property
|
| 115 |
+
def median(self) -> float:
|
| 116 |
+
self._lazy_init()
|
| 117 |
+
return self._median
|
| 118 |
+
|
| 119 |
+
@property
|
| 120 |
+
def mean(self) -> float:
|
| 121 |
+
self._lazy_init()
|
| 122 |
+
return self._mean
|
| 123 |
+
|
| 124 |
+
@property
|
| 125 |
+
def iqr(self) -> float:
|
| 126 |
+
self._lazy_init()
|
| 127 |
+
return self._p75 - self._p25
|
| 128 |
+
|
| 129 |
+
@property
|
| 130 |
+
def significant_figures(self) -> int:
|
| 131 |
+
"""Approximate significant figure estimate.
|
| 132 |
+
|
| 133 |
+
This property is intended to give a convenient way to estimate the
|
| 134 |
+
precision of a measurement. It only uses the interquartile region to
|
| 135 |
+
estimate statistics to try to mitigate skew from the tails, and
|
| 136 |
+
uses a static z value of 1.645 since it is not expected to be used
|
| 137 |
+
for small values of `n`, so z can approximate `t`.
|
| 138 |
+
|
| 139 |
+
The significant figure estimation used in conjunction with the
|
| 140 |
+
`trim_sigfig` method to provide a more human interpretable data
|
| 141 |
+
summary. __repr__ does not use this method; it simply displays raw
|
| 142 |
+
values. Significant figure estimation is intended for `Compare`.
|
| 143 |
+
"""
|
| 144 |
+
self._lazy_init()
|
| 145 |
+
n_total = len(self._sorted_times)
|
| 146 |
+
lower_bound = int(n_total // 4)
|
| 147 |
+
upper_bound = int(torch.tensor(3 * n_total / 4).ceil())
|
| 148 |
+
interquartile_points: tuple[float, ...] = self._sorted_times[lower_bound:upper_bound]
|
| 149 |
+
std = torch.tensor(interquartile_points).std(unbiased=False).item()
|
| 150 |
+
sqrt_n = torch.tensor(len(interquartile_points)).sqrt().item()
|
| 151 |
+
|
| 152 |
+
# Rough estimates. These are by no means statistically rigorous.
|
| 153 |
+
confidence_interval = max(1.645 * std / sqrt_n, _MIN_CONFIDENCE_INTERVAL)
|
| 154 |
+
relative_ci = torch.tensor(self._median / confidence_interval).log10().item()
|
| 155 |
+
num_significant_figures = int(torch.tensor(relative_ci).floor())
|
| 156 |
+
return min(max(num_significant_figures, 1), _MAX_SIGNIFICANT_FIGURES)
|
| 157 |
+
|
| 158 |
+
@property
|
| 159 |
+
def has_warnings(self) -> bool:
|
| 160 |
+
self._lazy_init()
|
| 161 |
+
return bool(self._warnings)
|
| 162 |
+
|
| 163 |
+
def _lazy_init(self) -> None:
|
| 164 |
+
if self.raw_times and not self._sorted_times:
|
| 165 |
+
self._sorted_times = tuple(sorted(self.times))
|
| 166 |
+
_sorted_times = torch.tensor(self._sorted_times, dtype=torch.float64)
|
| 167 |
+
self._median = _sorted_times.quantile(.5).item()
|
| 168 |
+
self._mean = _sorted_times.mean().item()
|
| 169 |
+
self._p25 = _sorted_times.quantile(.25).item()
|
| 170 |
+
self._p75 = _sorted_times.quantile(.75).item()
|
| 171 |
+
|
| 172 |
+
def add_warning(msg: str) -> None:
|
| 173 |
+
rel_iqr = self.iqr / self.median * 100
|
| 174 |
+
self._warnings += (
|
| 175 |
+
f" WARNING: Interquartile range is {rel_iqr:.1f}% "
|
| 176 |
+
f"of the median measurement.\n {msg}",
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
if not self.meets_confidence(_IQR_GROSS_WARN_THRESHOLD):
|
| 180 |
+
add_warning("This suggests significant environmental influence.")
|
| 181 |
+
elif not self.meets_confidence(_IQR_WARN_THRESHOLD):
|
| 182 |
+
add_warning("This could indicate system fluctuation.")
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def meets_confidence(self, threshold: float = _IQR_WARN_THRESHOLD) -> bool:
|
| 186 |
+
return self.iqr / self.median < threshold
|
| 187 |
+
|
| 188 |
+
@property
|
| 189 |
+
def title(self) -> str:
|
| 190 |
+
return self.task_spec.title
|
| 191 |
+
|
| 192 |
+
@property
|
| 193 |
+
def env(self) -> str:
|
| 194 |
+
return (
|
| 195 |
+
"Unspecified env" if self.taskspec.env is None
|
| 196 |
+
else cast(str, self.taskspec.env)
|
| 197 |
+
)
|
| 198 |
+
|
| 199 |
+
@property
|
| 200 |
+
def as_row_name(self) -> str:
|
| 201 |
+
return self.sub_label or self.stmt or "[Unknown]"
|
| 202 |
+
|
| 203 |
+
def __repr__(self) -> str:
|
| 204 |
+
"""
|
| 205 |
+
Example repr:
|
| 206 |
+
<utils.common.Measurement object at 0x7f395b6ac110>
|
| 207 |
+
Broadcasting add (4x8)
|
| 208 |
+
Median: 5.73 us
|
| 209 |
+
IQR: 2.25 us (4.01 to 6.26)
|
| 210 |
+
372 measurements, 100 runs per measurement, 1 thread
|
| 211 |
+
WARNING: Interquartile range is 39.4% of the median measurement.
|
| 212 |
+
This suggests significant environmental influence.
|
| 213 |
+
"""
|
| 214 |
+
self._lazy_init()
|
| 215 |
+
skip_line, newline = "MEASUREMENT_REPR_SKIP_LINE", "\n"
|
| 216 |
+
n = len(self._sorted_times)
|
| 217 |
+
time_unit, time_scale = select_unit(self._median)
|
| 218 |
+
iqr_filter = '' if n >= 4 else skip_line
|
| 219 |
+
|
| 220 |
+
repr_str = f"""
|
| 221 |
+
{super().__repr__()}
|
| 222 |
+
{self.task_spec.summarize()}
|
| 223 |
+
{'Median: ' if n > 1 else ''}{self._median / time_scale:.2f} {time_unit}
|
| 224 |
+
{iqr_filter}IQR: {self.iqr / time_scale:.2f} {time_unit} ({self._p25 / time_scale:.2f} to {self._p75 / time_scale:.2f})
|
| 225 |
+
{n} measurement{'s' if n > 1 else ''}, {self.number_per_run} runs {'per measurement,' if n > 1 else ','} {self.num_threads} thread{'s' if self.num_threads > 1 else ''}
|
| 226 |
+
{newline.join(self._warnings)}""".strip() # noqa: B950
|
| 227 |
+
|
| 228 |
+
return "\n".join(l for l in repr_str.splitlines(keepends=False) if skip_line not in l)
|
| 229 |
+
|
| 230 |
+
@staticmethod
|
| 231 |
+
def merge(measurements: Iterable["Measurement"]) -> list["Measurement"]:
|
| 232 |
+
"""Convenience method for merging replicates.
|
| 233 |
+
|
| 234 |
+
Merge will extrapolate times to `number_per_run=1` and will not
|
| 235 |
+
transfer any metadata. (Since it might differ between replicates)
|
| 236 |
+
"""
|
| 237 |
+
grouped_measurements: collections.defaultdict[TaskSpec, list[Measurement]] = collections.defaultdict(list)
|
| 238 |
+
for m in measurements:
|
| 239 |
+
grouped_measurements[m.task_spec].append(m)
|
| 240 |
+
|
| 241 |
+
def merge_group(task_spec: TaskSpec, group: list["Measurement"]) -> "Measurement":
|
| 242 |
+
times: list[float] = []
|
| 243 |
+
for m in group:
|
| 244 |
+
# Different measurements could have different `number_per_run`,
|
| 245 |
+
# so we call `.times` which normalizes the results.
|
| 246 |
+
times.extend(m.times)
|
| 247 |
+
|
| 248 |
+
return Measurement(
|
| 249 |
+
number_per_run=1,
|
| 250 |
+
raw_times=times,
|
| 251 |
+
task_spec=task_spec,
|
| 252 |
+
metadata=None,
|
| 253 |
+
)
|
| 254 |
+
|
| 255 |
+
return [merge_group(t, g) for t, g in grouped_measurements.items()]
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
def select_unit(t: float) -> tuple[str, float]:
|
| 259 |
+
"""Determine how to scale times for O(1) magnitude.
|
| 260 |
+
|
| 261 |
+
This utility is used to format numbers for human consumption.
|
| 262 |
+
"""
|
| 263 |
+
time_unit = {-3: "ns", -2: "us", -1: "ms"}.get(int(torch.tensor(t).log10().item() // 3), "s")
|
| 264 |
+
time_scale = {"ns": 1e-9, "us": 1e-6, "ms": 1e-3, "s": 1}[time_unit]
|
| 265 |
+
return time_unit, time_scale
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def unit_to_english(u: str) -> str:
|
| 269 |
+
return {
|
| 270 |
+
"ns": "nanosecond",
|
| 271 |
+
"us": "microsecond",
|
| 272 |
+
"ms": "millisecond",
|
| 273 |
+
"s": "second",
|
| 274 |
+
}[u]
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
def trim_sigfig(x: float, n: int) -> float:
|
| 278 |
+
"""Trim `x` to `n` significant figures. (e.g. 3.14159, 2 -> 3.10000)"""
|
| 279 |
+
if n != int(n):
|
| 280 |
+
raise AssertionError("Number of significant figures must be an integer")
|
| 281 |
+
magnitude = int(torch.tensor(x).abs().log10().ceil().item())
|
| 282 |
+
scale = 10 ** (magnitude - n)
|
| 283 |
+
return float(torch.tensor(x / scale).round() * scale)
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
def ordered_unique(elements: Iterable[Any]) -> list[Any]:
|
| 287 |
+
return list(collections.OrderedDict(dict.fromkeys(elements)).keys())
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
@contextlib.contextmanager
|
| 291 |
+
def set_torch_threads(n: int) -> Iterator[None]:
|
| 292 |
+
prior_num_threads = torch.get_num_threads()
|
| 293 |
+
try:
|
| 294 |
+
torch.set_num_threads(n)
|
| 295 |
+
yield
|
| 296 |
+
finally:
|
| 297 |
+
torch.set_num_threads(prior_num_threads)
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
def _make_temp_dir(prefix: str | None = None, gc_dev_shm: bool = False) -> str:
|
| 301 |
+
"""Create a temporary directory. The caller is responsible for cleanup.
|
| 302 |
+
|
| 303 |
+
This function is conceptually similar to `tempfile.mkdtemp`, but with
|
| 304 |
+
the key additional feature that it will use shared memory if the
|
| 305 |
+
`BENCHMARK_USE_DEV_SHM` environment variable is set. This is an
|
| 306 |
+
implementation detail, but an important one for cases where many Callgrind
|
| 307 |
+
measurements are collected at once. (Such as when collecting
|
| 308 |
+
microbenchmarks.)
|
| 309 |
+
|
| 310 |
+
This is an internal utility, and is exported solely so that microbenchmarks
|
| 311 |
+
can reuse the util.
|
| 312 |
+
"""
|
| 313 |
+
use_dev_shm: bool = (os.getenv("BENCHMARK_USE_DEV_SHM") or "").lower() in ("1", "true")
|
| 314 |
+
if use_dev_shm:
|
| 315 |
+
root = "/dev/shm/pytorch_benchmark_utils"
|
| 316 |
+
if os.name != "posix":
|
| 317 |
+
raise AssertionError(f"tmpfs (/dev/shm) is POSIX only, current platform is {os.name}")
|
| 318 |
+
if not os.path.exists("/dev/shm"):
|
| 319 |
+
raise AssertionError("This system does not appear to support tmpfs (/dev/shm).")
|
| 320 |
+
os.makedirs(root, exist_ok=True)
|
| 321 |
+
|
| 322 |
+
# Because we're working in shared memory, it is more important than
|
| 323 |
+
# usual to clean up ALL intermediate files. However we don't want every
|
| 324 |
+
# worker to walk over all outstanding directories, so instead we only
|
| 325 |
+
# check when we are sure that it won't lead to contention.
|
| 326 |
+
if gc_dev_shm:
|
| 327 |
+
for i in os.listdir(root):
|
| 328 |
+
owner_file = os.path.join(root, i, "owner.pid")
|
| 329 |
+
if not os.path.exists(owner_file):
|
| 330 |
+
continue
|
| 331 |
+
|
| 332 |
+
with open(owner_file) as f:
|
| 333 |
+
owner_pid = int(f.read())
|
| 334 |
+
|
| 335 |
+
if owner_pid == os.getpid():
|
| 336 |
+
continue
|
| 337 |
+
|
| 338 |
+
try:
|
| 339 |
+
# https://stackoverflow.com/questions/568271/how-to-check-if-there-exists-a-process-with-a-given-pid-in-python
|
| 340 |
+
os.kill(owner_pid, 0)
|
| 341 |
+
|
| 342 |
+
except OSError:
|
| 343 |
+
print(f"Detected that {os.path.join(root, i)} was orphaned in shared memory. Cleaning up.")
|
| 344 |
+
shutil.rmtree(os.path.join(root, i))
|
| 345 |
+
|
| 346 |
+
else:
|
| 347 |
+
root = tempfile.gettempdir()
|
| 348 |
+
|
| 349 |
+
# We include the time so names sort by creation time, and add a UUID
|
| 350 |
+
# to ensure we don't collide.
|
| 351 |
+
name = f"{prefix or tempfile.gettempprefix()}__{int(time.time())}__{uuid.uuid4()}"
|
| 352 |
+
path = os.path.join(root, name)
|
| 353 |
+
os.makedirs(path, exist_ok=False)
|
| 354 |
+
|
| 355 |
+
if use_dev_shm:
|
| 356 |
+
with open(os.path.join(path, "owner.pid"), "w") as f:
|
| 357 |
+
f.write(str(os.getpid()))
|
| 358 |
+
|
| 359 |
+
return path
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/utils/benchmark/utils/compare.py
ADDED
|
@@ -0,0 +1,345 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
"""Display class to aggregate and print the results of many measurements."""
|
| 3 |
+
import collections
|
| 4 |
+
import enum
|
| 5 |
+
import itertools as it
|
| 6 |
+
|
| 7 |
+
from torch.utils.benchmark.utils import common
|
| 8 |
+
from torch import tensor as _tensor
|
| 9 |
+
import operator
|
| 10 |
+
|
| 11 |
+
__all__ = ["Colorize", "Compare"]
|
| 12 |
+
|
| 13 |
+
BEST = "\033[92m"
|
| 14 |
+
GOOD = "\033[34m"
|
| 15 |
+
BAD = "\033[2m\033[91m"
|
| 16 |
+
VERY_BAD = "\033[31m"
|
| 17 |
+
BOLD = "\033[1m"
|
| 18 |
+
TERMINATE = "\033[0m"
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class Colorize(enum.Enum):
|
| 22 |
+
NONE = "none"
|
| 23 |
+
COLUMNWISE = "columnwise"
|
| 24 |
+
ROWWISE = "rowwise"
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
# Classes to separate internal bookkeeping from what is rendered.
|
| 28 |
+
class _Column:
|
| 29 |
+
def __init__(
|
| 30 |
+
self,
|
| 31 |
+
grouped_results: list[tuple[common.Measurement | None, ...]],
|
| 32 |
+
time_scale: float,
|
| 33 |
+
time_unit: str,
|
| 34 |
+
trim_significant_figures: bool,
|
| 35 |
+
highlight_warnings: bool,
|
| 36 |
+
) -> None:
|
| 37 |
+
self._grouped_results = grouped_results
|
| 38 |
+
self._flat_results = [*it.chain.from_iterable(grouped_results)]
|
| 39 |
+
self._time_scale = time_scale
|
| 40 |
+
self._time_unit = time_unit
|
| 41 |
+
self._trim_significant_figures = trim_significant_figures
|
| 42 |
+
self._highlight_warnings = (
|
| 43 |
+
highlight_warnings
|
| 44 |
+
and any(r.has_warnings for r in self._flat_results if r)
|
| 45 |
+
)
|
| 46 |
+
leading_digits = [
|
| 47 |
+
int(_tensor(r.median / self._time_scale).log10().ceil()) if r else None
|
| 48 |
+
for r in self._flat_results
|
| 49 |
+
]
|
| 50 |
+
unit_digits = max(d for d in leading_digits if d is not None)
|
| 51 |
+
decimal_digits = min(
|
| 52 |
+
max(m.significant_figures - digits, 0)
|
| 53 |
+
for digits, m in zip(leading_digits, self._flat_results, strict=True)
|
| 54 |
+
if (m is not None) and (digits is not None)
|
| 55 |
+
) if self._trim_significant_figures else 1
|
| 56 |
+
length = unit_digits + decimal_digits + (1 if decimal_digits else 0)
|
| 57 |
+
self._template = f"{{:>{length}.{decimal_digits}f}}{{:>{7 if self._highlight_warnings else 0}}}"
|
| 58 |
+
|
| 59 |
+
def get_results_for(self, group):
|
| 60 |
+
return self._grouped_results[group]
|
| 61 |
+
|
| 62 |
+
def num_to_str(self, value: float | None, estimated_sigfigs: int, spread: float | None):
|
| 63 |
+
if value is None:
|
| 64 |
+
return " " * len(self.num_to_str(1, estimated_sigfigs, None))
|
| 65 |
+
|
| 66 |
+
if self._trim_significant_figures:
|
| 67 |
+
value = common.trim_sigfig(value, estimated_sigfigs)
|
| 68 |
+
|
| 69 |
+
return self._template.format(
|
| 70 |
+
value,
|
| 71 |
+
f" (! {spread * 100:.0f}%)" if self._highlight_warnings and spread is not None else "")
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def optional_min(seq):
|
| 75 |
+
l = list(seq)
|
| 76 |
+
return None if len(l) == 0 else min(l)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
class _Row:
|
| 80 |
+
def __init__(self, results, row_group, render_env, env_str_len,
|
| 81 |
+
row_name_str_len, time_scale, colorize, num_threads=None) -> None:
|
| 82 |
+
super().__init__()
|
| 83 |
+
self._results = results
|
| 84 |
+
self._row_group = row_group
|
| 85 |
+
self._render_env = render_env
|
| 86 |
+
self._env_str_len = env_str_len
|
| 87 |
+
self._row_name_str_len = row_name_str_len
|
| 88 |
+
self._time_scale = time_scale
|
| 89 |
+
self._colorize = colorize
|
| 90 |
+
self._columns: tuple[_Column, ...] = ()
|
| 91 |
+
self._num_threads = num_threads
|
| 92 |
+
|
| 93 |
+
def register_columns(self, columns: tuple[_Column, ...]) -> None:
|
| 94 |
+
self._columns = columns
|
| 95 |
+
|
| 96 |
+
def as_column_strings(self):
|
| 97 |
+
concrete_results = [r for r in self._results if r is not None]
|
| 98 |
+
env = f"({concrete_results[0].env})" if self._render_env else ""
|
| 99 |
+
env = env.ljust(self._env_str_len + 4)
|
| 100 |
+
output = [" " + env + concrete_results[0].as_row_name]
|
| 101 |
+
for m, col in zip(self._results, self._columns or (), strict=False):
|
| 102 |
+
if m is None:
|
| 103 |
+
output.append(col.num_to_str(None, 1, None))
|
| 104 |
+
else:
|
| 105 |
+
output.append(col.num_to_str(
|
| 106 |
+
m.median / self._time_scale,
|
| 107 |
+
m.significant_figures,
|
| 108 |
+
m.iqr / m.median if m.has_warnings else None
|
| 109 |
+
))
|
| 110 |
+
return output
|
| 111 |
+
|
| 112 |
+
@staticmethod
|
| 113 |
+
def color_segment(segment, value, best_value):
|
| 114 |
+
if value <= best_value * 1.01 or value <= best_value + 100e-9:
|
| 115 |
+
return BEST + BOLD + segment + TERMINATE * 2
|
| 116 |
+
if value <= best_value * 1.1:
|
| 117 |
+
return GOOD + BOLD + segment + TERMINATE * 2
|
| 118 |
+
if value >= best_value * 5:
|
| 119 |
+
return VERY_BAD + BOLD + segment + TERMINATE * 2
|
| 120 |
+
if value >= best_value * 2:
|
| 121 |
+
return BAD + segment + TERMINATE * 2
|
| 122 |
+
|
| 123 |
+
return segment
|
| 124 |
+
|
| 125 |
+
def row_separator(self, overall_width):
|
| 126 |
+
return (
|
| 127 |
+
[f"{self._num_threads} threads: ".ljust(overall_width, "-")]
|
| 128 |
+
if self._num_threads is not None else []
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
def finalize_column_strings(self, column_strings, col_widths):
|
| 132 |
+
best_values = [-1 for _ in column_strings]
|
| 133 |
+
if self._colorize == Colorize.ROWWISE:
|
| 134 |
+
row_min = min(r.median for r in self._results if r is not None)
|
| 135 |
+
best_values = [row_min for _ in column_strings]
|
| 136 |
+
elif self._colorize == Colorize.COLUMNWISE:
|
| 137 |
+
best_values = [
|
| 138 |
+
optional_min(r.median for r in column.get_results_for(self._row_group) if r is not None)
|
| 139 |
+
for column in (self._columns or ())
|
| 140 |
+
]
|
| 141 |
+
|
| 142 |
+
row_contents = [column_strings[0].ljust(col_widths[0])]
|
| 143 |
+
for col_str, width, result, best_value in zip(column_strings[1:], col_widths[1:], self._results, best_values, strict=False):
|
| 144 |
+
col_str = col_str.center(width)
|
| 145 |
+
if self._colorize != Colorize.NONE and result is not None and best_value is not None:
|
| 146 |
+
col_str = self.color_segment(col_str, result.median, best_value)
|
| 147 |
+
row_contents.append(col_str)
|
| 148 |
+
return row_contents
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
class Table:
|
| 152 |
+
def __init__(
|
| 153 |
+
self,
|
| 154 |
+
results: list[common.Measurement],
|
| 155 |
+
colorize: Colorize,
|
| 156 |
+
trim_significant_figures: bool,
|
| 157 |
+
highlight_warnings: bool
|
| 158 |
+
) -> None:
|
| 159 |
+
if len({r.label for r in results}) != 1:
|
| 160 |
+
raise AssertionError("All results must share the same label")
|
| 161 |
+
|
| 162 |
+
self.results = results
|
| 163 |
+
self._colorize = colorize
|
| 164 |
+
self._trim_significant_figures = trim_significant_figures
|
| 165 |
+
self._highlight_warnings = highlight_warnings
|
| 166 |
+
self.label = results[0].label
|
| 167 |
+
self.time_unit, self.time_scale = common.select_unit(
|
| 168 |
+
min(r.median for r in results)
|
| 169 |
+
)
|
| 170 |
+
|
| 171 |
+
self.row_keys = common.ordered_unique([self.row_fn(i) for i in results])
|
| 172 |
+
self.row_keys.sort(key=operator.itemgetter(slice(2))) # preserve stmt order
|
| 173 |
+
self.column_keys = common.ordered_unique([self.col_fn(i) for i in results])
|
| 174 |
+
self.rows, self.columns = self.populate_rows_and_columns()
|
| 175 |
+
|
| 176 |
+
@staticmethod
|
| 177 |
+
def row_fn(m: common.Measurement) -> tuple[int, str | None, str]:
|
| 178 |
+
return m.num_threads, m.env, m.as_row_name
|
| 179 |
+
|
| 180 |
+
@staticmethod
|
| 181 |
+
def col_fn(m: common.Measurement) -> str | None:
|
| 182 |
+
return m.description
|
| 183 |
+
|
| 184 |
+
def populate_rows_and_columns(self) -> tuple[tuple[_Row, ...], tuple[_Column, ...]]:
|
| 185 |
+
rows: list[_Row] = []
|
| 186 |
+
columns: list[_Column] = []
|
| 187 |
+
ordered_results: list[list[common.Measurement | None]] = [
|
| 188 |
+
[None for _ in self.column_keys]
|
| 189 |
+
for _ in self.row_keys
|
| 190 |
+
]
|
| 191 |
+
row_position = {key: i for i, key in enumerate(self.row_keys)}
|
| 192 |
+
col_position = {key: i for i, key in enumerate(self.column_keys)}
|
| 193 |
+
for r in self.results:
|
| 194 |
+
i = row_position[self.row_fn(r)]
|
| 195 |
+
j = col_position[self.col_fn(r)]
|
| 196 |
+
ordered_results[i][j] = r
|
| 197 |
+
|
| 198 |
+
unique_envs = {r.env for r in self.results}
|
| 199 |
+
render_env = len(unique_envs) > 1
|
| 200 |
+
env_str_len = max(len(i) for i in unique_envs) if render_env else 0
|
| 201 |
+
|
| 202 |
+
row_name_str_len = max(len(r.as_row_name) for r in self.results)
|
| 203 |
+
|
| 204 |
+
prior_num_threads = -1
|
| 205 |
+
prior_env = ""
|
| 206 |
+
row_group = -1
|
| 207 |
+
rows_by_group: list[list[list[common.Measurement | None]]] = []
|
| 208 |
+
for (num_threads, env, _), row in zip(self.row_keys, ordered_results, strict=True):
|
| 209 |
+
thread_transition = (num_threads != prior_num_threads)
|
| 210 |
+
if thread_transition:
|
| 211 |
+
prior_num_threads = num_threads
|
| 212 |
+
prior_env = ""
|
| 213 |
+
row_group += 1
|
| 214 |
+
rows_by_group.append([])
|
| 215 |
+
rows.append(
|
| 216 |
+
_Row(
|
| 217 |
+
results=row,
|
| 218 |
+
row_group=row_group,
|
| 219 |
+
render_env=(render_env and env != prior_env),
|
| 220 |
+
env_str_len=env_str_len,
|
| 221 |
+
row_name_str_len=row_name_str_len,
|
| 222 |
+
time_scale=self.time_scale,
|
| 223 |
+
colorize=self._colorize,
|
| 224 |
+
num_threads=num_threads if thread_transition else None,
|
| 225 |
+
)
|
| 226 |
+
)
|
| 227 |
+
rows_by_group[-1].append(row)
|
| 228 |
+
prior_env = env
|
| 229 |
+
|
| 230 |
+
for i in range(len(self.column_keys)):
|
| 231 |
+
grouped_results = [tuple(row[i] for row in g) for g in rows_by_group]
|
| 232 |
+
column = _Column(
|
| 233 |
+
grouped_results=grouped_results,
|
| 234 |
+
time_scale=self.time_scale,
|
| 235 |
+
time_unit=self.time_unit,
|
| 236 |
+
trim_significant_figures=self._trim_significant_figures,
|
| 237 |
+
highlight_warnings=self._highlight_warnings,)
|
| 238 |
+
columns.append(column)
|
| 239 |
+
|
| 240 |
+
rows_tuple, columns_tuple = tuple(rows), tuple(columns)
|
| 241 |
+
for ri in rows_tuple:
|
| 242 |
+
ri.register_columns(columns_tuple)
|
| 243 |
+
return rows_tuple, columns_tuple
|
| 244 |
+
|
| 245 |
+
def render(self) -> str:
|
| 246 |
+
string_rows = [[""] + self.column_keys]
|
| 247 |
+
string_rows.extend(r.as_column_strings() for r in self.rows)
|
| 248 |
+
num_cols = max(len(i) for i in string_rows)
|
| 249 |
+
for sr in string_rows:
|
| 250 |
+
sr.extend(["" for _ in range(num_cols - len(sr))])
|
| 251 |
+
|
| 252 |
+
col_widths = [max(len(j) for j in i) for i in zip(*string_rows, strict=True)]
|
| 253 |
+
finalized_columns = [" | ".join(i.center(w) for i, w in zip(string_rows[0], col_widths, strict=True))]
|
| 254 |
+
overall_width = len(finalized_columns[0])
|
| 255 |
+
for string_row, row in zip(string_rows[1:], self.rows, strict=True):
|
| 256 |
+
finalized_columns.extend(row.row_separator(overall_width))
|
| 257 |
+
finalized_columns.append(" | ".join(row.finalize_column_strings(string_row, col_widths)))
|
| 258 |
+
|
| 259 |
+
newline = "\n"
|
| 260 |
+
has_warnings = self._highlight_warnings and any(ri.has_warnings for ri in self.results)
|
| 261 |
+
return f"""
|
| 262 |
+
[{(' ' + (self.label or '') + ' ').center(overall_width - 2, '-')}]
|
| 263 |
+
{newline.join(finalized_columns)}
|
| 264 |
+
|
| 265 |
+
Times are in {common.unit_to_english(self.time_unit)}s ({self.time_unit}).
|
| 266 |
+
{'(! XX%) Measurement has high variance, where XX is the IQR / median * 100.' + newline if has_warnings else ""}"""[1:]
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
class Compare:
|
| 270 |
+
"""Helper class for displaying the results of many measurements in a
|
| 271 |
+
formatted table.
|
| 272 |
+
|
| 273 |
+
The table format is based on the information fields provided in
|
| 274 |
+
:class:`torch.utils.benchmark.Timer` (`description`, `label`, `sub_label`,
|
| 275 |
+
`num_threads`, etc).
|
| 276 |
+
|
| 277 |
+
The table can be directly printed using :meth:`print` or casted as a `str`.
|
| 278 |
+
|
| 279 |
+
For a full tutorial on how to use this class, see:
|
| 280 |
+
https://pytorch.org/tutorials/recipes/recipes/benchmark.html
|
| 281 |
+
|
| 282 |
+
Args:
|
| 283 |
+
results: List of Measurement to display.
|
| 284 |
+
"""
|
| 285 |
+
def __init__(self, results: list[common.Measurement]) -> None:
|
| 286 |
+
self._results: list[common.Measurement] = []
|
| 287 |
+
self.extend_results(results)
|
| 288 |
+
self._trim_significant_figures = False
|
| 289 |
+
self._colorize = Colorize.NONE
|
| 290 |
+
self._highlight_warnings = False
|
| 291 |
+
|
| 292 |
+
def __str__(self) -> str:
|
| 293 |
+
return "\n".join(self._render())
|
| 294 |
+
|
| 295 |
+
def extend_results(self, results) -> None:
|
| 296 |
+
"""Append results to already stored ones.
|
| 297 |
+
|
| 298 |
+
All added results must be instances of ``Measurement``.
|
| 299 |
+
"""
|
| 300 |
+
for r in results:
|
| 301 |
+
if not isinstance(r, common.Measurement):
|
| 302 |
+
raise ValueError(
|
| 303 |
+
"Expected an instance of `Measurement`, " f"got {type(r)} instead."
|
| 304 |
+
)
|
| 305 |
+
self._results.extend(results)
|
| 306 |
+
|
| 307 |
+
def trim_significant_figures(self) -> None:
|
| 308 |
+
"""Enables trimming of significant figures when building the formatted table."""
|
| 309 |
+
self._trim_significant_figures = True
|
| 310 |
+
|
| 311 |
+
def colorize(self, rowwise=False) -> None:
|
| 312 |
+
"""Colorize formatted table.
|
| 313 |
+
|
| 314 |
+
Colorize columnwise by default.
|
| 315 |
+
"""
|
| 316 |
+
self._colorize = Colorize.ROWWISE if rowwise else Colorize.COLUMNWISE
|
| 317 |
+
|
| 318 |
+
def highlight_warnings(self) -> None:
|
| 319 |
+
"""Enables warning highlighting when building formatted table."""
|
| 320 |
+
self._highlight_warnings = True
|
| 321 |
+
|
| 322 |
+
def print(self) -> None:
|
| 323 |
+
"""Print formatted table"""
|
| 324 |
+
print(str(self))
|
| 325 |
+
|
| 326 |
+
def _render(self):
|
| 327 |
+
results = common.Measurement.merge(self._results)
|
| 328 |
+
grouped_results = self._group_by_label(results)
|
| 329 |
+
output = [self._layout(group) for group in grouped_results.values()]
|
| 330 |
+
return output
|
| 331 |
+
|
| 332 |
+
def _group_by_label(self, results: list[common.Measurement]):
|
| 333 |
+
grouped_results: collections.defaultdict[str, list[common.Measurement]] = collections.defaultdict(list)
|
| 334 |
+
for r in results:
|
| 335 |
+
grouped_results[r.label].append(r)
|
| 336 |
+
return grouped_results
|
| 337 |
+
|
| 338 |
+
def _layout(self, results: list[common.Measurement]):
|
| 339 |
+
table = Table(
|
| 340 |
+
results,
|
| 341 |
+
self._colorize,
|
| 342 |
+
self._trim_significant_figures,
|
| 343 |
+
self._highlight_warnings
|
| 344 |
+
)
|
| 345 |
+
return table.render()
|